2020-06-05 21:14:10 -03:00
|
|
|
|
/*
|
2022-08-16 16:33:17 -03:00
|
|
|
|
* Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
|
2020-06-05 21:14:10 -03:00
|
|
|
|
*
|
2021-04-22 05:24:48 -03:00
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-06-05 21:14:10 -03:00
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
#include <LibCrypto/BigInt/SignedBigInteger.h>
|
2024-11-14 12:01:23 -03:00
|
|
|
|
#include <LibGC/Heap.h>
|
2020-06-05 21:14:10 -03:00
|
|
|
|
#include <LibJS/Runtime/BigInt.h>
|
2021-07-07 20:30:56 -03:00
|
|
|
|
#include <LibJS/Runtime/GlobalObject.h>
|
2020-06-05 21:14:10 -03:00
|
|
|
|
|
|
|
|
|
|
namespace JS {
|
|
|
|
|
|
|
2024-11-14 12:01:23 -03:00
|
|
|
|
GC_DEFINE_ALLOCATOR(BigInt);
|
2023-11-19 05:45:05 -03:00
|
|
|
|
|
2024-11-14 12:01:23 -03:00
|
|
|
|
GC::Ref<BigInt> BigInt::create(VM& vm, Crypto::SignedBigInteger big_integer)
|
2020-06-05 21:14:10 -03:00
|
|
|
|
{
|
2024-11-13 14:13:46 -03:00
|
|
|
|
return vm.heap().allocate<BigInt>(move(big_integer));
|
2020-06-05 21:14:10 -03:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-12-06 19:03:52 -03:00
|
|
|
|
BigInt::BigInt(Crypto::SignedBigInteger big_integer)
|
|
|
|
|
|
: m_big_integer(move(big_integer))
|
2021-08-02 20:14:48 -03:00
|
|
|
|
{
|
2022-12-06 19:03:52 -03:00
|
|
|
|
VERIFY(!m_big_integer.is_invalid());
|
2021-08-02 20:14:48 -03:00
|
|
|
|
}
|
|
|
|
|
|
|
2023-02-12 23:03:11 -03:00
|
|
|
|
ErrorOr<String> BigInt::to_string() const
|
|
|
|
|
|
{
|
|
|
|
|
|
return String::formatted("{}n", TRY(m_big_integer.to_base(10)));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2021-07-07 20:30:56 -03:00
|
|
|
|
// 21.2.1.1.1 NumberToBigInt ( number ), https://tc39.es/ecma262/#sec-numbertobigint
|
2024-11-24 11:50:02 -03:00
|
|
|
|
ThrowCompletionOr<GC::Ref<BigInt>> number_to_bigint(VM& vm, Value number)
|
2021-07-07 20:30:56 -03:00
|
|
|
|
{
|
|
|
|
|
|
VERIFY(number.is_number());
|
|
|
|
|
|
|
|
|
|
|
|
// 1. If IsIntegralNumber(number) is false, throw a RangeError exception.
|
2021-10-22 21:26:55 -03:00
|
|
|
|
if (!number.is_integral_number())
|
2022-08-16 16:33:17 -03:00
|
|
|
|
return vm.throw_completion<RangeError>(ErrorType::BigIntFromNonIntegral);
|
2021-07-07 20:30:56 -03:00
|
|
|
|
|
|
|
|
|
|
// 2. Return the BigInt value that represents ℝ(number).
|
2024-11-24 11:50:02 -03:00
|
|
|
|
return BigInt::create(vm, Crypto::SignedBigInteger { number.as_double() });
|
2021-07-07 20:30:56 -03:00
|
|
|
|
}
|
|
|
|
|
|
|
2020-06-05 21:14:10 -03:00
|
|
|
|
}
|