Skip to content

Commit d64e6e0

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

File tree

2 files changed

+19
-23
lines changed

2 files changed

+19
-23
lines changed

lib/buffer.js

+12-23
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,13 @@ function fromString(string, encoding) {
117117
return b;
118118
}
119119

120+
function fromArrayLike(obj) {
121+
const length = obj.length;
122+
const b = allocate(length);
123+
for (let i = 0; i < length; i++)
124+
b[i] = obj[i] & 255;
125+
return b;
126+
}
120127

121128
function fromObject(obj) {
122129
if (obj instanceof Buffer) {
@@ -129,14 +136,6 @@ function fromObject(obj) {
129136
return b;
130137
}
131138

132-
if (Array.isArray(obj)) {
133-
const length = obj.length;
134-
const b = allocate(length);
135-
for (let i = 0; i < length; i++)
136-
b[i] = obj[i] & 255;
137-
return b;
138-
}
139-
140139
if (obj == null) {
141140
throw new TypeError('must start with number, buffer, array or string');
142141
}
@@ -145,25 +144,15 @@ function fromObject(obj) {
145144
return binding.createFromArrayBuffer(obj);
146145
}
147146

148-
if (obj.buffer instanceof ArrayBuffer || obj.length) {
149-
let length;
150-
if (typeof obj.length !== 'number' || obj.length !== obj.length)
151-
length = 0;
152-
else
153-
length = obj.length;
154-
const b = allocate(length);
155-
for (let i = 0; i < length; i++) {
156-
b[i] = obj[i] & 255;
147+
if (obj.buffer instanceof ArrayBuffer || 'length' in obj) {
148+
if (typeof obj.length !== 'number' || obj.length !== obj.length) {
149+
return allocate(0);
157150
}
158-
return b;
151+
return fromArrayLike(obj);
159152
}
160153

161154
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
162-
var array = obj.data;
163-
const b = allocate(array.length);
164-
for (let i = 0; i < array.length; i++)
165-
b[i] = array[i] & 255;
166-
return b;
155+
return fromArrayLike(obj.data);
167156
}
168157

169158
throw new TypeError('must start with number, buffer, array or string');

test/parallel/test-buffer.js

+7
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)