From 56f200af5d8a1d98b40d70ed54cf643afa0008dc Mon Sep 17 00:00:00 2001 From: Peter Griess Date: Tue, 20 Jul 2010 17:23:30 -0500 Subject: [PATCH] Fix Buffer.toString() on 0-length slices. - Buffer.toString('ascii', 0, 0) incorrectly returns the entire contents of the buffer. Fix this. - Provide similar behavior to Buffer.write() and Buffer.copy() when dealing with 0-length in valid and invalid byte ranges. --- lib/buffer.js | 7 ++++++- test/simple/test-buffer.js | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) 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++) {