4

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 = ...?
Tom
  • 8,536
  • 31
  • 133
  • 232
  • maybe slice can help you https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/slice – Vadim Hulevich Jan 09 '19 at 14:40
  • @VadimHulevich how though? calling `slice` on an `ArrayBuffer` returns another `ArrayBuffer`, not a `SharedArrayBuffer` – Tom Jan 09 '19 at 14:42

1 Answers1

7

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

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44