buffer: add Buffer.copyBytesFrom(...)

Fixes: https://github.com/nodejs/node/issues/43862
PR-URL: https://github.com/nodejs/node/pull/46500
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
James M Snell
2023-02-04 14:02:10 -08:00
parent 3c0131a419
commit 311fb041fa
3 changed files with 146 additions and 1 deletions

View File

@@ -43,9 +43,13 @@ const {
StringPrototypeTrim,
SymbolSpecies,
SymbolToPrimitive,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeGetByteLength,
TypedArrayPrototypeGetByteOffset,
TypedArrayPrototypeFill,
TypedArrayPrototypeGetLength,
TypedArrayPrototypeSet,
TypedArrayPrototypeSlice,
Uint8Array,
Uint8ArrayPrototype,
} = primordials;
@@ -330,6 +334,48 @@ Buffer.from = function from(value, encodingOrOffset, length) {
);
};
/**
* Creates the Buffer as a copy of the underlying ArrayBuffer of the view
* rather than the contents of the view.
* @param {TypedArray} view
* @param {number} [offset]
* @param {number} [length]
* @returns {Buffer}
*/
Buffer.copyBytesFrom = function copyBytesFrom(view, offset, length) {
if (!isTypedArray(view)) {
throw new ERR_INVALID_ARG_TYPE('view', [ 'TypedArray' ], view);
}
const viewLength = TypedArrayPrototypeGetLength(view);
if (viewLength === 0) {
return Buffer.alloc(0);
}
if (offset !== undefined || length !== undefined) {
if (offset !== undefined) {
validateInteger(offset, 'offset', 0);
if (offset >= viewLength) return Buffer.alloc(0);
} else {
offset = 0;
}
let end;
if (length !== undefined) {
validateInteger(length, 'length', 0);
end = offset + length;
} else {
end = viewLength;
}
view = TypedArrayPrototypeSlice(view, offset, end);
}
return fromArrayLike(new Uint8Array(
TypedArrayPrototypeGetBuffer(view),
TypedArrayPrototypeGetByteOffset(view),
TypedArrayPrototypeGetByteLength(view)));
};
// Identical to the built-in %TypedArray%.of(), but avoids using the deprecated
// Buffer() constructor. Must use arrow function syntax to avoid automatically
// adding a `prototype` property and making the function a constructor.