Offload functions to worker threads with shared memory primitives for Node.js.
1import { describe, it } from 'node:test';
2import assert from 'node:assert/strict';
3import { shared, int32, int64, bool } from 'moroutine';
4
5describe('shared() tuple', () => {
6 it('creates a tuple from array schema', () => {
7 const t = shared([int32, int64]);
8 assert.deepEqual(t.load(), [0, 0n]);
9 });
10
11 it('store writes all elements', () => {
12 const t = shared([int32, int64, bool]);
13 t.store([42, 99n, true]);
14 assert.deepEqual(t.load(), [42, 99n, true]);
15 });
16
17 it('elements provides direct access to each Loadable', () => {
18 const t = shared([int32, int32]);
19 t.elements[0].store(10);
20 t.elements[1].store(20);
21 assert.deepEqual(t.load(), [10, 20]);
22 });
23
24 it('length returns fixed element count', () => {
25 const t = shared([int32, int32, bool]);
26 assert.equal(t.length, 3);
27 });
28
29 it('tuple elements share one buffer', () => {
30 const t = shared([int32, int32]);
31 const SHARED = Symbol.for('moroutine.shared');
32 const s0 = (t.elements[0] as any)[SHARED]();
33 const s1 = (t.elements[1] as any)[SHARED]();
34 assert.equal(s0.buffer, s1.buffer);
35 });
36
37 it('tuple with struct elements', () => {
38 const t = shared([
39 { x: int32, y: int32 },
40 { x: int32, y: int32 },
41 ]);
42 t.store([
43 { x: 1, y: 2 },
44 { x: 3, y: 4 },
45 ]);
46 assert.deepEqual(t.load(), [
47 { x: 1, y: 2 },
48 { x: 3, y: 4 },
49 ]);
50 });
51
52 it('struct containing tuple field', () => {
53 const s = shared({
54 points: [int32, int32, int32],
55 count: int32,
56 });
57 s.store({ points: [1, 2, 3], count: 3 });
58 assert.deepEqual(s.load(), { points: [1, 2, 3], count: 3 });
59 });
60});