buffer: improve copy() performance

PR-URL: https://github.com/nodejs/node/pull/29066
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
Brian White authored and Rich Trott committed 2019-08-14 15:59:32 -07:00
1 parent e505a741e3
commit 6d351d4cc0
4 files changed
+105 -10

No files matched your search

+69 -1
View File
@@ -25,7 +25,6 @@ const { Math, Object } = primordials;
const {
byteLengthUtf8,
copy: _copy,
compare: _compare,
compareOffset,
createFromString,
@@ -69,6 +68,7 @@ const {
ERR_INVALID_ARG_VALUE,
ERR_INVALID_BUFFER_SIZE,
ERR_INVALID_OPT_VALUE,
ERR_OUT_OF_RANGE,
ERR_UNKNOWN_ENCODING
},
hideStackFrames
@@ -157,6 +157,74 @@ function showFlaggedDeprecation() {
bufferWarningAlreadyEmitted = true;
}
function toInteger(n, defaultVal) {
n = +n;
if (!Number.isNaN(n) &&
n >= Number.MIN_SAFE_INTEGER &&
n <= Number.MAX_SAFE_INTEGER) {
return ((n % 1) === 0 ? n : Math.floor(n));
}
return defaultVal;
}
function _copy(source, target, targetStart, sourceStart, sourceEnd) {
if (!isUint8Array(source))
throw new ERR_INVALID_ARG_TYPE('source', ['Buffer', 'Uint8Array'], source);
if (!isUint8Array(target))
throw new ERR_INVALID_ARG_TYPE('target', ['Buffer', 'Uint8Array'], target);
if (targetStart === undefined) {
targetStart = 0;
} else {
targetStart = toInteger(targetStart, 0);
if (targetStart < 0)
throw new ERR_OUT_OF_RANGE('targetStart', '>= 0', targetStart);
}
if (sourceStart === undefined) {
sourceStart = 0;
} else {
sourceStart = toInteger(sourceStart, 0);
if (sourceStart < 0)
throw new ERR_OUT_OF_RANGE('sourceStart', '>= 0', sourceStart);
}
if (sourceEnd === undefined) {
sourceEnd = source.length;
} else {
sourceEnd = toInteger(sourceEnd, 0);
if (sourceEnd < 0)
throw new ERR_OUT_OF_RANGE('sourceEnd', '>= 0', sourceEnd);
}
if (targetStart >= target.length || sourceStart >= sourceEnd)
return 0;
if (sourceStart > source.length) {
throw new ERR_OUT_OF_RANGE('sourceStart',
`<= ${source.length}`,
sourceStart);
}
if (sourceEnd - sourceStart > target.length - targetStart)
sourceEnd = sourceStart + target.length - targetStart;
let nb = sourceEnd - sourceStart;
const targetLen = target.length - targetStart;
const sourceLen = source.length - sourceStart;
if (nb > targetLen)
nb = targetLen;
if (nb > sourceLen)
nb = sourceLen;
if (sourceStart !== 0 || sourceEnd !== source.length)
source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb);
target.set(source, targetStart);
return nb;
}
/**
* The Buffer() constructor is deprecated in documentation and should not be
* used moving forward. Rather, developers should use one of the three new