|
1 | 1 | package dev.suresh.wasm |
2 | 2 |
|
| 3 | +import com.dylibso.chicory.experimental.aot.AotMachine |
| 4 | +import com.dylibso.chicory.runtime.HostFunction |
| 5 | +import com.dylibso.chicory.runtime.Instance |
| 6 | +import com.dylibso.chicory.wasm.Module |
| 7 | +import com.dylibso.chicory.wasm.Parser |
| 8 | +import com.dylibso.chicory.wasm.types.ValueType |
3 | 9 | import io.ktor.server.response.respondText |
4 | 10 | import io.ktor.server.routing.* |
5 | 11 |
|
6 | | -// val factModule by lazy { Parser.parse(::class.java.getResourceAsStream("/fact.wasm")!!) } |
| 12 | +/** |
| 13 | + * More wasm modules can be found in |
| 14 | + * - [wasm-corpus](https://github.com/dylibso/chicory/tree/main/wasm-corpus/src/main/resources/compiled) |
| 15 | + * - [extism](https://github.com/extism/plugins/releases) |
| 16 | + */ |
| 17 | +val factWasmMod: Module by lazy { |
| 18 | + val wasmRes = Thread.currentThread().contextClassLoader.getResourceAsStream("wasm/factorial.wasm") |
| 19 | + // val wasmRes = object {}.javaClass.getResourceAsStream("wasm/factorial.wasm") |
| 20 | + Parser.parse(wasmRes) |
| 21 | +} |
7 | 22 |
|
8 | 23 | fun Routing.wasm() { |
9 | | - get("/wasm") { call.respondText("WASM: WebAssembly") } |
| 24 | + route("/wasm") { |
| 25 | + get("fact") { |
| 26 | + val num = call.parameters["num"]?.toLongOrNull() ?: 5 |
| 27 | + val inst = Instance.builder(factWasmMod).withMachineFactory(::AotMachine).build() |
| 28 | + val iterFact = inst.export("iterFact") |
| 29 | + val fact = iterFact.apply(num)[0] |
| 30 | + |
| 31 | + call.respondText("WASM: Factorial($num): $fact") |
| 32 | + } |
| 33 | + } |
10 | 34 | } |
11 | 35 |
|
12 | | -// https://github.com/extism/plugins/releases |
| 36 | +fun logFunction() = |
| 37 | + HostFunction("console", "log", listOf(ValueType.I32, ValueType.I32), emptyList()) { |
| 38 | + instance, |
| 39 | + args -> |
| 40 | + val msg = instance.memory().readString(args[0].toInt(), args[1].toInt()) |
| 41 | + println("WASM: $msg") |
| 42 | + // Value.i32(0) |
| 43 | + longArrayOf() |
| 44 | + } |
0 commit comments