diff --git a/index.js b/index.js index 5e97e21..2ff3e3e 100644 --- a/index.js +++ b/index.js @@ -12,8 +12,11 @@ var Reader = module.exports = function(options) { this.chunkLength = 0 this.headerSize = options.headerSize || 0 this.lengthPadding = options.lengthPadding || 0 + this.lengthLE = options.lengthLE || false + this.lengthSize = options.lengthSize || 4 + assert( this.lengthSize <= 6, 'lengths of more than 6 bytes are not currently supported' ) this.header = null - assert(this.headerSize < 2, 'pre-length header of more than 1 byte length not currently supported') + assert(this.headerSize <= 6 , 'pre-length header with more than a 6 byte length not currently supported') } Reader.prototype.addChunk = function(chunk) { @@ -41,24 +44,29 @@ Reader.prototype.addChunk = function(chunk) { } Reader.prototype.read = function() { - if(this.chunkLength < (this.headerSize + 4 + this.offset)) { + if(this.chunkLength < (this.headerSize + this.lengthSize + this.offset)) { return false } if(this.headerSize) { - this.header = this.chunk[this.offset] + if ( this.lengthLE ) + this.header = this.chunk.readUIntLE( this.offset, this.headerSize ); + else this.header = this.chunk.readUIntBE( this.offset, this.headerSize ); } //read length of next item - var length = this.chunk.readUInt32BE(this.offset + this.headerSize) + this.lengthPadding + var length = this.lengthPadding; + if ( this.lengthLE ) + length += this.chunk.readUIntLE( this.offset + this.headerSize, this.lengthSize ); + else length += this.chunk.readUIntBE( this.offset + this.headerSize, this.lengthSize ); //next item spans more chunks than we have - var remaining = this.chunkLength - (this.offset + 4 + this.headerSize) + var remaining = this.chunkLength - (this.offset + this.lengthSize + this.headerSize) if(length > remaining) { return false } - this.offset += (this.headerSize + 4) + this.offset += (this.headerSize + this.lengthSize) var result = this.chunk.slice(this.offset, this.offset + length) this.offset += length return result diff --git a/test/index.js b/test/index.js index 0e2eedb..b1ae678 100644 --- a/test/index.js +++ b/test/index.js @@ -146,3 +146,25 @@ describe('postgres style packet', function() { assert.equal(result[3], 0) }) }) + + +describe('little-endian style packet', function() { + beforeEach(function() { + this.reader = new Reader({ + headerSize: 4, + lengthLE: true, + lengthPadding: 8, + }) + }) + + it('reads 4-byte LE size with a 4 byte LE header and 8 byte padding', function() { + var buf = Buffer.from([0x7A, 0xB1, 0xEA, 0x06, 4, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0x00, 0xA4, 0xD3, 0xF1]); + this.reader.addChunk( buf ) + var result = this.reader.read() + assert(result) + assert.equal(this.reader.header, 0x06EAB17A) + assert.equal(result.length, 12) + for ( i = 0; i < result.length; ++i ) + assert.equal(result[i], buf[i+8]) + }) +})