BigInt.cpp 1.3 KB

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