diff --git a/lib/buffer.js b/lib/buffer.js index e1fcdb4044..ef46482151 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -24,7 +24,12 @@ Buffer.prototype.inspect = function () { Buffer.prototype.toString = function (encoding, start, stop) { encoding = (encoding || 'utf8').toLowerCase(); if (!start) start = 0; - if (!stop) stop = this.length; + if (stop === undefined) stop = this.length; + + // Fastpath empty strings + if (stop === start) { + return ''; + } switch (encoding) { case 'utf8': diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 3ef85b97b1..5776997112 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -131,6 +131,12 @@ b.copy(new Buffer(1), 1, 1, 1); // try to copy 0 bytes from past the end of the source buffer b.copy(new Buffer(1), 0, 2048, 2048); +// try to toString() a 0-length slice of a buffer, both within and without the +// valid buffer range +assert.equal(new Buffer('abc').toString('ascii', 0, 0), ''); +assert.equal(new Buffer('abc').toString('ascii', -100, -100), ''); +assert.equal(new Buffer('abc').toString('ascii', 100, 100), ''); + var asciiString = "hello world"; var offset = 100; for (var j = 0; j < 500; j++) {