Created: 2019-09-23 Mon 16:11
.wat
S-expressions
(module
(type (;0;) (func (param i32 i32 i32) (result i32)))
(memory (export "mem") 1)
(import "env" "_memcpy" (func (type 0)))
(func $multiply (param $lhs i32) (param $rhs i32) (result i32)
local.get $lhs
local.get $rhs
i32.mul)
(export "multi" (func $multiply))
(func (export "greeting_") (result i32 i32) (i32.const 0) (i32.const 5))
(data (i32.const 0) "hello"))
wasm32-unknown-emscripten
wasm32-unknown-unknown
emscripten
and barebone
Embedded JS, with interpolation: js!
let button = document().query_selector("#hide-button")?.unwrap();
button.add_event_listener(move |_: ClickEvent| {
for anchor in document().query_selector_all( "#main a" ) {
js!( @{anchor}.style = "display: none;"; );
}
});
#[js_export]
fn hash(string: String) -> String {
let mut hasher = Sha1::new();
hasher.update(string.as_bytes());
hasher.digest().to_string()
}
Targets wasm32-unknown-unknown
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {}!", name));
}
wasm-bindgen
Eventually faster than JS DOM APIs
let document = web_sys::window()?.document()?;
let body = document.body()?;
let val = document.create_element("p")?;
val.set_inner_html("Hello from Rust!");
body.append_child(&val)?;
Supports Rust (wasm-bindgen
)
// synchronous import
import { add } from './add.rs'
console.log(add(2, 3))
// asynchronous import
const { add } = await import('./add.rs')
console.log(add(2, 3))
Direct-copy optimization
(module
(memory (export "mem") 1)
(data (i32.const 0) "hello there")
(func (export "greeting_") (result i32 i32)
i32.const 0 ;; offset of string in memory
i32.const 11 ;; length
)
(@interface func (export "greeting") (result string)
call-export "greeting_"
memory-to-string "mem"))