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
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
  • Loading branch information
ronag authored and targos committed Aug 14, 2024
1 parent 8c9a4ae commit ab6fae9
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 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 @@ -202,9 +203,9 @@ function toInteger(n, defaultVal) {
}

function copyImpl(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 @@ -219,30 +220,30 @@ function copyImpl(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;

Expand Down

0 comments on commit ab6fae9

Please sign in to comment.