Skip to content

Commit

Permalink
Apply suggestions from code review
Browse files Browse the repository at this point in the history
Co-authored-by: Antoine du Hamel <[email protected]>
  • Loading branch information
jasnell and aduh95 authored Feb 25, 2023
1 parent 4490513 commit 339dc32
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 15 deletions.
14 changes: 5 additions & 9 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
46 changes: 40 additions & 6 deletions test/parallel/test-buffer-from.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
})
);

0 comments on commit 339dc32

Please sign in to comment.