Skip to content

Commit e7b9d23

Browse files
Add shared memory support to the Swift runtime
1 parent 4c05d63 commit e7b9d23

File tree

3 files changed

+32
-11
lines changed

3 files changed

+32
-11
lines changed

Plugins/PackageToJS/Templates/instantiate.d.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
/* #if USE_SHARED_MEMORY */
2+
import type { SwiftRuntimeThreadChannel } from "./runtime.js";
3+
/* #endif */
4+
15
export type Import = {
26
// TODO: Generate type from imported .d.ts files
37
}
@@ -65,6 +69,7 @@ export declare function instantiate(
6569
/* #endif */
6670
/* #if USE_SHARED_MEMORY */
6771
memory: WebAssembly.Memory
72+
threadChannel: SwiftRuntimeThreadChannel
6873
/* #endif */
6974
}
7075
): Promise<{

Plugins/PackageToJS/Templates/instantiate.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,24 @@ export async function instantiate(
2727
const { wasi } = options;
2828
/* #endif */
2929
const instantiator = await createInstantiator(imports, options);
30-
const swift = new SwiftRuntime();
30+
const swift = new SwiftRuntime({
31+
/* #if USE_SHARED_MEMORY */
32+
sharedMemory: true,
33+
threadChannel: options.threadChannel,
34+
/* #endif */
35+
});
3136

3237
/** @type {WebAssembly.Imports} */
3338
const importObject = {
3439
javascript_kit: swift.wasmImports,
35-
/* #if IS_WASI */
40+
/* #if IS_WASI */
3641
wasi_snapshot_preview1: wasi.wasiImport,
37-
/* #if USE_SHARED_MEMORY */ env: {
42+
/* #if USE_SHARED_MEMORY */
43+
env: {
3844
memory: options.memory,
3945
},
40-
/* #endif */
41-
/* #endif */
46+
/* #endif */
47+
/* #endif */
4248
};
4349
instantiator.addImports(importObject);
4450

Plugins/PackageToJS/Templates/test.js

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,23 @@ Please ensure you are using Node.js v18.x or newer.
3737
returnOnExit: false,
3838
})
3939
const dirname = path.dirname(fileURLToPath(import.meta.url))
40+
const module = await WebAssembly.compile(await readFile(path.join(dirname, MODULE_PATH)))
41+
const options = { wasi }
42+
/* #if USE_SHARED_MEMORY */
43+
// @ts-ignore
44+
const memoryType = WebAssembly.Module.imports(module).find(i => i.module === "env" && i.name === "memory")?.type
45+
const memory = new WebAssembly.Memory({
46+
initial: memoryType.minimum,
47+
maximum: memoryType.maximum,
48+
shared: memoryType.shared,
49+
})
50+
options.memory = memory
51+
/* #endif */
4052
const { swift } = await instantiate(
41-
await readFile(path.join(dirname, MODULE_PATH)),
42-
{}, {
43-
wasi,
44-
/* #if USE_SHARED_MEMORY */
45-
/* #endif */
46-
}
53+
module,
54+
{},
55+
// @ts-ignore
56+
options
4757
)
4858
swift.main()
4959
}

0 commit comments

Comments
 (0)