From c6e722aca4f80801c20b23fb8e1534db7e47dcab Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sat, 4 Feb 2023 14:02:10 -0800 Subject: [PATCH] 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 Reviewed-By: Antoine du Hamel --- doc/api/buffer.md | 22 +++++++++ lib/buffer.js | 46 ++++++++++++++++++ test/parallel/test-buffer-from.js | 79 ++++++++++++++++++++++++++++++- 3 files changed, 146 insertions(+), 1 deletion(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index bb608c852cf3d2..d4ea73a669f87d 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1056,6 +1056,28 @@ console.log(bufA.length); `Buffer.concat()` may also use the internal `Buffer` pool like [`Buffer.allocUnsafe()`][] does. +### Static method: `Buffer.copyBytesFrom(view[, offset[, length]])` + + + +* `view` {TypedArray} The {TypedArray} to copy. +* `offset` {integer} The starting offset within `view`. **Default:**: `0`. +* `length` {integer} The number of elements from `view` to copy. + **Default:** `view.length - offset`. + +Copies the underlying memory of `view` into a new `Buffer`. + +```js +const u16 = new Uint16Array([0, 0xffff]); +const buf = Buffer.copyBytesFrom(u16, 0, 1); +u16[1] = 0; +console.log(buf.length); // 2 +console.log(buf[0]); // 255 +console.log(buf[1]); // 255 +``` + ### Static method: `Buffer.from(array)`