From d363956ba1f2a27262691619cbc1853e4c482ab5 Mon Sep 17 00:00:00 2001 From: "Ryan X. Charles" Date: Mon, 15 Sep 2014 14:27:42 -0700 Subject: [PATCH] add readVarIntBuf function ...will be useful for new Varint class --- lib/bufferreader.js | 14 ++++++++++++++ test/bufferreader.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/lib/bufferreader.js b/lib/bufferreader.js index 21fea1a..7ce44a3 100644 --- a/lib/bufferreader.js +++ b/lib/bufferreader.js @@ -98,6 +98,20 @@ BufferReader.prototype.readVarIntNum = function() { } }; +BufferReader.prototype.readVarIntBuf = function() { + var first = this.buf.readUInt8(this.pos); + switch (first) { + case 0xFD: + return this.buffer(1 + 2);; + case 0xFE: + return this.buffer(1 + 4); + case 0xFF: + return this.buffer(1 + 8); + default: + return this.buffer(1); + } +}; + BufferReader.prototype.readVarIntBN = function() { var first = this.readUInt8(); switch (first) { diff --git a/test/bufferreader.js b/test/bufferreader.js index 2c9adf2..862bd96 100644 --- a/test/bufferreader.js +++ b/test/bufferreader.js @@ -168,6 +168,35 @@ describe('BufferReader', function() { }); + describe('#readVarIntBuf', function() { + + it('should read a 1 byte varint', function() { + var buf = new Buffer([50]); + var br = new BufferReader({buf: buf}); + br.readVarIntBuf().length.should.equal(1); + }); + + it('should read a 3 byte varint', function() { + var buf = new Buffer([253, 253, 0]); + var br = new BufferReader({buf: buf}); + br.readVarIntBuf().length.should.equal(3); + }); + + it('should read a 5 byte varint', function() { + var buf = new Buffer([254, 0, 0, 0, 0]); + buf.writeUInt32LE(50000, 1); + var br = new BufferReader({buf: buf}); + br.readVarIntBuf().length.should.equal(5); + }); + + it('should read a 9 byte varint', function() { + var buf = BufferWriter().writeVarIntBN(BN(Math.pow(2, 54).toString())).concat(); + var br = new BufferReader({buf: buf}); + br.readVarIntBuf().length.should.equal(9); + }); + + }); + describe('#readVarIntNum', function() { it('should read a 1 byte varint', function() {