Skip to content

Commit 8ec089a

Browse files
thefourtheyervagg
authored andcommitted
buffer: fix case of one buffer passed to concat
Fix Buffer.concat() so a copy is always returned regardless of the number of buffers that were passed. Previously if the array length was one then the same same buffer was returned. This created a special case for the user where there was a chance mutating the buffer returned by .concat() could mutate the buffer passed in. Also fixes an inconsistency when throwing if an array member was not a Buffer instance. For example: Buffer.concat([42]); // Returns 42 Buffer.concat([42, 1]); // Throws a TypeError Now .concat() will always throw if an array member is not a Buffer instance. See: #1891 PR-URL: #1937 Reviewed-By: Trevor Norris <trev.norris@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
1 parent 9b1341c commit 8ec089a

File tree

4 files changed

+7
-10
lines changed

4 files changed

+7
-10
lines changed

doc/api/buffer.markdown

-5
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,6 @@ the list together.
130130
If the list has no items, or if the totalLength is 0, then it returns a
131131
zero-length buffer.
132132

133-
If the list has exactly one item, then the first item of the list is
134-
returned.
135-
136-
If the list has more than one item, then a new Buffer is created.
137-
138133
If totalLength is not provided, it is read from the buffers in the list.
139134
However, this adds an additional loop to the function, so it is faster
140135
to provide the length explicitly.

lib/internal/buffer_new.js

-2
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,6 @@ Buffer.concat = function(list, length) {
183183

184184
if (list.length === 0)
185185
return new Buffer(0);
186-
else if (list.length === 1)
187-
return list[0];
188186

189187
if (length === undefined) {
190188
length = 0;

lib/internal/buffer_old.js

-2
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,6 @@ Buffer.concat = function(list, length) {
249249

250250
if (list.length === 0)
251251
return new Buffer(0);
252-
else if (list.length === 1)
253-
return list[0];
254252

255253
if (length === undefined) {
256254
length = 0;

test/parallel/test-buffer-concat.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,14 @@ var flatLongLen = Buffer.concat(long, 40);
1414

1515
assert(flatZero.length === 0);
1616
assert(flatOne.toString() === 'asdf');
17-
assert(flatOne === one[0]);
17+
// A special case where concat used to return the first item,
18+
// if the length is one. This check is to make sure that we don't do that.
19+
assert(flatOne !== one[0]);
1820
assert(flatLong.toString() === (new Array(10 + 1).join('asdf')));
1921
assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf')));
2022

23+
assert.throws(function() {
24+
Buffer.concat([42]);
25+
}, TypeError);
26+
2127
console.log('ok');

0 commit comments

Comments
 (0)