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, string, int32 } from 'moroutine';
4
5describe('string', () => {
6 it('string(n) creates standalone empty string', () => {
7 const s = string(32);
8 assert.equal(s.load(), '');
9 });
10
11 it('shared(string(n)) creates string', () => {
12 const s = shared(string(32));
13 assert.equal(s.load(), '');
14 });
15
16 it('store and load a string', () => {
17 const s = string(32);
18 s.store('hello');
19 assert.equal(s.load(), 'hello');
20 });
21
22 it('store overwrites previous value', () => {
23 const s = string(32);
24 s.store('hello');
25 s.store('world');
26 assert.equal(s.load(), 'world');
27 });
28
29 it('store empty string', () => {
30 const s = string(32);
31 s.store('hello');
32 s.store('');
33 assert.equal(s.load(), '');
34 });
35
36 it('store throws if encoded bytes exceed max', () => {
37 const s = string(4);
38 assert.throws(() => s.store('hello'), /exceeds/i);
39 });
40
41 it('handles multibyte UTF-8', () => {
42 const s = string(32);
43 s.store('héllo');
44 assert.equal(s.load(), 'héllo');
45 });
46
47 it('string in struct schema', () => {
48 const entity = shared({ name: string(16), hp: int32 });
49 entity.store({ name: 'goblin', hp: 50 });
50 assert.deepEqual(entity.load(), { name: 'goblin', hp: 50 });
51 });
52
53 it('string in struct shares one buffer', () => {
54 const entity = shared({ name: string(16), hp: int32 });
55 const SHARED = Symbol.for('moroutine.shared');
56 const nameSer = (entity.fields.name as any)[SHARED]();
57 const hpSer = (entity.fields.hp as any)[SHARED]();
58 assert.equal(nameSer.buffer, hpSer.buffer);
59 });
60});