Skip to content

Commit c0bfac6

Browse files
entertainyoutrevnorris
authored andcommitted
buffer: remove duplicated code in fromObject
Add fromArrayLike() to handle logic of copying in values from array-like argument. PR-URL: nodejs#4948 Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent 25751be commit c0bfac6

File tree

2 files changed

+19
-23
lines changed

2 files changed

+19
-23
lines changed

lib/buffer.js

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,13 @@ function fromString(string, encoding) {
122122
return b;
123123
}
124124

125+
function fromArrayLike(obj) {
126+
const length = obj.length;
127+
const b = allocate(length);
128+
for (let i = 0; i < length; i++)
129+
b[i] = obj[i] & 255;
130+
return b;
131+
}
125132

126133
function fromObject(obj) {
127134
if (obj instanceof Buffer) {
@@ -134,14 +141,6 @@ function fromObject(obj) {
134141
return b;
135142
}
136143

137-
if (Array.isArray(obj)) {
138-
const length = obj.length;
139-
const b = allocate(length);
140-
for (let i = 0; i < length; i++)
141-
b[i] = obj[i] & 255;
142-
return b;
143-
}
144-
145144
if (obj == null) {
146145
throw new TypeError('Must start with number, buffer, array or string');
147146
}
@@ -150,25 +149,15 @@ function fromObject(obj) {
150149
return binding.createFromArrayBuffer(obj);
151150
}
152151

153-
if (obj.buffer instanceof ArrayBuffer || obj.length) {
154-
let length;
155-
if (typeof obj.length !== 'number' || obj.length !== obj.length)
156-
length = 0;
157-
else
158-
length = obj.length;
159-
const b = allocate(length);
160-
for (let i = 0; i < length; i++) {
161-
b[i] = obj[i] & 255;
152+
if (obj.buffer instanceof ArrayBuffer || 'length' in obj) {
153+
if (typeof obj.length !== 'number' || obj.length !== obj.length) {
154+
return allocate(0);
162155
}
163-
return b;
156+
return fromArrayLike(obj);
164157
}
165158

166159
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
167-
var array = obj.data;
168-
const b = allocate(array.length);
169-
for (let i = 0; i < array.length; i++)
170-
b[i] = array[i] & 255;
171-
return b;
160+
return fromArrayLike(obj.data);
172161
}
173162

174163
throw new TypeError('Must start with number, buffer, array or string');

test/parallel/test-buffer.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ var c = new Buffer(512);
2828
console.log('c.length == %d', c.length);
2929
assert.strictEqual(512, c.length);
3030

31+
var d = new Buffer([]);
32+
assert.strictEqual(0, d.length);
33+
34+
var ui32 = new Uint32Array(4).fill(42);
35+
var e = Buffer(ui32);
36+
assert.deepEqual(ui32, e);
37+
3138
// First check Buffer#fill() works as expected.
3239

3340
assert.throws(function() {

0 commit comments

Comments
 (0)