Skip to content

Commit

Permalink
Merge pull request #6 from dominictarr/master
Browse files Browse the repository at this point in the history
support for numbers up to 9 QUADRILLION!
  • Loading branch information
chrisdickinson committed May 9, 2014
2 parents 566d0f0 + d51a128 commit a974285
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
9 changes: 7 additions & 2 deletions encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,22 @@ module.exports = encode
var MSB = 0x80
, REST = 0x7F
, MSBALL = ~REST
, INT = Math.pow(2, 31)

function encode(num, out, offset) {
out = out || []
offset = offset || 0
var oldOffset = offset

while(num >= INT) {
out[offset++] = (num & 0xFF) | MSB
num /= 128
}
while(num & MSBALL) {
out[offset++] = (num & 0xFF) | MSB
out[offset++] = (num & 0xFF) | MSB
num >>>= 7
}
out[offset] = num
out[offset] = num | 0

encode.bytesWritten = offset - oldOffset + 1

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@
"author": "Chris Dickinson <chris@neversaw.us>",
"license": "MIT",
"devDependencies": {
"tape": "~0.2.2"
"tape": "~2.12.3"
}
}
}
38 changes: 37 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,42 @@ test('encode multiple byte with zero first byte', function(assert) {
assert.end()
})

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) {
var data = encode(n)
console.error(n, '->', data)
assert.equal(decode(data), n)
assert.notEqual(decode(data), n - 1)
})
assert.end()
})

test('fuzz test - big', function(assert) {
var expect
, encoded

var MAX_INTD = Math.pow(2, 55)
var MAX_INT = Math.pow(2, 31)

for(var i = 0, len = 100; i < len; ++i) {
expect = randint(MAX_INTD - MAX_INT) + MAX_INT
encoded = encode(expect)
var data = decode(encoded)
assert.equal(expect, data, 'fuzz test: ' + expect.toString())
assert.equal(decode.bytesRead, encoded.length)
}

assert.end()
})


function randint(range) {
return ~~(Math.random() * range)
return Math.floor(Math.random() * range)
}

0 comments on commit a974285

Please sign in to comment.