diff --git a/Changes.md b/Changes.md index 2b5e42635..6f30769a5 100644 --- a/Changes.md +++ b/Changes.md @@ -4,6 +4,10 @@ This file is a manually maintained list of changes for each release. Feel free to add your changes here when sending pull requests. Also send corrections if you spot any mistakes. +## HEAD + +* Store only current pack and beyond in parser + ## v2.5.1 (2014-09-22) * Fix `pool.end` race conditions #915 diff --git a/lib/protocol/Parser.js b/lib/protocol/Parser.js index a00ccd0da..bf8e65a81 100644 --- a/lib/protocol/Parser.js +++ b/lib/protocol/Parser.js @@ -98,25 +98,36 @@ Parser.prototype.write = function(buffer) { } }; -Parser.prototype.append = function(newBuffer) { - // If resume() is called, we don't pass a buffer to write() - if (!newBuffer) { +Parser.prototype.append = function append(chunk) { + if (!chunk || chunk.length === 0) { return; } - var oldBuffer = this._buffer; - var bytesRemaining = this._bytesRemaining(); - var newLength = bytesRemaining + newBuffer.length; + var buffer = chunk; + var sliceEnd = this._buffer.length; + var sliceStart = this._packetOffset === null + ? this._offset + : this._packetOffset; + var sliceLength = sliceEnd - sliceStart; - var combinedBuffer = (this._offset > newLength) - ? oldBuffer.slice(0, newLength) - : new Buffer(newLength); + if (sliceLength !== 0) { + // Create a new Buffer + buffer = new Buffer(sliceLength + chunk.length); - oldBuffer.copy(combinedBuffer, 0, this._offset); - newBuffer.copy(combinedBuffer, bytesRemaining); + // Copy data + this._buffer.copy(buffer, 0, sliceStart, sliceEnd); + chunk.copy(buffer, sliceLength); + } - this._buffer = combinedBuffer; - this._offset = 0; + // Adjust data-tracking pointers + this._buffer = buffer; + this._offset = this._offset - sliceStart; + this._packetEnd = this._packetEnd !== null + ? this._packetEnd - sliceStart + : null; + this._packetOffset = this._packetOffset !== null + ? this._packetOffset - sliceStart + : null; }; Parser.prototype.pause = function() {