How to cast an `ArrayBuffer` to a `SharedArrayBuffer` in Javascript?
Asked Answered
P

1

5

Take the following snippet:

const arr = [1.1, 2.2, 3.3]
const arrBuffer = (Float32Array.from(arr)).buffer

How would one cast this ArrayBuffer to a SharedArrayBuffer?

const sharedArrBuffer = ...?
Ponceau answered 9/1, 2019 at 14:29 Comment(2)
maybe slice can help you developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Edrisedrock
@VadimHulevich how though? calling slice on an ArrayBuffer returns another ArrayBuffer, not a SharedArrayBufferPonceau
P
8

Note that both ArrayBuffer and SharedArrayBuffer are backing data pointers that you only interact with through a typed array (like Float32Array, in your example). Array Buffers represent memory allocations and can't be "cast" (only represented with a typed array).

If you have one typed array already, and need to copy it into a new SharedArrayBuffer, you can do that with set:

// Create a shared float array big enough for 256 floats
let sharedFloats = new Float32Array(new SharedArrayBuffer(1024));

// Copy floats from existing array into this buffer
// existingArray can be a typed array or plain javascript array
sharedFloats.set(existingArray, 0);

(In general, you can have a single array buffer and interact with it through multiple "typed lenses" - so, basically, casting an array buffer into different types, like Float32 and Uint8. But you can't cast an ArrayBuffer to a SharedArrayBuffer, you'll need to copy its contents.)

Paynter answered 9/1, 2019 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.