Skip to content

Commit 339dc32

Browse files
jasnelladuh95
andauthored
Apply suggestions from code review
Co-authored-by: Antoine du Hamel <[email protected]>
1 parent 4490513 commit 339dc32

File tree

2 files changed

+45
-15
lines changed

2 files changed

+45
-15
lines changed

lib/buffer.js

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -355,23 +355,19 @@ Buffer.copyBytesFrom = function copyBytesFrom(view, offset, length) {
355355
if (offset !== undefined || length !== undefined) {
356356
if (offset !== undefined) {
357357
validateInteger(offset, 'offset', 0);
358+
if (offset >= viewLength) return Buffer.alloc(0);
358359
} else {
359360
offset = 0;
360361
}
362+
let end;
361363
if (length !== undefined) {
362364
validateInteger(length, 'length', 0);
365+
end = offset + length;
363366
} else {
364-
length = viewLength;
367+
end = viewLength;
365368
}
366369

367-
offset = MathMin(offset, viewLength);
368-
length = MathMin(length, viewLength - offset);
369-
370-
if (length === 0) {
371-
return Buffer.alloc(0);
372-
}
373-
374-
view = TypedArrayPrototypeSlice(view, offset, offset + length);
370+
view = TypedArrayPrototypeSlice(view, offset, end);
375371
}
376372

377373
return fromArrayLike(new Uint8Array(

test/parallel/test-buffer-from.js

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,13 +95,47 @@ Buffer.from('deadbeaf', 'hex'); // Should not throw.
9595
}
9696

9797
throws(() => {
98-
Buffer.copyBytesFrom('nope');
98+
Buffer.copyBytesFrom();
9999
}, {
100100
code: 'ERR_INVALID_ARG_TYPE',
101101
});
102102

103-
throws(() => {
104-
Buffer.copyBytesFrom(new Uint8Array(1), 'a');
105-
}, {
106-
code: 'ERR_INVALID_ARG_TYPE',
107-
});
103+
['', Symbol(), true, false, {}, [], () => {}, 1, 1n, null, undefined].forEach(
104+
(notTypedArray) => throws(() => {
105+
Buffer.copyBytesFrom('nope');
106+
}, {
107+
code: 'ERR_INVALID_ARG_TYPE',
108+
})
109+
);
110+
111+
['', Symbol(), true, false, {}, [], () => {}, 1n].forEach((notANumber) =>
112+
throws(() => {
113+
Buffer.copyBytesFrom(new Uint8Array(1), notANumber);
114+
}, {
115+
code: 'ERR_INVALID_ARG_TYPE',
116+
})
117+
);
118+
119+
[-1, NaN, 1.1, -Infinity].forEach((outOfRange) =>
120+
throws(() => {
121+
Buffer.copyBytesFrom(new Uint8Array(1), outOfRange);
122+
}, {
123+
code: 'ERR_OUT_OF_RANGE',
124+
})
125+
);
126+
127+
['', Symbol(), true, false, {}, [], () => {}, 1n].forEach((notANumber) =>
128+
throws(() => {
129+
Buffer.copyBytesFrom(new Uint8Array(1), 0, notANumber);
130+
}, {
131+
code: 'ERR_INVALID_ARG_TYPE',
132+
})
133+
);
134+
135+
[-1, NaN, 1.1, -Infinity].forEach((outOfRange) =>
136+
throws(() => {
137+
Buffer.copyBytesFrom(new Uint8Array(1), 0, outOfRange);
138+
}, {
139+
code: 'ERR_OUT_OF_RANGE',
140+
})
141+
);

0 commit comments

Comments
 (0)