Skip to content

Commit

Permalink
buffer: combine checking range of sourceStart in buf.copy
Browse files Browse the repository at this point in the history
Merging 2 checking range of sourceStart into 1. Plus,
add test case to increase coverage if sourceStart is greater
than length of source.

PR-URL: #47758
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
deokjinkim authored and MoLow committed Jul 6, 2023
1 parent 353dfbd commit cca557c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 11 deletions.
10 changes: 2 additions & 8 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
sourceStart = 0;
} else {
sourceStart = toInteger(sourceStart, 0);
if (sourceStart < 0)
throw new ERR_OUT_OF_RANGE('sourceStart', '>= 0', sourceStart);
if (sourceStart < 0 || sourceStart > source.length)
throw new ERR_OUT_OF_RANGE('sourceStart', `>= 0 && <= ${source.length}`, sourceStart);
}

if (sourceEnd === undefined) {
Expand All @@ -246,12 +246,6 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
if (targetStart >= target.length || sourceStart >= sourceEnd)
return 0;

if (sourceStart > source.length) {
throw new ERR_OUT_OF_RANGE('sourceStart',
`<= ${source.length}`,
sourceStart);
}

return _copyActual(source, target, targetStart, sourceStart, sourceEnd);
}

Expand Down
2 changes: 1 addition & 1 deletion test/parallel/test-buffer-alloc.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ b.copy(Buffer.alloc(0), 1, 1, 1);
b.copy(Buffer.alloc(1), 1, 1, 1);

// Try to copy 0 bytes from past the end of the source buffer
b.copy(Buffer.alloc(1), 0, 2048, 2048);
b.copy(Buffer.alloc(1), 0, 1024, 1024);

// Testing for smart defaults and ability to pass string values as offset
{
Expand Down
11 changes: 9 additions & 2 deletions test/parallel/test-buffer-copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,15 @@ assert.throws(
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
message: 'The value of "sourceStart" is out of range. ' +
'It must be >= 0. Received -1'
}
);

// Copy throws if sourceStart is greater than length of source
assert.throws(
() => Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, 100),
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
}
);

Expand Down

0 comments on commit cca557c

Please sign in to comment.