Search code examples
javascriptnode.jsarraybuffertyped-arrayssharedarraybuffer

How to cast an `ArrayBuffer` to a `SharedArrayBuffer` in Javascript?


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 = ...?

Solution

  • 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.)