Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active April 15, 2024 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/51dd8e53eabd25b4a805e9aec80efa48 to your computer and use it in GitHub Desktop.
Save mizchi/51dd8e53eabd25b4a805e9aec80efa48 to your computer and use it in GitHub Desktop.

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment