From 2cae44f16934836f0a66b2ea930a0604f505e571 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 27 Jun 2014 00:07:16 -0400 Subject: [PATCH] buffer: construct new buffer from buffer toJSON() output Creating a new buffer from the toJSON() output of another buffer does not currently work. This commit adds that support. Closes #7849. Signed-off-by: Fedor Indutny --- lib/buffer.js | 7 +++++-- test/simple/test-buffer.js | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 686c072e84e..c1abb005904 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -53,9 +53,12 @@ function Buffer(subject, encoding) { this.length = subject > 0 ? subject >>> 0 : 0; else if (util.isString(subject)) this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8'); - else if (util.isObject(subject)) + else if (util.isObject(subject)) { + if (subject.type === 'Buffer' && util.isArray(subject.data)) + subject = subject.data; + this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0; - else + } else throw new TypeError('must start with number, buffer, array or string'); if (this.length > kMaxLength) { diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 1ad5244f707..70cc5908af4 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -849,6 +849,16 @@ Buffer(Buffer(0), 0, 0); })); })(); +// issue GH-7849 +(function() { + var buf = new Buffer('test'); + var json = JSON.stringify(buf); + var obj = JSON.parse(json); + var copy = new Buffer(obj); + + assert(buf.equals(copy)); +})(); + // issue GH-4331 assert.throws(function() { new Buffer(0xFFFFFFFF);