Skip to content

Commit e457d89

Browse files
deokjinkimtargos
authored andcommitted
buffer: combine checking range of sourceStart in buf.copy
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>
1 parent 1b06c1e commit e457d89

File tree

3 files changed

+12
-11
lines changed

3 files changed

+12
-11
lines changed

lib/buffer.js

+2-8
Original file line numberDiff line numberDiff line change
@@ -222,8 +222,8 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
222222
sourceStart = 0;
223223
} else {
224224
sourceStart = toInteger(sourceStart, 0);
225-
if (sourceStart < 0)
226-
throw new ERR_OUT_OF_RANGE('sourceStart', '>= 0', sourceStart);
225+
if (sourceStart < 0 || sourceStart > source.length)
226+
throw new ERR_OUT_OF_RANGE('sourceStart', `>= 0 && <= ${source.length}`, sourceStart);
227227
}
228228

229229
if (sourceEnd === undefined) {
@@ -237,12 +237,6 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
237237
if (targetStart >= target.length || sourceStart >= sourceEnd)
238238
return 0;
239239

240-
if (sourceStart > source.length) {
241-
throw new ERR_OUT_OF_RANGE('sourceStart',
242-
`<= ${source.length}`,
243-
sourceStart);
244-
}
245-
246240
return _copyActual(source, target, targetStart, sourceStart, sourceEnd);
247241
}
248242

test/parallel/test-buffer-alloc.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ b.copy(Buffer.alloc(0), 1, 1, 1);
124124
b.copy(Buffer.alloc(1), 1, 1, 1);
125125

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

129129
// Testing for smart defaults and ability to pass string values as offset
130130
{

test/parallel/test-buffer-copy.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,15 @@ assert.throws(
155155
{
156156
code: 'ERR_OUT_OF_RANGE',
157157
name: 'RangeError',
158-
message: 'The value of "sourceStart" is out of range. ' +
159-
'It must be >= 0. Received -1'
158+
}
159+
);
160+
161+
// Copy throws if sourceStart is greater than length of source
162+
assert.throws(
163+
() => Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, 100),
164+
{
165+
code: 'ERR_OUT_OF_RANGE',
166+
name: 'RangeError',
160167
}
161168
);
162169

0 commit comments

Comments
 (0)