diff --git a/lib/writer.js b/lib/writer.js index 520b6b17..f87ba29f 100644 --- a/lib/writer.js +++ b/lib/writer.js @@ -1,18 +1,15 @@ var Writer = function(size) { this.size = size || 1024; - this.buffer = new Buffer(this.size); - this.offset = 0; + this.buffer = new Buffer(this.size + 5); + this.offset = 5; }; var p = Writer.prototype; -p._remaining = function() { - return this.buffer.length - this.offset; -} - //resizes internal buffer if not enough size left p._ensure = function(size) { - if(this._remaining() < size) { + var remaining = this.buffer.length - this.offset; + if(remaining < size) { var oldBuffer = this.buffer; this.buffer = Buffer(oldBuffer.length + size); oldBuffer.copy(this.buffer); @@ -52,10 +49,6 @@ p.addChar = function(char) { return this; } -p.join = function() { - return this.buffer.slice(0, this.offset); -} - p.addString = function(string) { var string = string || ""; var len = Buffer.byteLength(string); @@ -66,7 +59,7 @@ p.addString = function(string) { } p.getByteLength = function() { - return this.offset; + return this.offset - 5; } p.add = function(otherBuffer) { @@ -77,11 +70,24 @@ p.add = function(otherBuffer) { } p.clear = function() { - this.offset=0; + this.offset=5; } -p.flush = function() { - var result = this.join(); +p.join = function(code) { + if(code) { + var end = this.offset; + this.offset = 0; + this.buffer[this.offset++] = code; + //write the length which is length of entire packet not including + //message type code byte + this.addInt32(end - 1); + this.offset = end; + } + return this.buffer.slice(code ? 0 : 5, this.offset); +} + +p.flush = function(code) { + var result = this.join(code); this.clear(); return result; } diff --git a/test/unit/writer-tests.js b/test/unit/writer-tests.js index 8a385ff6..f2052bf4 100644 --- a/test/unit/writer-tests.js +++ b/test/unit/writer-tests.js @@ -155,3 +155,23 @@ test("resizing to much larger", function() { var result = subject.addCString(string).flush(); assert.equalBuffers(result, [33, 33, 33, 33, 33, 33, 33, 33, 0]) }) + +test("header", function() { + test('added as a hex code to a full writer', function() { + var subject = new Writer(2); + var result = subject.addCString("!").flush(0x50) + assert.equalBuffers(result, [0x50, 0, 0, 0, 6, 33, 0]); + }) + + test('added as a hex code to a non-full writer', function() { + var subject = new Writer(10).addCString("!"); + var joinedResult = subject.join(0x50); + var result = subject.flush(0x50); + assert.equalBuffers(result, [0x50, 0, 0, 0, 6, 33, 0]); + }) + + test('added as a hex code to a buffer which requires resizing', function() { + var result = new Writer(2).addCString("!!!!!!!!").flush(0x50); + assert.equalBuffers(result, [0x50, 0, 0, 0, 0x0D, 33, 33, 33, 33, 33, 33, 33, 33, 0]); + }) +})