Created
February 1, 2011 08:07
-
-
Save isaacs/805571 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
From 75d7f34fbee6b7ae4a65d9334c38ebd66de565bb Mon Sep 17 00:00:00 2001 | |
From: isaacs <i@izs.me> | |
Date: Tue, 1 Feb 2011 00:06:44 -0800 | |
Subject: [PATCH] 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. | |
--- | |
lib/buffer.js | 10 ++++++++-- | |
test/simple/test-buffer.js | 8 ++++++++ | |
2 files changed, 16 insertions(+), 2 deletions(-) | |
diff --git a/lib/buffer.js b/lib/buffer.js | |
index 2733947..7369807 100644 | |
--- a/lib/buffer.js | |
+++ b/lib/buffer.js | |
@@ -139,8 +139,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]; | |
} | |
@@ -153,6 +153,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; | |
diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js | |
index e8756a7..2e7b990 100644 | |
--- a/test/simple/test-buffer.js | |
+++ b/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()); | |
@@ -225,6 +226,13 @@ var f = new Buffer('über', 'ascii'); | |
console.error('f.length: %d (should be 4)', f.length); | |
assert.deepEqual(f, new Buffer([252, 98, 101, 114])); | |
+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') | |
-- | |
1.7.2.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment