diff --git a/README.md b/README.md index be59be7..1b84062 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ encode whole numbers to an array of [protobuf-style varint bytes](https://develo var varint = require('varint') var bytes = varint.encode(300) // === [0xAC, 0x02] -varint.decode(bytes) // 300 +varint.decode(bytes) // [300, 2] ``` ## api @@ -18,9 +18,9 @@ varint.decode(bytes) // 300 encodes `num` into either the array given by `offset` or a new array at `offset` and returns that array filled with integers. -### varint.decode(data[, offset=0]) -> number +### varint.decode(data[, offset=0]) -> [number, length] -decodes `data`, which can be either a buffer or array of integers, from position `offset` or default 0 and returns the decoded integer +decodes `data`, which can be either a buffer or array of integers, from position `offset` or default 0 and returns an array containing `[number, length]` where number is the original integer and length is the amount of bytes that were consumed in order to decode the number # License diff --git a/decode.js b/decode.js index 3ed365e..8a5fb17 100644 --- a/decode.js +++ b/decode.js @@ -7,15 +7,16 @@ function read(buf, offset) { var res = 0 , offset = offset || 0 , shift = 0 + , counter = offset , b do { - b = buf[offset++] + b = buf[counter++] res += shift < 28 ? (b & REST) << shift : (b & REST) * Math.pow(2, shift) shift += 7 } while (b >= MSB) - return res + return [res, counter - offset] } diff --git a/test.js b/test.js index 2acb9ff..9427952 100644 --- a/test.js +++ b/test.js @@ -9,7 +9,8 @@ test('fuzz test', function(assert) { expect = randint(0x7FFFFFFF) encoded = varint.encode(expect) var data = varint.decode(encoded) - assert.equal(expect, data, 'fuzz test: '+expect.toString()) + assert.equal(expect, data[0], 'fuzz test: '+expect.toString()) + assert.equal(data[1], encoded.length) } assert.end() @@ -20,7 +21,8 @@ test('test single byte works as expected', function(assert) { buf[0] = 172 buf[1] = 2 var data = varint.decode(buf) - assert.equal(data, 300, 'should equal 300') + assert.equal(data[0], 300, 'should equal 300') + assert.equal(data[1], 2) assert.end() }) @@ -37,7 +39,8 @@ test('test decode single bytes', function(assert) { var buf = new Uint8Array(1) buf[0] = expected var data = varint.decode(buf) - assert.equal(data, expected) + assert.equal(data[0], expected) + assert.equal(data[1], 1) assert.end() }) @@ -47,7 +50,8 @@ test('test decode multiple bytes with zero', function(assert) { buf[0] = 128 buf[1] = expected var data = varint.decode(buf) - assert.equal(data, expected << 7) + assert.equal(data[0], expected << 7) + assert.equal(data[1], 2) assert.end() })