diff --git a/README.md b/README.md index d2c7fd8..df72382 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,11 @@ if you also require the length (number of bytes) that were required to decode th similar to `bytesRead` when encoding a number it can be useful to know how many bytes where written (especially if you pass an output array). you can access this via `varint.encode.bytesWritten` which holds the number of bytes written in the last encode. + +### varint.encodingLength(num) + +returns the number of bytes this number will be encoded as, up to a maximum of 8. + ## usage notes if you are using this to decode buffers from a streaming source it's up to you to make sure that you send 'complete' buffers into `varint.decode`. the maximum number of bytes that varint will need to decode is 8, so all you have to do is make sure you are sending buffers that are at least 8 bytes long from the point at which you know a varint range begins. diff --git a/index.js b/index.js index 1c4e803..a27770c 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,5 @@ module.exports = { encode: require('./encode.js') , decode: require('./decode.js') -} \ No newline at end of file + , encodingLength: require('./length.js') +} diff --git a/length.js b/length.js new file mode 100644 index 0000000..b3b26e0 --- /dev/null +++ b/length.js @@ -0,0 +1,21 @@ + +var N1 = Math.pow(2, 7) +var N2 = Math.pow(2, 14) +var N3 = Math.pow(2, 21) +var N4 = Math.pow(2, 28) +var N5 = Math.pow(2, 35) +var N6 = Math.pow(2, 42) +var N7 = Math.pow(2, 49) + +module.exports = function (value) { + return ( + value < N1 ? 1 + : value < N2 ? 2 + : value < N3 ? 3 + : value < N4 ? 4 + : value < N5 ? 5 + : value < N6 ? 6 + : value < N7 ? 7 + : 8 + ) +} diff --git a/test.js b/test.js index 0769851..4c5f51d 100644 --- a/test.js +++ b/test.js @@ -2,6 +2,7 @@ var varint = require('./index') , test = require('tape') , decode = varint.decode , encode = varint.encode + , encodingLength = varint.encodingLength test('fuzz test', function(assert) { var expect @@ -106,6 +107,15 @@ test('fuzz test - big', function(assert) { assert.end() }) +test('encodingLength', function (assert) { + + for(var i = 0; i <= 53; i++) { + var n = Math.pow(2, i) + assert.equal(encode(n).length, encodingLength(n)) + } + + assert.end() +}) function randint(range) { return Math.floor(Math.random() * range)