buffer: faster type check

Also add support for any TypedArray as target.

PR-URL: https://github.com/nodejs/node/pull/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>
This commit is contained in:
Robert Nagy authored and GitHub committed 2024-08-03 17:15:03 +00:00
1 parent 358ff748ea
commit acbd0be0da
1 file changed
+10 -9
+10 -9
View File
@@ -23,6 +23,7 @@
const {
Array,
ArrayBufferIsView,
ArrayIsArray,
ArrayPrototypeForEach,
MathFloor,
@@ -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) {
@@ -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;