Skip to content

Commit cca557c

Browse files
deokjinkimMoLow
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 353dfbd commit cca557c

3 files changed

Lines changed: 12 additions & 11 deletions

File tree

‎lib/buffer.js‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,8 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
231231
sourceStart=0;
232232
}else{
233233
sourceStart=toInteger(sourceStart,0);
234-
if(sourceStart<0)
235-
thrownewERR_OUT_OF_RANGE('sourceStart','>= 0',sourceStart);
234+
if(sourceStart<0||sourceStart>source.length)
235+
thrownewERR_OUT_OF_RANGE('sourceStart',`>= 0 && <= ${source.length}`,sourceStart);
236236
}
237237

238238
if(sourceEnd===undefined){
@@ -246,12 +246,6 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
246246
if(targetStart>=target.length||sourceStart>=sourceEnd)
247247
return0;
248248

249-
if(sourceStart>source.length){
250-
thrownewERR_OUT_OF_RANGE('sourceStart',
251-
`<= ${source.length}`,
252-
sourceStart);
253-
}
254-
255249
return_copyActual(source,target,targetStart,sourceStart,sourceEnd);
256250
}
257251

‎test/parallel/test-buffer-alloc.js‎

Lines changed: 1 addition & 1 deletion
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‎

Lines changed: 9 additions & 2 deletions
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)