Browse Source

Support more number literals in BigInt's from string constructor (#880)

pull/881/head
George Roman 4 years ago committed by GitHub
parent
commit
0c6bcac997
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 24
      boa/src/builtins/bigint/conversions.rs
  2. 4
      boa/src/builtins/bigint/tests.rs

24
boa/src/builtins/bigint/conversions.rs

@ -14,15 +14,29 @@ impl BigInt {
/// ///
/// [spec]: https://tc39.es/ecma262/#sec-stringtobigint /// [spec]: https://tc39.es/ecma262/#sec-stringtobigint
#[inline] #[inline]
pub(crate) fn from_string(string: &str, _ctx: &mut Context) -> Result<Self, Value> { pub(crate) fn from_string(string: &str, context: &mut Context) -> Result<Self, Value> {
if string.is_empty() { if string.trim().is_empty() {
return Ok(BigInt::from(0)); return Ok(BigInt::from(0));
} }
match num_bigint::BigInt::from_str(string) { let mut radix = 10;
Ok(bigint) => Ok(Self(bigint)), let mut string = string;
_ => panic!("SyntaxError: cannot convert {} to a BigInt", string), if string.starts_with("0b") || string.starts_with("0B") {
radix = 2;
string = &string[2..];
}
if string.starts_with("0x") || string.starts_with("0X") {
radix = 16;
string = &string[2..];
} }
if string.starts_with("0o") || string.starts_with("0O") {
radix = 8;
string = &string[2..];
}
BigInt::from_string_radix(string, radix).ok_or_else(|| {
context.construct_syntax_error(format!("cannot convert {} to a BigInt", string))
})
} }
/// Converts a string to a BigInt with the specified radix. /// Converts a string to a BigInt with the specified radix.

4
boa/src/builtins/bigint/tests.rs

@ -132,6 +132,7 @@ fn bigint_function_conversion_from_undefined() {
fn bigint_function_conversion_from_string() { fn bigint_function_conversion_from_string() {
let mut engine = Context::new(); let mut engine = Context::new();
assert_eq!(forward(&mut engine, "BigInt('')"), "0n");
assert_eq!(forward(&mut engine, "BigInt(' ')"), "0n"); assert_eq!(forward(&mut engine, "BigInt(' ')"), "0n");
assert_eq!( assert_eq!(
forward(&mut engine, "BigInt('200000000000000000')"), forward(&mut engine, "BigInt('200000000000000000')"),
@ -141,6 +142,9 @@ fn bigint_function_conversion_from_string() {
forward(&mut engine, "BigInt('1000000000000000000000000000000000')"), forward(&mut engine, "BigInt('1000000000000000000000000000000000')"),
"1000000000000000000000000000000000n" "1000000000000000000000000000000000n"
); );
assert_eq!(forward(&mut engine, "BigInt('0b1111')"), "15n");
assert_eq!(forward(&mut engine, "BigInt('0o70')"), "56n");
assert_eq!(forward(&mut engine, "BigInt('0xFF')"), "255n");
} }
#[test] #[test]

Loading…
Cancel
Save