Closes GH-609 Support array-ish args to Buffer ctor

Any array-ish thing (whether a Buffer, an Array, or just an object with
a numeric "length") is interpreted as a list of bytes.
This commit is contained in:
isaacs 2011-02-01 00:06:44 -08:00 committed by Ryan Dahl
parent 5f2e90934e
commit 2e6a263e29
2 changed files with 18 additions and 2 deletions

View File

@ -147,8 +147,8 @@ function Buffer(subject, encoding, offset) {
pool.used += this.length; pool.used += this.length;
} }
// Assume object is an array // Treat array-ish objects as a byte array.
if (Array.isArray(subject)) { if (isArrayIsh(subject)) {
for (var i = 0; i < this.length; i++) { for (var i = 0; i < this.length; i++) {
this.parent[i + this.offset] = subject[i]; this.parent[i + this.offset] = subject[i];
} }
@ -161,6 +161,12 @@ function Buffer(subject, encoding, offset) {
SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length); SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
} }
function isArrayIsh(subject) {
return Array.isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number';
}
exports.SlowBuffer = SlowBuffer; exports.SlowBuffer = SlowBuffer;
exports.Buffer = Buffer; exports.Buffer = Buffer;

View File

@ -216,6 +216,7 @@ assert.equal(d.length, 3);
assert.equal(d[0], 23); assert.equal(d[0], 23);
assert.equal(d[1], 42); assert.equal(d[1], 42);
assert.equal(d[2], 255); assert.equal(d[2], 255);
assert.deepEqual(d, new Buffer(d));
var e = new Buffer('über'); var e = new Buffer('über');
console.error('uber: \'%s\'', e.toString()); console.error('uber: \'%s\'', e.toString());
@ -234,6 +235,15 @@ console.error('f.length: %d (should be 12)', f.length);
assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4]));
assert.equal(f.toString('ucs2'), 'привет'); assert.equal(f.toString('ucs2'), 'привет');
var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4};
var g = new Buffer(arrayIsh);
assert.deepEqual(g, new Buffer([0, 1, 2, 3]));
var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4};
g = new Buffer(strArrayIsh);
assert.deepEqual(g, new Buffer([0, 1, 2, 3]));
// //
// Test toString('base64') // Test toString('base64')
// //