From 93c80f191056073b403f60bab7ee0084c810d2ee Mon Sep 17 00:00:00 2001 From: Niklas Mischkulnig Date: Tue, 25 Feb 2020 15:01:34 +0100 Subject: [PATCH] Fix Buffer.from for SharedArrayBuffer --- index.js | 5 +++++ package.json | 3 +++ test/node/test-buffer-alloc.js | 8 ++++++++ 3 files changed, 16 insertions(+) diff --git a/index.js b/index.js index 19b0468..8f8b708 100644 --- a/index.js +++ b/index.js @@ -142,6 +142,11 @@ function from (value, encodingOrOffset, length) { return fromArrayBuffer(value, encodingOrOffset, length) } + if (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' diff --git a/package.json b/package.json index 9d9c6e0..494c282 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,9 @@ "test/common.js", "test/_polyfill.js", "perf/**/*.js" + ], + "globals": [ + "SharedArrayBuffer" ] } } diff --git a/test/node/test-buffer-alloc.js b/test/node/test-buffer-alloc.js index 030bad3..5d96e0a 100644 --- a/test/node/test-buffer-alloc.js +++ b/test/node/test-buffer-alloc.js @@ -51,6 +51,14 @@ assert.strictEqual(0, d.length); assert.deepStrictEqual(value, ui32[key]); } } +{ + const sab = new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * 4); + const ui32 = new Uint8Array(sab).fill(42); + const e = Buffer(sab); + for (const [key, value] of e.entries()) { + assert.deepStrictEqual(value, ui32[key]); + } +} // Test invalid encoding for Buffer.toString assert.throws(() => b.toString('invalid'), -- 2.34.1