Browse Source

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.
v0.7.4-release
isaacs 14 years ago
committed by Ryan Dahl
parent
commit
2e6a263e29
  1. 10
      lib/buffer.js
  2. 10
      test/simple/test-buffer.js

10
lib/buffer.js

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

10
test/simple/test-buffer.js

@ -216,6 +216,7 @@ assert.equal(d.length, 3);
assert.equal(d[0], 23);
assert.equal(d[1], 42);
assert.equal(d[2], 255);
assert.deepEqual(d, new Buffer(d));
var e = new Buffer('über');
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.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')
//

Loading…
Cancel
Save