Merge pull request #7 from dominictarr/encoding-length

Encoding length
master
Chris Dickinson 10 years ago
commit c6a6a844c5

@ -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.

@ -1,4 +1,5 @@
module.exports = {
encode: require('./encode.js')
, decode: require('./decode.js')
}
, encodingLength: require('./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
)
}

@ -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)

Loading…
Cancel
Save