From 21a58310f0ba4c0150bde470c1e0596af125b790 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Mon, 29 Jul 2024 00:18:18 +0200 Subject: [PATCH] buffers: faster type check Also add support for any TypedArray as target. PR-URL: https://github.com/nodejs/node/pull/54088 --- lib/buffer.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 823a9249eccc52..2d5405ec7b5e61 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -23,6 +23,7 @@ const { Array, + ArrayBufferIsView, ArrayIsArray, ArrayPrototypeForEach, MathFloor, @@ -200,9 +201,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) { @@ -217,34 +218,34 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) { sourceStart = 0; } else { 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 = 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);