From 339dc3230cc607cd507d6b5adf874afcec7aa937 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 24 Feb 2023 16:33:25 -0800 Subject: [PATCH] Apply suggestions from code review Co-authored-by: Antoine du Hamel --- lib/buffer.js | 14 ++++------ test/parallel/test-buffer-from.js | 46 +++++++++++++++++++++++++++---- 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index b42b379294e5bb..3019af96432115 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -355,23 +355,19 @@ Buffer.copyBytesFrom = function copyBytesFrom(view, offset, length) { if (offset !== undefined || length !== undefined) { if (offset !== undefined) { validateInteger(offset, 'offset', 0); + if (offset >= viewLength) return Buffer.alloc(0); } else { offset = 0; } + let end; if (length !== undefined) { validateInteger(length, 'length', 0); + end = offset + length; } else { - length = viewLength; + end = viewLength; } - offset = MathMin(offset, viewLength); - length = MathMin(length, viewLength - offset); - - if (length === 0) { - return Buffer.alloc(0); - } - - view = TypedArrayPrototypeSlice(view, offset, offset + length); + view = TypedArrayPrototypeSlice(view, offset, end); } return fromArrayLike(new Uint8Array( diff --git a/test/parallel/test-buffer-from.js b/test/parallel/test-buffer-from.js index 206aa063798649..284c63e7d02e8e 100644 --- a/test/parallel/test-buffer-from.js +++ b/test/parallel/test-buffer-from.js @@ -95,13 +95,47 @@ Buffer.from('deadbeaf', 'hex'); // Should not throw. } throws(() => { - Buffer.copyBytesFrom('nope'); + Buffer.copyBytesFrom(); }, { code: 'ERR_INVALID_ARG_TYPE', }); -throws(() => { - Buffer.copyBytesFrom(new Uint8Array(1), 'a'); -}, { - code: 'ERR_INVALID_ARG_TYPE', -}); +['', Symbol(), true, false, {}, [], () => {}, 1, 1n, null, undefined].forEach( + (notTypedArray) => throws(() => { + Buffer.copyBytesFrom('nope'); + }, { + code: 'ERR_INVALID_ARG_TYPE', + }) +); + +['', Symbol(), true, false, {}, [], () => {}, 1n].forEach((notANumber) => + throws(() => { + Buffer.copyBytesFrom(new Uint8Array(1), notANumber); + }, { + code: 'ERR_INVALID_ARG_TYPE', + }) +); + +[-1, NaN, 1.1, -Infinity].forEach((outOfRange) => + throws(() => { + Buffer.copyBytesFrom(new Uint8Array(1), outOfRange); + }, { + code: 'ERR_OUT_OF_RANGE', + }) +); + +['', Symbol(), true, false, {}, [], () => {}, 1n].forEach((notANumber) => + throws(() => { + Buffer.copyBytesFrom(new Uint8Array(1), 0, notANumber); + }, { + code: 'ERR_INVALID_ARG_TYPE', + }) +); + +[-1, NaN, 1.1, -Infinity].forEach((outOfRange) => + throws(() => { + Buffer.copyBytesFrom(new Uint8Array(1), 0, outOfRange); + }, { + code: 'ERR_OUT_OF_RANGE', + }) +);