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 <fedor@indutny.com>
This commit is contained in:
cjihrig 2014-06-27 00:07:16 -04:00 committed by Fedor Indutny
parent 1a1b1a7534
commit 2cae44f169
2 changed files with 15 additions and 2 deletions

View 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) {

View 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);