From 5f2e9840fa9cebd11f550b94174f9668b2650ee7 Mon Sep 17 00:00:00 2001 From: jakobkummerow Date: Thu, 12 Aug 2021 12:33:41 +0200 Subject: [PATCH] Throw a few more errors for invalid inputs (#65) Fixes #39. --- jsbi.mjs | 10 +++++++++- tests/tests.mjs | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/jsbi.mjs b/jsbi.mjs index 6189711..4b81d33 100644 --- a/jsbi.mjs +++ b/jsbi.mjs @@ -399,6 +399,10 @@ class JSBI extends Array { static asIntN(n, x) { if (x.length === 0) return x; n = Math.floor(n); + if (n < 0) { + throw new RangeError( + 'Invalid value: not (convertible to) a safe integer'); + } if (n === 0) return JSBI.__zero(); // If {x} has less than {n} bits, return it directly. if (n >= JSBI.__kMaxLengthBits) return x; @@ -426,6 +430,10 @@ class JSBI extends Array { static asUintN(n, x) { if (x.length === 0) return x; n = Math.floor(n); + if (n < 0) { + throw new RangeError( + 'Invalid value: not (convertible to) a safe integer'); + } if (n === 0) return JSBI.__zero(); // If {x} is negative, simulate two's complement representation. if (x.sign) { @@ -711,6 +719,7 @@ class JSBI extends Array { } } } + if (sign !== 0 && radix !== 10) return null; // Skip leading zeros. while (current === 0x30) { leadingZero = true; @@ -809,7 +818,6 @@ class JSBI extends Array { } // Get result. - if (sign !== 0 && radix !== 10) return null; result.sign = (sign === -1); return result.__trim(); } diff --git a/tests/tests.mjs b/tests/tests.mjs index 8d3d1fc..5730c8a 100644 --- a/tests/tests.mjs +++ b/tests/tests.mjs @@ -83,7 +83,8 @@ const TESTS = [ // https://github.com/GoogleChromeLabs/jsbi/issues/36 (function() { const VALID = ['123', ' 123 ', ' 123 ']; - const INVALID = ['x123', 'x 123', ' 123x', '123 x', '123 xx', '123 ?a']; + const INVALID = ['x123', 'x 123', ' 123x', '123 x', '123 xx', '123 ?a', + '-0o0', '-0x0', '-0b0', '-0x1']; for (const v of VALID) { const result = JSBI.BigInt(v); console.assert(JSBI.equal(result, JSBI.BigInt(123)));