Offload functions to worker threads with shared memory primitives for Node.js.
1import type { Loadable } from './loadable.ts';
2
3const SHARED = Symbol.for('moroutine.shared');
4
5/** A fixed-size shared byte buffer backed by SharedArrayBuffer. */
6export class Bytes implements Loadable<Readonly<Uint8Array>> {
7 readonly size: number;
8 readonly view: Uint8Array;
9
10 static byteAlignment = 1;
11
12 constructor(size: number, buffer?: SharedArrayBuffer, byteOffset?: number) {
13 this.size = size;
14 const buf = buffer ?? new SharedArrayBuffer(size);
15 const offset = byteOffset ?? 0;
16 this.view = new Uint8Array(buf, offset, size);
17 }
18
19 /**
20 * Returns a readonly view of the buffer. No copy — mutations via `view` are visible.
21 * @returns A readonly typed array view into the shared buffer.
22 */
23 load(): Readonly<Uint8Array> {
24 return this.view as Readonly<Uint8Array>;
25 }
26
27 /**
28 * Writes data into the buffer. Must be exact length.
29 * @param value - A Uint8Array whose length must equal the buffer's size.
30 */
31 store(value: Uint8Array): void {
32 if (value.length !== this.size) {
33 throw new RangeError(`Expected Uint8Array of length ${this.size}, got ${value.length}`);
34 }
35 this.view.set(value);
36 }
37
38 [SHARED](): { tag: string; buffer: SharedArrayBuffer; byteOffset: number; size: number } {
39 return {
40 tag: 'Bytes',
41 buffer: this.view.buffer as SharedArrayBuffer,
42 byteOffset: this.view.byteOffset,
43 size: this.size,
44 };
45 }
46}