├── .gitignore ├── serve.sh ├── Dockerfile ├── Cargo.toml ├── docker-shell.sh ├── LICENSE ├── Cargo.lock ├── index.html ├── src └── lib.rs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | miniwasm.wasm 3 | -------------------------------------------------------------------------------- /serve.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | # Run Python's built-in web server. 6 | python3 -m http.server 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rust:1.50.0-buster 2 | 3 | RUN set -ex; \ 4 | apt-get update && \ 5 | apt-get install --no-install-recommends -y binaryen wabt && \ 6 | rustup target add wasm32-unknown-unknown && \ 7 | mkdir -p /app 8 | 9 | WORKDIR /app 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "miniwasm" 3 | version = "1.0.0" 4 | authors = ["Emil Loer "] 5 | edition = "2018" 6 | license = "MIT" 7 | 8 | [lib] 9 | crate-type = ["cdylib", "rlib"] 10 | 11 | [features] 12 | default = ["wee_alloc"] 13 | 14 | [dependencies] 15 | wee_alloc = { version = "0.4.5", optional = true } 16 | 17 | [profile.release] 18 | opt-level = "s" 19 | lto = true 20 | -------------------------------------------------------------------------------- /docker-shell.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script builds the development docker image and runs it with port 4 | # 8000 exposed. It also mounts the current working directory in to /app 5 | # inside the container so you can use an editor that is running outside 6 | # of the container. 7 | 8 | set -e 9 | 10 | docker build -t miniwasm -f Dockerfile . 11 | 12 | docker run -ti --mount type=bind,source="$PWD",target=/app -p 8000:8000 miniwasm 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2021 Emil Loer 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "cfg-if" 5 | version = "0.1.10" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 8 | 9 | [[package]] 10 | name = "libc" 11 | version = "0.2.88" 12 | source = "registry+https://github.com/rust-lang/crates.io-index" 13 | checksum = "03b07a082330a35e43f63177cc01689da34fbffa0105e1246cf0311472cac73a" 14 | 15 | [[package]] 16 | name = "memory_units" 17 | version = "0.4.0" 18 | source = "registry+https://github.com/rust-lang/crates.io-index" 19 | checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" 20 | 21 | [[package]] 22 | name = "miniwasm" 23 | version = "1.0.0" 24 | dependencies = [ 25 | "wee_alloc", 26 | ] 27 | 28 | [[package]] 29 | name = "wee_alloc" 30 | version = "0.4.5" 31 | source = "registry+https://github.com/rust-lang/crates.io-index" 32 | checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" 33 | dependencies = [ 34 | "cfg-if", 35 | "libc", 36 | "memory_units", 37 | "winapi", 38 | ] 39 | 40 | [[package]] 41 | name = "winapi" 42 | version = "0.3.9" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 45 | dependencies = [ 46 | "winapi-i686-pc-windows-gnu", 47 | "winapi-x86_64-pc-windows-gnu", 48 | ] 49 | 50 | [[package]] 51 | name = "winapi-i686-pc-windows-gnu" 52 | version = "0.4.0" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 55 | 56 | [[package]] 57 | name = "winapi-x86_64-pc-windows-gnu" 58 | version = "0.4.0" 59 | source = "registry+https://github.com/rust-lang/crates.io-index" 60 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 61 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | MiniWASM 6 | 7 | 8 | 9 |

MiniWASM

10 |

Open the development console to see log messages.

11 | 12 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This is a minimal WebAssembly application. It was designed to showcase what must be done to get 2 | //! Rust-powered WebAssembly going with only a small amount of code, while still providing useful 3 | //! tools, such as integration with console.log. 4 | 5 | use std::cell::RefCell; 6 | use std::panic; 7 | 8 | /// Use wee_alloc as the global allocator 9 | #[cfg(feature = "wee_alloc")] 10 | #[global_allocator] 11 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 12 | 13 | thread_local! { 14 | /// Assign some memory to global state. We don't use lazy_alloc or something similar to prevent 15 | /// pulling in a lot of threading code. This of course limits this example to a single threaded 16 | /// application, but that's fine for most use cases. 17 | /// 18 | /// Note: wrapping the RefCell in a Box appears to result in smaller code size 19 | static APP: Box> = Box::new(RefCell::new(App::new())); 20 | } 21 | 22 | /// A custom panic handler that delegates to console.error so we can see panics inside the browser 23 | /// console. 24 | fn panic_handler(info: &panic::PanicInfo) { 25 | error(&info.to_string()); 26 | } 27 | 28 | /// Import some callbacks that map to console functions. 29 | extern "C" { 30 | #[link_name="console_log"] 31 | fn _console_log(a_ptr: *const u8, a_len: usize); 32 | 33 | #[link_name="console_error"] 34 | fn _console_error(a_ptr: *const u8, a_len: usize); 35 | } 36 | 37 | /// A helper function to wrap an unsafe external callback (that requires memory addresses) with a 38 | /// function that accepts a &str. The &str is split into an address/length tuple so the 39 | /// JavaScript-side knows where to find its argument. 40 | fn wrap(s: &str, f: unsafe extern "C" fn(*const u8, usize)) { 41 | let ptr = s.as_ptr(); 42 | let len = s.len(); 43 | 44 | unsafe { 45 | f(ptr, len); 46 | } 47 | } 48 | 49 | /// Forward the provided &str to JavaScript's console.log 50 | pub fn log(s: &str) { 51 | wrap(s, _console_log); 52 | } 53 | 54 | /// Forward the provided &str to JavaScript's console.error 55 | pub fn error(s: &str) { 56 | wrap(s, _console_error); 57 | } 58 | 59 | /// Initialization entry point for the WebAssembly module. This sets a new panic handler and calls 60 | /// the initialize function on the global App instance. 61 | #[no_mangle] 62 | pub extern "C" fn initialize() { 63 | panic::set_hook(Box::new(panic_handler)); 64 | 65 | APP.with(|k| k.borrow_mut().initialize()); 66 | } 67 | 68 | /// Example exported custom function. This one calls a method on the App instance and returns its 69 | /// result. Note that calling methods from the App instance is optional, but this approach makes 70 | /// things more flexible by providing a container for global state. 71 | #[no_mangle] 72 | pub extern "C" fn hello(arg: u32) -> u32 { 73 | APP.with(|k| k.borrow_mut().hello(arg)) 74 | } 75 | 76 | /// The WebAssembly application's global state struct. 77 | struct App { 78 | } 79 | 80 | impl App { 81 | /// Create a new App instance. This is called by thread_local! on first use of the global 82 | /// instance. 83 | fn new() -> Self { 84 | Self { 85 | } 86 | } 87 | 88 | /// Initialize the application here. 89 | fn initialize(&self) { 90 | log("App initialized"); 91 | } 92 | 93 | /// Example custom function 94 | fn hello(&self, arg: u32) -> u32 { 95 | log("Hello, world!"); 96 | 97 | // Return an example value. Note that WebAssembly's calling convention only allows us to 98 | // accept/return primitive types and pointers to said types. 99 | arg * arg 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MiniWASM - A minimalist Rust WebAssembly project template 2 | 3 | This is a minimal Rust-powered WebAssembly application template. It was 4 | designed to showcase what must be done to get Rust-powered WebAssembly going 5 | with only a small amount of code, while still providing useful tools, such as 6 | integration with `console.log`. 7 | 8 | ## How to build? 9 | 10 | The easiest way is to install Docker on your system and run the 11 | `docker-shell.sh` script. This script builds a Docker image containing Rust, 12 | the wasm32-unknown-unknown target, and a couple of dependencies for optimizing 13 | the generated `.wasm` files. 14 | 15 | After building the Docker image the script then launches a container with that 16 | image, giving you a shell with a proper build environment. Alternatively you 17 | can just install Rust and the `wasm32` target on your host machine, and also 18 | install `binaryen` and `wabt`. 19 | 20 | Either way, after opening a shell with a build environment, you can just run 21 | the `build.sh` script. This builds the `miniwasm.wasm` file and runs it 22 | through the optimizer to reduce the file size. 23 | 24 | Now that you have the compiled WebAssembly file you can run the `serve.sh` 25 | script. This runs a web server in the current working directory (thanks to 26 | Python). You can then go to `http://localhost:8000/` to view the application. 27 | Open the console to see the log messages that the WebAssembly produces. 28 | 29 | ## Why not wasm-bindgen or wasm-pack? 30 | 31 | Wasm-bindgen is awesome, so use it when you can. I myself am working on 32 | projects that have more strict performance requirements, and wasm-bindgen's 33 | translation layer often gets in the way of performance when I need to pass 34 | data back and forth between Rust and JavaScript. Therefore I created MiniWASM 35 | as a template to quickly prototype new experiments for my algorithms. 36 | 37 | Another reason why you might want to use MiniWASM as a starting point is that 38 | you want to build something small and don't want to depend on wasm-pack's NPM 39 | packages. 40 | 41 | ## Compatibility 42 | 43 | This application template should be compatible with all modern browsers. 44 | However, it has only been tested with Chrome 88 and Safari 14. It will 45 | probably work fine in Firefox too though. 46 | 47 | ## Technical details 48 | 49 | This project consists of two components: 50 | 51 | 1. A Rust file serving as the entry point for the WebAssembly application. 52 | 2. An HTML file with embedded JavaScript code to bootstrap the WebAssembly 53 | application. 54 | 55 | ### The Rust WebAssembly application 56 | 57 | The Rust WebAssembly application is a single-file crate that performs a few 58 | functions: 59 | 60 | 1. It sets up `wee_alloc` as the memory allocator. 61 | 62 | 2. It has a bridge to send log messages to JavaScript. This is done by 63 | importing some proxy functions (one for `console.log` and one for 64 | `console.error`) and calling them with the address and length of a `&str`. 65 | 66 | The JavaScript implementation of these functions then looks into the 67 | WebAssembly application's `WebAssembly.Memory` instance and extracts the 68 | characters, converting the raw bytes back into a JavaScript-representation 69 | before handing them off to the JavaScript console functions. 70 | 71 | 3. It defines a struct that holds the application's global state and stores 72 | this in a cell in thread local storage. 73 | 74 | 4. It defines functions that act as a bridge between the WebAssembly module's 75 | external interface and the application struct. 76 | 77 | 5. It has a bootstrapping function that sets up a new panic handler so that we 78 | can see panics in the JavaScript console. 79 | 80 | ### JavaScript bootstrapping code 81 | 82 | Instantiating a WebAssembly module is easy. We just have to fetch the `.wasm` 83 | file and pass its contents into `WebAssembly.instantiate`. 84 | 85 | To get logging to work we need to do a little bit more though. When 86 | instantiating the WebAssembly module we provide an import descriptor that 87 | exposes `console.log` and `console.error`. We can't expose those functions 88 | directly though, because WebAssembly's calling convention only allows us to 89 | use primitive types as arguments and return values. Therefore we wrap the 90 | logging functions with a function that takes the location of a string slice 91 | and extracts the bytes from the WebAssembly application's `Memory` instance. 92 | These bytes are converted into a JavaScript string and then handed off to the 93 | logging function. 94 | 95 | ## License 96 | 97 | Copyright 2021 Emil Loer. 98 | 99 | This project is licensed under the MIT license. A copy of the license can be 100 | found in the project repository. 101 | --------------------------------------------------------------------------------