From 0c6bcac9978fc6a2b4dd27a681fb5dfabc890b1f Mon Sep 17 00:00:00 2001 From: George Roman <30772943+georgeroman@users.noreply.github.com> Date: Fri, 16 Oct 2020 12:54:51 +0300 Subject: [PATCH] Support more number literals in BigInt's from string constructor (#880) --- boa/src/builtins/bigint/conversions.rs | 24 +++++++++++++++++++----- boa/src/builtins/bigint/tests.rs | 4 ++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/boa/src/builtins/bigint/conversions.rs b/boa/src/builtins/bigint/conversions.rs index 88494ad0a5..6cdb1f14f2 100644 --- a/boa/src/builtins/bigint/conversions.rs +++ b/boa/src/builtins/bigint/conversions.rs @@ -14,15 +14,29 @@ impl BigInt { /// /// [spec]: https://tc39.es/ecma262/#sec-stringtobigint #[inline] - pub(crate) fn from_string(string: &str, _ctx: &mut Context) -> Result { - if string.is_empty() { + pub(crate) fn from_string(string: &str, context: &mut Context) -> Result { + if string.trim().is_empty() { return Ok(BigInt::from(0)); } - match num_bigint::BigInt::from_str(string) { - Ok(bigint) => Ok(Self(bigint)), - _ => panic!("SyntaxError: cannot convert {} to a BigInt", string), + let mut radix = 10; + let mut string = 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. diff --git a/boa/src/builtins/bigint/tests.rs b/boa/src/builtins/bigint/tests.rs index 0a7f21113c..0fdf2e52df 100644 --- a/boa/src/builtins/bigint/tests.rs +++ b/boa/src/builtins/bigint/tests.rs @@ -133,6 +133,7 @@ fn bigint_function_conversion_from_string() { 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('200000000000000000')"), "200000000000000000n" @@ -141,6 +142,9 @@ fn bigint_function_conversion_from_string() { forward(&mut engine, "BigInt('1000000000000000000000000000000000')"), "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]