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.
This commit is contained in:
Peter Griess 2010-07-20 17:23:30 -05:00 committed by Ryan Dahl
parent 8acea2693d
commit 56f200af5d
2 changed files with 12 additions and 1 deletions

View File

@ -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':

View File

@ -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++) {