String JS <=> Moonbit
struct MyCtx {
result: String
mut cur: Int
input: @vec.Vec[Int]
}
pub fn app() -> MyCtx {
MyCtx::{
result: "hello", // extracting target
cur: 0,
input: @vec.Vec::new()
}
}
fn MyCtx::next(self: MyCtx) -> Int {
if (self.cur >= self.result.length()) {
return -1
}
let r = self.result[self.cur].to_int()
self.cur += 1
r
}
pub fn reset(buf: MyCtx) -> Unit {
buf.cur = 0
}
pub fn next_char(buf: MyCtx) -> Int {
buf.next()
}
pub fn reset_input(buf: MyCtx) -> Unit {
buf.input.clear()
}
pub fn input(buf: MyCtx, code: Int) -> Unit {
buf.input.push(code)
}
pub fn read_input(buf: MyCtx) -> Unit {
let mut str: String = ""
buf.input.iter(fn (c) {
let char = Char::from_int(c)
str += char.to_string()
});
println("input: \(str)")
}
JS
const obj = await WebAssembly.instantiateStreaming(fetch("/target/wasm-gc/release/build/lib/lib.wasm"), importObject);
memory = obj.instance.exports["moonbit.memory"];
obj.instance.exports._start();
const api = obj.instance.exports;
const decoder = new TextDecoder("utf-16");
function getResult(app) {
api.reset(app);
let next;
let buf = [];
while ((next = api.next_char(app)) !== -1) {
buf.push(next);
}
return decoder.decode(new Uint16Array(buf).valueOf());
}
function write(app, text) {
api.reset_input(app);
const buf = new Uint16Array(new TextEncoder().encode(text));
for (let i = 0; i < buf.length; i++) {
api.input(app, buf[i]);
}
}
const app = api.app();
const str = getResult(app);
console.log(str);
write(app, "Hello, World!");
api.read_input(app);