BigInt.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCrypto/BigInt/SignedBigInteger.h>
  7. #include <LibJS/Heap/Heap.h>
  8. #include <LibJS/Runtime/BigInt.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. namespace JS {
  11. JS_DEFINE_ALLOCATOR(BigInt);
  12. NonnullGCPtr<BigInt> BigInt::create(VM& vm, Crypto::SignedBigInteger big_integer)
  13. {
  14. return vm.heap().allocate<BigInt>(move(big_integer));
  15. }
  16. BigInt::BigInt(Crypto::SignedBigInteger big_integer)
  17. : m_big_integer(move(big_integer))
  18. {
  19. VERIFY(!m_big_integer.is_invalid());
  20. }
  21. ErrorOr<String> BigInt::to_string() const
  22. {
  23. return String::formatted("{}n", TRY(m_big_integer.to_base(10)));
  24. }
  25. // 21.2.1.1.1 NumberToBigInt ( number ), https://tc39.es/ecma262/#sec-numbertobigint
  26. ThrowCompletionOr<BigInt*> number_to_bigint(VM& vm, Value number)
  27. {
  28. VERIFY(number.is_number());
  29. // 1. If IsIntegralNumber(number) is false, throw a RangeError exception.
  30. if (!number.is_integral_number())
  31. return vm.throw_completion<RangeError>(ErrorType::BigIntFromNonIntegral);
  32. // 2. Return the BigInt value that represents ℝ(number).
  33. return BigInt::create(vm, Crypto::SignedBigInteger { number.as_double() }).ptr();
  34. }
  35. }