Skip to content

Commit

Permalink
Throw a few more errors for invalid inputs (#65)
Browse files Browse the repository at this point in the history
Fixes #39.
  • Loading branch information
jakobkummerow authored Aug 12, 2021
1 parent 596c0d6 commit 5f2e984
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
10 changes: 9 additions & 1 deletion jsbi.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -711,6 +719,7 @@ class JSBI extends Array {
}
}
}
if (sign !== 0 && radix !== 10) return null;
// Skip leading zeros.
while (current === 0x30) {
leadingZero = true;
Expand Down Expand Up @@ -809,7 +818,6 @@ class JSBI extends Array {
}

// Get result.
if (sign !== 0 && radix !== 10) return null;
result.sign = (sign === -1);
return result.__trim();
}
Expand Down
3 changes: 2 additions & 1 deletion tests/tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
Expand Down

0 comments on commit 5f2e984

Please sign in to comment.