BigInt.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. 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. vm.throw_exception<RangeError>(global_object, ErrorType::BigIntFromNonIntegral);
  35. return {};
  36. }
  37. // 2. Return the BigInt value that represents ℝ(number).
  38. return js_bigint(vm, Crypto::SignedBigInteger::create_from((i64)number.as_double()));
  39. }
  40. }