Skip to content

Commit 7e75cf4

Browse files
committed
add type check to set
1 parent 0a50b68 commit 7e75cf4

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

lib/buffer.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ function copyImpl(source, target, targetStart, sourceStart, sourceEnd) {
240240
return _copyActual(source, target, targetStart, sourceStart, sourceEnd);
241241
}
242242

243-
function _copyActual(source, target, targetStart, sourceStart, sourceEnd) {
243+
function _copyActual(source, target, targetStart, sourceStart, sourceEnd, isUint8Copy = false) {
244244
if (sourceEnd - sourceStart > target.byteLength - targetStart)
245245
sourceEnd = sourceStart + target.byteLength - targetStart;
246246

@@ -252,7 +252,7 @@ function _copyActual(source, target, targetStart, sourceStart, sourceEnd) {
252252
if (nb <= 0)
253253
return 0;
254254

255-
if (sourceStart === 0 && nb === sourceLen) {
255+
if (sourceStart === 0 && nb === sourceLen && (isUint8Copy || isUint8Array(target))) {
256256
TypedArrayPrototypeSet(target, source, targetStart);
257257
} else {
258258
_copy(source, target, targetStart, sourceStart, nb);
@@ -604,7 +604,7 @@ Buffer.concat = function concat(list, length) {
604604
throw new ERR_INVALID_ARG_TYPE(
605605
`list[${i}]`, ['Buffer', 'Uint8Array'], list[i]);
606606
}
607-
pos += _copyActual(buf, buffer, pos, 0, buf.length);
607+
pos += _copyActual(buf, buffer, pos, 0, buf.length, true);
608608
}
609609

610610
// Note: `length` is always equal to `buffer.length` at this point

test/parallel/test-buffer-copy.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,16 @@ b.copy(c, 'not a valid offset');
226226
// Make sure this acted like a regular copy with `0` offset.
227227
assert.deepStrictEqual(c, b.slice(0, c.length));
228228

229+
// Copy into a Uint16Array target; bytes are packed into 16-bit elements.
230+
{
231+
const x = new Uint16Array(4);
232+
const buf = Buffer.of(1, 2, 3, 4);
233+
const copied = buf.copy(x);
234+
assert.strictEqual(copied, 4);
235+
assert.ok(x instanceof Uint16Array);
236+
assert.deepStrictEqual(Array.from(x), [513, 1027, 0, 0]);
237+
}
238+
229239
{
230240
c.fill('C');
231241
assert.throws(() => {

0 commit comments

Comments
 (0)