Skip to content

Commit 0832a06

Browse files
committed
chore: wasm chicory samples
1 parent 6d8dc83 commit 0832a06

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed
Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,44 @@
11
package dev.suresh.wasm
22

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
39
import io.ktor.server.response.respondText
410
import io.ktor.server.routing.*
511

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+
}
722

823
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+
}
1034
}
1135

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+
}
140 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)