Skip to content

Commit

Permalink
buffer: faster type check
Browse files Browse the repository at this point in the history
Also add support for any TypedArray as target.

PR-URL: #54088
  • Loading branch information
ronag committed Jul 31, 2024
1 parent 7941b4b commit 324f2c6
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

const {
Array,
ArrayBufferIsView,
ArrayIsArray,
ArrayPrototypeForEach,
MathFloor,
Expand Down Expand Up @@ -201,9 +202,9 @@ function toInteger(n, defaultVal) {
}

function _copy(source, target, targetStart, sourceStart, sourceEnd) {
if (!isUint8Array(source))
if (!ArrayBufferIsView(source))
throw new ERR_INVALID_ARG_TYPE('source', ['Buffer', 'Uint8Array'], source);
if (!isUint8Array(target))
if (!ArrayBufferIsView(target))
throw new ERR_INVALID_ARG_TYPE('target', ['Buffer', 'Uint8Array'], target);

if (targetStart === undefined) {
Expand All @@ -218,34 +219,34 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
sourceStart = 0;
} else {
sourceStart = NumberIsInteger(sourceStart) ? sourceStart : toInteger(sourceStart, 0);
if (sourceStart < 0 || sourceStart > source.length)
throw new ERR_OUT_OF_RANGE('sourceStart', `>= 0 && <= ${source.length}`, sourceStart);
if (sourceStart < 0 || sourceStart > source.byteLength)
throw new ERR_OUT_OF_RANGE('sourceStart', `>= 0 && <= ${source.byteLength}`, sourceStart);
}

if (sourceEnd === undefined) {
sourceEnd = source.length;
sourceEnd = source.byteLength;
} else {
sourceEnd = NumberIsInteger(sourceEnd) ? sourceEnd : toInteger(sourceEnd, 0);
if (sourceEnd < 0)
throw new ERR_OUT_OF_RANGE('sourceEnd', '>= 0', sourceEnd);
}

if (targetStart >= target.length || sourceStart >= sourceEnd)
if (targetStart >= target.byteLength || sourceStart >= sourceEnd)
return 0;

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

function _copyActual(source, target, targetStart, sourceStart, sourceEnd) {
if (sourceEnd - sourceStart > target.length - targetStart)
sourceEnd = sourceStart + target.length - targetStart;
if (sourceEnd - sourceStart > target.byteLength - targetStart)
sourceEnd = sourceStart + target.byteLength - targetStart;

let nb = sourceEnd - sourceStart;
const sourceLen = source.length - sourceStart;
const sourceLen = source.byteLength - sourceStart;
if (nb > sourceLen)
nb = sourceLen;

if (sourceStart !== 0 || sourceEnd < source.length)
if (sourceStart !== 0 || sourceEnd < source.byteLength)
source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb);

TypedArrayPrototypeSet(target, source, targetStart);
Expand Down

0 comments on commit 324f2c6

Please sign in to comment.