Offload functions to worker threads with shared memory primitives for Node.js.
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat: Int32 non-atomic shared primitive

+76
+1
src/index.ts
··· 5 5 export type { Runner } from './runner.ts'; 6 6 export type { Loadable } from './shared/index.ts'; 7 7 export { 8 + Int32, 8 9 AtomicBool, 9 10 AtomicInt8, 10 11 AtomicUint8,
+1
src/shared/index.ts
··· 1 1 export type { Loadable } from './loadable.ts'; 2 + export { Int32 } from './int32.ts'; 2 3 export { AtomicBool } from './atomic-bool.ts'; 3 4 export { AtomicInt8 } from './atomic-int8.ts'; 4 5 export { AtomicUint8 } from './atomic-uint8.ts';
+28
src/shared/int32.ts
··· 1 + import { registerSync } from './reconstruct.ts'; 2 + import type { Loadable } from './loadable.ts'; 3 + 4 + export class Int32 implements Loadable<number> { 5 + static readonly byteSize = 4; 6 + static readonly byteAlignment = 4; 7 + private readonly view: Int32Array; 8 + 9 + constructor(buffer?: SharedArrayBuffer, byteOffset?: number) { 10 + const buf = buffer ?? new SharedArrayBuffer(4); 11 + const offset = byteOffset ?? 0; 12 + this.view = new Int32Array(buf, offset, 1); 13 + } 14 + 15 + load(): number { 16 + return this.view[0]; 17 + } 18 + 19 + store(value: number): void { 20 + this.view[0] = value; 21 + } 22 + 23 + [Symbol.for('moroutine.shared')](): { tag: string; buffer: SharedArrayBuffer; byteOffset: number } { 24 + return { tag: 'Int32', buffer: this.view.buffer as SharedArrayBuffer, byteOffset: this.view.byteOffset }; 25 + } 26 + } 27 + 28 + registerSync('Int32', Int32);
+46
test/shared/int32.test.ts
··· 1 + import { describe, it } from 'node:test'; 2 + import assert from 'node:assert/strict'; 3 + import { Int32 } from 'moroutine'; 4 + 5 + describe('Int32', () => { 6 + it('self-allocates and initializes to zero', () => { 7 + const v = new Int32(); 8 + assert.equal(v.load(), 0); 9 + }); 10 + 11 + it('stores and loads a value', () => { 12 + const v = new Int32(); 13 + v.store(42); 14 + assert.equal(v.load(), 42); 15 + }); 16 + 17 + it('accepts an external buffer and byteOffset', () => { 18 + const buffer = new SharedArrayBuffer(16); 19 + const v = new Int32(buffer, 4); 20 + v.store(99); 21 + assert.equal(new Int32Array(buffer, 4, 1)[0], 99); 22 + }); 23 + 24 + it('defaults byteOffset to 0', () => { 25 + const buffer = new SharedArrayBuffer(4); 26 + const v = new Int32(buffer); 27 + v.store(7); 28 + assert.equal(new Int32Array(buffer)[0], 7); 29 + }); 30 + 31 + it('exposes static byteSize of 4', () => { 32 + assert.equal(Int32.byteSize, 4); 33 + }); 34 + 35 + it('exposes static byteAlignment of 4', () => { 36 + assert.equal(Int32.byteAlignment, 4); 37 + }); 38 + 39 + it('does not use Atomics (plain read/write)', () => { 40 + const buffer = new SharedArrayBuffer(4); 41 + const v = new Int32(buffer); 42 + v.store(123); 43 + const raw = new Int32Array(buffer); 44 + assert.equal(raw[0], 123); 45 + }); 46 + });