summaryrefslogtreecommitdiff
path: root/src/module.rs
blob: 1fc4100d0e4a426b9f1b0e7ee743bece89d2235d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn log_info(msg: i8) {
    log::info!("{:?}", msg);
}

#[wasm_bindgen(module="/src/js/module.js")]
extern "C" {
    fn js_build_interface() -> js_sys::Object;
}

pub struct Module {
    pub wasm: js_sys::WebAssembly::Instance,
}

impl Module {
    pub async fn new(bytes: &[u8]) -> Option<Self> {
        let imp = js_build_interface();
        let o = wasm_bindgen_futures::JsFuture::from(
            js_sys::WebAssembly::instantiate_buffer(bytes, &imp)
        ).await.unwrap();
        let i = js_sys::Reflect::get(&o, &"instance".into()).unwrap();
        if let Ok(wasm) = i.dyn_into::<js_sys::WebAssembly::Instance>() {
            Some(Self {
                wasm,
            })
        } else {
            log::info!("failed 3");
            None
        }
    }
    pub fn call(&self, nm: &str) {
        let exp = self.wasm.exports();
        if let Ok(fo) = js_sys::Reflect::get(&exp, &nm.into()) {
            if let Ok(func) = fo.dyn_into::<js_sys::Function>() {
                let _ = func.call0(&JsValue::undefined());
            } else {
                log::warn!("couldn't cast module function: {}", nm);
            }
        } else {
            log::warn!("couldn't find module function: {}", nm);
        }
    }
}