Revert "Revert "add bounds checking to encode and decode""

This reverts commit 614645bb03.
master
Chris Dickinson 4 years ago
parent fbcfa76d76
commit 4234244a96

@ -12,7 +12,7 @@ function read(buf, offset) {
, l = buf.length
do {
if (counter >= l) {
if (counter >= l || shift > 49) {
read.bytes = 0
throw new RangeError('Could not decode varint')
}

@ -6,6 +6,10 @@ var MSB = 0x80
, INT = Math.pow(2, 31)
function encode(num, out, offset) {
if (num > Number.MAX_SAFE_INTEGER) {
encode.bytes = 0
throw new RangeError('Could not encode varint')
}
out = out || []
offset = offset || 0
var oldOffset = offset

@ -77,7 +77,6 @@ test('big integers', function (assert) {
var bigs = []
for(var i = 32; i <= 53; i++) (function (i) {
bigs.push(Math.pow(2, i) - 1)
bigs.push(Math.pow(2, i))
})(i)
bigs.forEach(function (n) {
@ -93,7 +92,7 @@ test('fuzz test - big', function(assert) {
var expect
, encoded
var MAX_INTD = Math.pow(2, 55)
var MAX_INTD = Number.MAX_SAFE_INTEGER
var MAX_INT = Math.pow(2, 31)
for(var i = 0, len = 100; i < len; ++i) {
@ -110,7 +109,7 @@ test('fuzz test - big', function(assert) {
test('encodingLength', function (assert) {
for(var i = 0; i <= 53; i++) {
var n = Math.pow(2, i)
var n = Math.pow(2, i) - 1
assert.equal(encode(n).length, encodingLength(n))
}
@ -134,6 +133,24 @@ test('buffer too short', function (assert) {
assert.end()
})
test('buffer too long', function (assert) {
var buffer = Uint8Array.from(
Array.from({length: 150}, function () { return 0xff })
.concat(Array.from({length: 1}, function () { return 0x1 }))
)
try {
var val = decode(buffer)
encode(val)
assert.fail('expected an error received value instead: ' + val)
} catch (err) {
assert.equal(err.constructor, RangeError)
assert.equal(decode.bytes, 0)
}
assert.end()
})
function randint(range) {
return Math.floor(Math.random() * range)
}

Loading…
Cancel
Save