Skip to content

Commit 56f200a

Browse files
pgriessry
authored andcommitted
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.
1 parent 8acea26 commit 56f200a

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

lib/buffer.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@ Buffer.prototype.inspect = function () {
2424
Buffer.prototype.toString = function (encoding, start, stop) {
2525
encoding = (encoding || 'utf8').toLowerCase();
2626
if (!start) start = 0;
27-
if (!stop) stop = this.length;
27+
if (stop === undefined) stop = this.length;
28+
29+
// Fastpath empty strings
30+
if (stop === start) {
31+
return '';
32+
}
2833

2934
switch (encoding) {
3035
case 'utf8':

test/simple/test-buffer.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ b.copy(new Buffer(1), 1, 1, 1);
131131
// try to copy 0 bytes from past the end of the source buffer
132132
b.copy(new Buffer(1), 0, 2048, 2048);
133133

134+
// try to toString() a 0-length slice of a buffer, both within and without the
135+
// valid buffer range
136+
assert.equal(new Buffer('abc').toString('ascii', 0, 0), '');
137+
assert.equal(new Buffer('abc').toString('ascii', -100, -100), '');
138+
assert.equal(new Buffer('abc').toString('ascii', 100, 100), '');
139+
134140
var asciiString = "hello world";
135141
var offset = 100;
136142
for (var j = 0; j < 500; j++) {

0 commit comments

Comments
 (0)