Something went wrong. Try again.
Offload functions to worker threads with shared memory primitives for Node.js.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import { describe, it } from 'node:test';import assert from 'node:assert/strict';import { shared, int32, int64, bool, mutex } from 'moroutine';
describe('shared()', () => { it('shared(descriptor) creates a standalone instance', () => { const x = shared(int32); assert.equal(x.load(), 0); x.store(42); assert.equal(x.load(), 42); });
it('shared(struct schema) creates a struct with fields', () => { const point = shared({ x: int32, y: int32 }); assert.deepEqual(point.load(), { x: 0, y: 0 }); point.store({ x: 10, y: 20 }); assert.deepEqual(point.load(), { x: 10, y: 20 }); });
it('struct fields are accessible via .fields', () => { const point = shared({ x: int32, y: int32 }); point.fields.x.store(42); assert.equal(point.fields.x.load(), 42); assert.equal(point.fields.y.load(), 0); });
it('struct with mixed types', () => { const state = shared({ hp: int32, alive: bool }); state.store({ hp: 100, alive: true }); assert.deepEqual(state.load(), { hp: 100, alive: true }); });
it('nested struct schema', () => { const rect = shared({ pos: { x: int32, y: int32 }, size: { w: int32, h: int32 }, }); rect.store({ pos: { x: 1, y: 2 }, size: { w: 100, h: 50 } }); assert.deepEqual(rect.load(), { pos: { x: 1, y: 2 }, size: { w: 100, h: 50 }, }); });
it('nested struct fields accessible', () => { const rect = shared({ pos: { x: int32, y: int32 }, w: int32, }); rect.fields.pos.fields.x.store(99); rect.fields.w.store(200); assert.deepEqual(rect.load(), { pos: { x: 99, y: 0 }, w: 200 }); });
it('struct with mutex excludes mutex from load/store', () => { const state = shared({ x: int32, mu: mutex }); state.store({ x: 42 }); assert.deepEqual(state.load(), { x: 42 }); });
it('struct mutex accessible via fields', async () => { const state = shared({ x: int32, mu: mutex }); const guard = await state.fields.mu.lock(); guard[Symbol.dispose](); });
it('struct fields share one SharedArrayBuffer', () => { const point = shared({ x: int32, y: int32 }); const SHARED = Symbol.for('moroutine.shared'); const xSync = (point.fields.x as any)[SHARED](); const ySync = (point.fields.y as any)[SHARED](); assert.equal(xSync.buffer, ySync.buffer); });});