buffer: construct new buffer from buffer toJSON() output
authorcjihrig <cjihrig@gmail.com>
Fri, 27 Jun 2014 04:07:16 +0000 (00:07 -0400)
committerFedor Indutny <fedor@indutny.com>
Fri, 27 Jun 2014 09:36:44 +0000 (13:36 +0400)
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 <fedor@indutny.com>
lib/buffer.js
test/simple/test-buffer.js

index 686c072..c1abb00 100644 (file)
@@ -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) {
index 1ad5244..70cc590 100644 (file)
@@ -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);