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 {
4 int8,
5 uint8,
6 int16,
7 uint16,
8 int32,
9 uint32,
10 int64,
11 uint64,
12 bool,
13 int8atomic,
14 uint8atomic,
15 int16atomic,
16 uint16atomic,
17 int32atomic,
18 uint32atomic,
19 int64atomic,
20 uint64atomic,
21 boolatomic,
22 mutex,
23 rwlock,
24} from 'moroutine';
25
26describe('descriptors', () => {
27 it('int32() creates a Loadable<number>', () => {
28 const x = int32();
29 assert.equal(x.load(), 0);
30 x.store(42);
31 assert.equal(x.load(), 42);
32 });
33
34 it('int64() creates a Loadable<bigint>', () => {
35 const x = int64();
36 assert.equal(x.load(), 0n);
37 x.store(99n);
38 assert.equal(x.load(), 99n);
39 });
40
41 it('bool() creates a Loadable<boolean>', () => {
42 const x = bool();
43 assert.equal(x.load(), false);
44 x.store(true);
45 assert.equal(x.load(), true);
46 });
47
48 it('int32atomic() creates an atomic with add/sub/etc', () => {
49 const x = int32atomic();
50 x.store(10);
51 assert.equal(x.add(5), 10);
52 assert.equal(x.load(), 15);
53 });
54
55 it('boolatomic() creates an atomic bool', () => {
56 const x = boolatomic();
57 assert.equal(x.load(), false);
58 x.store(true);
59 assert.equal(x.load(), true);
60 assert.equal(x.exchange(false), true);
61 });
62
63 it('all non-atomic descriptors create loadable values', () => {
64 assert.equal(int8().load(), 0);
65 assert.equal(uint8().load(), 0);
66 assert.equal(int16().load(), 0);
67 assert.equal(uint16().load(), 0);
68 assert.equal(int32().load(), 0);
69 assert.equal(uint32().load(), 0);
70 assert.equal(int64().load(), 0n);
71 assert.equal(uint64().load(), 0n);
72 assert.equal(bool().load(), false);
73 });
74
75 it('all atomic descriptors create loadable values', () => {
76 assert.equal(int8atomic().load(), 0);
77 assert.equal(uint8atomic().load(), 0);
78 assert.equal(int16atomic().load(), 0);
79 assert.equal(uint16atomic().load(), 0);
80 assert.equal(int32atomic().load(), 0);
81 assert.equal(uint32atomic().load(), 0);
82 assert.equal(int64atomic().load(), 0n);
83 assert.equal(uint64atomic().load(), 0n);
84 assert.equal(boolatomic().load(), false);
85 });
86
87 it('mutex() creates a mutex', async () => {
88 const m = mutex();
89 const guard = await m.lock();
90 guard[Symbol.dispose]();
91 });
92
93 it('rwlock() creates a rwlock', async () => {
94 const rw = rwlock();
95 const guard = await rw.readLock();
96 rw.readUnlock();
97 });
98
99 it('descriptors have schema metadata', () => {
100 assert.equal(int32.byteSize, 4);
101 assert.equal(int32.byteAlignment, 4);
102 assert.equal(typeof int32._class, 'function');
103 assert.equal(bool.byteSize, 1);
104 assert.equal(int64.byteSize, 8);
105 assert.equal(mutex.byteSize, 4);
106 });
107});