diff --git a/README.md b/README.md index 78da997..d2c7fd8 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,10 @@ decodes `data`, which can be either a buffer or array of integers, from position if you also require the length (number of bytes) that were required to decode the integer you can access it via `varint.decode.bytesRead`. this is an integer property that will tell you the number of bytes that the last .decode() call had to use to decode. +### varint.encode.bytesWritten + +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. + ## 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/encode.js b/encode.js index e2e2e36..3320033 100644 --- a/encode.js +++ b/encode.js @@ -7,11 +7,15 @@ var MSB = 0x80 function encode(num, out, offset) { out = out || [] offset = offset || 0 + var oldOffset = offset while(num & MSBALL) { out[offset++] = (num & 0xFF) | MSB num >>>= 7 } out[offset] = num + + encode.bytesWritten = offset - oldOffset + 1 + return out } diff --git a/test.js b/test.js index 58bd670..12f2e8f 100644 --- a/test.js +++ b/test.js @@ -60,12 +60,14 @@ test('test decode multiple bytes with zero', function(assert) { test('encode single byte', function(assert) { var expected = randint(parseInt('1111111', '2')) assert.deepEqual(encode(expected), [expected]) + assert.equal(encode.bytesWritten, 1) assert.end() }) test('encode multiple byte with zero first byte', function(assert) { var expected = 0x0F00 assert.deepEqual(encode(expected), [0x80, 0x1E]) + assert.equal(encode.bytesWritten, 2) assert.end() })