Skip to content

Commit

Permalink
Store last read header on reader
Browse files Browse the repository at this point in the history
  • Loading branch information
brianc committed Mar 14, 2014
1 parent d5355b9 commit df6a7da
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
20 changes: 10 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
var assert = require('assert')

var Reader = module.exports = function(codeSize) {
var Reader = module.exports = function(headerSize) {
this.offset = 0
this.lastChunk = false
this.chunk = null
//TODO - support code length > 1
this.codeSize = codeSize || 0
assert(this.codeSize < 2, 'pre-length code >1 not currently supported')
this.headerSize = headerSize || 0
this.header = null
assert(this.headerSize < 2, 'pre-length header of more than 1 byte length not currently supported')
}

Reader.prototype.addChunk = function(chunk) {
Expand All @@ -27,24 +27,24 @@ Reader.prototype._save = function() {
}

Reader.prototype.read = function() {
if(this.chunk.length < (this.codeSize + 4 + this.offset)) {
if(this.chunk.length < (this.headerSize + 4 + this.offset)) {
return this._save()
}

if(this.codeSize) {
var code = this.chunk[this.offset]
if(this.headerSize) {
this.header = this.chunk[this.offset]
}

//read length of next item
var length = this.chunk.readUInt32BE(this.offset + this.codeSize)
var length = this.chunk.readUInt32BE(this.offset + this.headerSize)

//next item spans more chunks than we have
var remaining = this.chunk.length - (this.offset + 4 + this.codeSize)
var remaining = this.chunk.length - (this.offset + 4 + this.headerSize)
if(length > remaining) {
return this._save()
}

this.offset += (this.codeSize + 4)
this.offset += (this.headerSize + 4)
var result = this.chunk.slice(this.offset, this.offset + length)
this.offset += length
return result
Expand Down
22 changes: 22 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,25 @@ describe('variable length header', function() {
assert.strictEqual(this.reader.read(), false)
})
})

describe('1 length code', function() {
beforeEach(function() {
this.reader = new Reader(1)
})

it('reads code', function() {
this.reader.addChunk(Buffer([9, 0, 0, 0, 1, 1]))
var result = this.reader.read()
assert(result)
assert.equal(this.reader.header, 9)
assert.equal(result.length, 1)
assert.equal(result[0], 1)
})

it('is set on uncompleted read', function() {
assert.equal(this.reader.header, null)
this.reader.addChunk(Buffer([2, 0, 0, 0, 1]))
assert.strictEqual(this.reader.read(), false)
assert.equal(this.reader.header, 2)
})
})

0 comments on commit df6a7da

Please sign in to comment.