From bc28acdd029687d24004f69f98617c7e171ca173 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Fri, 23 Aug 2013 12:00:28 +0200 Subject: [PATCH] buffer: fix regression in Buffer(buf) constructor Commit 3a2f273b got the source and the target wrong when copying over the data. Fix that and add a regression test. Fixes #6111. --- lib/buffer.js | 2 +- test/simple/test-buffer.js | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index c6266428d9..6d753eb1dd 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -88,7 +88,7 @@ function Buffer(subject, encoding) { this.length = this.write(subject, 0, encoding); } else { if (util.isBuffer(subject)) - this.copy(subject, 0, 0, this.length); + subject.copy(this, 0, 0, this.length); else if (util.isNumber(subject.length) || util.isArray(subject)) for (var i = 0; i < this.length; i++) this[i] = subject[i]; diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 91b38422f5..45eb28761a 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -965,3 +965,19 @@ assert.throws(function() { Buffer('', 'buffer'); }, TypeError); +// Regression test for #6111. Constructing a buffer from another buffer +// should a) work, and b) not corrupt the source buffer. +(function() { + var a = [0]; + for (var i = 0; i < 7; ++i) a = a.concat(a); + a = a.map(function(_, i) { return i }); + var b = Buffer(a); + var c = Buffer(b); + assert.equal(b.length, a.length); + assert.equal(c.length, a.length); + for (var i = 0, k = a.length; i < k; ++i) { + assert.equal(a[i], i); + assert.equal(b[i], i); + assert.equal(c[i], i); + } +})();