BigInt.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (c) 2020-2021, 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. BigInt::BigInt(Crypto::SignedBigInteger big_integer)
  12. : m_big_integer(move(big_integer))
  13. {
  14. VERIFY(!m_big_integer.is_invalid());
  15. }
  16. BigInt::~BigInt()
  17. {
  18. }
  19. BigInt* js_bigint(Heap& heap, Crypto::SignedBigInteger big_integer)
  20. {
  21. return heap.allocate_without_global_object<BigInt>(move(big_integer));
  22. }
  23. BigInt* js_bigint(VM& vm, Crypto::SignedBigInteger big_integer)
  24. {
  25. return js_bigint(vm.heap(), move(big_integer));
  26. }
  27. // 21.2.1.1.1 NumberToBigInt ( number ), https://tc39.es/ecma262/#sec-numbertobigint
  28. ThrowCompletionOr<BigInt*> number_to_bigint(GlobalObject& global_object, Value number)
  29. {
  30. VERIFY(number.is_number());
  31. auto& vm = global_object.vm();
  32. // 1. If IsIntegralNumber(number) is false, throw a RangeError exception.
  33. if (!number.is_integral_number())
  34. return vm.throw_completion<RangeError>(global_object, ErrorType::BigIntFromNonIntegral);
  35. // 2. Return the BigInt value that represents ℝ(number).
  36. return js_bigint(vm, Crypto::SignedBigInteger::create_from((i64)number.as_double()));
  37. }
  38. }