Skip to content

Commit e993fc6

Browse files
committed
buffers: faster type check
Also add support for any TypedArray as target. PR-URL: #54088
1 parent 6ad25e3 commit e993fc6

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

lib/buffer.js

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
const {
2525
Array,
26+
ArrayBufferIsView,
2627
ArrayIsArray,
2728
ArrayPrototypeForEach,
2829
MathFloor,
@@ -200,9 +201,9 @@ function toInteger(n, defaultVal) {
200201
}
201202

202203
function _copy(source, target, targetStart, sourceStart, sourceEnd) {
203-
if (!isUint8Array(source))
204+
if (!ArrayBufferIsView(source) || source.length !== source.byteLength)
204205
throw new ERR_INVALID_ARG_TYPE('source', ['Buffer', 'Uint8Array'], source);
205-
if (!isUint8Array(target))
206+
if (!ArrayBufferIsView(target) || target.length !== target.byteLength)
206207
throw new ERR_INVALID_ARG_TYPE('target', ['Buffer', 'Uint8Array'], target);
207208

208209
if (targetStart === undefined) {
@@ -217,34 +218,34 @@ function _copy(source, target, targetStart, sourceStart, sourceEnd) {
217218
sourceStart = 0;
218219
} else {
219220
sourceStart = toInteger(sourceStart, 0);
220-
if (sourceStart < 0 || sourceStart > source.length)
221-
throw new ERR_OUT_OF_RANGE('sourceStart', `>= 0 && <= ${source.length}`, sourceStart);
221+
if (sourceStart < 0 || sourceStart > source.byteLength)
222+
throw new ERR_OUT_OF_RANGE('sourceStart', `>= 0 && <= ${source.byteLength}`, sourceStart);
222223
}
223224

224225
if (sourceEnd === undefined) {
225-
sourceEnd = source.length;
226+
sourceEnd = source.byteLength;
226227
} else {
227228
sourceEnd = toInteger(sourceEnd, 0);
228229
if (sourceEnd < 0)
229230
throw new ERR_OUT_OF_RANGE('sourceEnd', '>= 0', sourceEnd);
230231
}
231232

232-
if (targetStart >= target.length || sourceStart >= sourceEnd)
233+
if (targetStart >= target.byteLength || sourceStart >= sourceEnd)
233234
return 0;
234235

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

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

242243
let nb = sourceEnd - sourceStart;
243-
const sourceLen = source.length - sourceStart;
244+
const sourceLen = source.byteLength - sourceStart;
244245
if (nb > sourceLen)
245246
nb = sourceLen;
246247

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

250251
TypedArrayPrototypeSet(target, source, targetStart);

0 commit comments

Comments
 (0)