[
  {
    "path": ".gitignore",
    "content": "target/\nminiwasm.wasm\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"miniwasm\"\nversion = \"1.0.0\"\nauthors = [\"Emil Loer <emil@koffietijd.net>\"]\nedition = \"2018\"\nlicense = \"MIT\"\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[features]\ndefault = [\"wee_alloc\"]\n\n[dependencies]\nwee_alloc = { version = \"0.4.5\", optional = true }\n\n[profile.release]\nopt-level = \"s\"\nlto = true\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM rust:1.50.0-buster\n\nRUN set -ex; \\\n    apt-get update && \\\n    apt-get install --no-install-recommends -y binaryen wabt && \\\n    rustup target add wasm32-unknown-unknown && \\\n    mkdir -p /app\n\nWORKDIR /app\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright 2021 Emil Loer\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n"
  },
  {
    "path": "README.md",
    "content": "# MiniWASM - A minimalist Rust WebAssembly project template\n\nThis is a minimal Rust-powered WebAssembly application template. It was\ndesigned to showcase what must be done to get Rust-powered WebAssembly going\nwith only a small amount of code, while still providing useful tools, such as\nintegration with `console.log`.\n\n## How to build?\n\nThe easiest way is to install Docker on your system and run the\n`docker-shell.sh` script. This script builds a Docker image containing Rust,\nthe wasm32-unknown-unknown target, and a couple of dependencies for optimizing\nthe generated `.wasm` files.\n\nAfter building the Docker image the script then launches a container with that\nimage, giving you a shell with a proper build environment. Alternatively you\ncan just install Rust and the `wasm32` target on your host machine, and also\ninstall `binaryen` and `wabt`.\n\nEither way, after opening a shell with a build environment, you can just run\nthe `build.sh` script. This builds the `miniwasm.wasm` file and runs it\nthrough the optimizer to reduce the file size.\n\nNow that you have the compiled WebAssembly file you can run the `serve.sh`\nscript. This runs a web server in the current working directory (thanks to\nPython). You can then go to `http://localhost:8000/` to view the application.\nOpen the console to see the log messages that the WebAssembly produces.\n\n## Why not wasm-bindgen or wasm-pack?\n\nWasm-bindgen is awesome, so use it when you can. I myself am working on\nprojects that have more strict performance requirements, and wasm-bindgen's\ntranslation layer often gets in the way of performance when I need to pass\ndata back and forth between Rust and JavaScript. Therefore I created MiniWASM\nas a template to quickly prototype new experiments for my algorithms.\n\nAnother reason why you might want to use MiniWASM as a starting point is that\nyou want to build something small and don't want to depend on wasm-pack's NPM\npackages.\n\n## Compatibility\n\nThis application template should be compatible with all modern browsers.\nHowever, it has only been tested with Chrome 88 and Safari 14. It will\nprobably work fine in Firefox too though.\n\n## Technical details\n\nThis project consists of two components:\n\n1. A Rust file serving as the entry point for the WebAssembly application.\n2. An HTML file with embedded JavaScript code to bootstrap the WebAssembly\n   application.\n\n### The Rust WebAssembly application\n\nThe Rust WebAssembly application is a single-file crate that performs a few\nfunctions:\n\n1. It sets up `wee_alloc` as the memory allocator.\n\n2. It has a bridge to send log messages to JavaScript. This is done by\n   importing some proxy functions (one for `console.log` and one for\n   `console.error`) and calling them with the address and length of a `&str`.\n\n   The JavaScript implementation of these functions then looks into the\n   WebAssembly application's `WebAssembly.Memory` instance and extracts the\n   characters, converting the raw bytes back into a JavaScript-representation\n   before handing them off to the JavaScript console functions.\n\n3. It defines a struct that holds the application's global state and stores\n   this in a cell in thread local storage.\n\n4. It defines functions that act as a bridge between the WebAssembly module's\n   external interface and the application struct.\n\n5. It has a bootstrapping function that sets up a new panic handler so that we\n   can see panics in the JavaScript console.\n\n### JavaScript bootstrapping code\n\nInstantiating a WebAssembly module is easy. We just have to fetch the `.wasm`\nfile and pass its contents into `WebAssembly.instantiate`.\n\nTo get logging to work we need to do a little bit more though. When\ninstantiating the WebAssembly module we provide an import descriptor that\nexposes `console.log` and `console.error`. We can't expose those functions\ndirectly though, because WebAssembly's calling convention only allows us to\nuse primitive types as arguments and return values. Therefore we wrap the\nlogging functions with a function that takes the location of a string slice\nand extracts the bytes from the WebAssembly application's `Memory` instance.\nThese bytes are converted into a JavaScript string and then handed off to the\nlogging function.\n\n## License\n\nCopyright 2021 Emil Loer.\n\nThis project is licensed under the MIT license. A copy of the license can be\nfound in the project repository.\n"
  },
  {
    "path": "build.sh",
    "content": "#!/bin/bash\n\nset -e\n\nTARGET_PATH=\"target/wasm32-unknown-unknown/release/miniwasm.wasm\"\n\n# Build the wasm32 release target\ncargo build --target wasm32-unknown-unknown --release --lib\n\n# Run the wasm optimizer\nwasm-opt ${TARGET_PATH} -o ${TARGET_PATH} -Oz --strip-debug --strip-producers --vacuum\n\n# Copy the wasm file to the root directory so it can be served.\ncp ${TARGET_PATH} ./miniwasm.wasm\n"
  },
  {
    "path": "docker-shell.sh",
    "content": "#!/bin/bash\n\n# This script builds the development docker image and runs it with port\n# 8000 exposed. It also mounts the current working directory in to /app\n# inside the container so you can use an editor that is running outside\n# of the container.\n\nset -e\n\ndocker build -t miniwasm -f Dockerfile .\n\ndocker run -ti --mount type=bind,source=\"$PWD\",target=/app -p 8000:8000 miniwasm\n"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <meta charset=\"utf-8\">\n        <title>MiniWASM</title>\n    </head>\n\n    <body>\n        <h1>MiniWASM</h1>\n        <p>Open the development console to see log messages.</p>\n\n        <script>\n            class MiniBridge {\n                async bootstrap(url) {\n                    // Fetch wasm file\n                    const response = await fetch(url);\n                    if (!response.ok) {\n                        throw Error(\"Error loading wasm file: \" + response.status);\n                    }\n\n                    // Instantiate WebAssembly context\n                    const data = await response.arrayBuffer();\n                    const webAssembly = await WebAssembly.instantiate(data, {\n                        env: {\n                            console_log: this.extractString(console.log),\n                            console_error: this.extractString(console.error)\n                        }\n                    });\n\n                    // Grab the wasm instance and its memory (wrapped in an Uint8Array)\n                    this.wasm = webAssembly.instance;\n                    this.buffer = new Uint8Array(this.wasm.exports.memory.buffer);\n\n                    // Call the wasm module's entry point\n                    this.wasm.exports.initialize();\n                }\n\n                extractString = fn => (ptr, len) => {\n                    // Get a fresh Uint8Array if the wasm memory buffer was moved\n                    const buffer = this.wasm.exports.memory.buffer;\n                    if (this.buffer !== buffer) {\n                        this.buffer = new Uint8Array(buffer);\n                    }\n\n                    // Make a string from the slice of memory and pass it into fn\n                    fn(String.fromCharCode.apply(null, this.buffer.slice(ptr, ptr + len)));\n                }\n            }\n\n            const bridge = new MiniBridge();\n\n            bridge.bootstrap(\"miniwasm.wasm\").then(function() {\n                console.log(\"Bootstrap completed, now go build something awesome!\");\n\n                // Call example function\n                const value = bridge.wasm.exports.hello(256);\n                console.log(\"The value returned by hello() was \" + value);\n            });\n        </script>\n    </body>\n</html>\n"
  },
  {
    "path": "serve.sh",
    "content": "#!/bin/bash\n\nset -e\n\n# Run Python's built-in web server.\npython3 -m http.server\n"
  },
  {
    "path": "src/lib.rs",
    "content": "//! This is a minimal WebAssembly application. It was designed to showcase what must be done to get\n//! Rust-powered WebAssembly going with only a small amount of code, while still providing useful\n//! tools, such as integration with console.log.\n\nuse std::cell::RefCell;\nuse std::panic;\n\n/// Use wee_alloc as the global allocator\n#[cfg(feature = \"wee_alloc\")]\n#[global_allocator]\nstatic ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;\n\nthread_local! {\n    /// Assign some memory to global state. We don't use lazy_alloc or something similar to prevent\n    /// pulling in a lot of threading code. This of course limits this example to a single threaded\n    /// application, but that's fine for most use cases.\n    /// \n    /// Note: wrapping the RefCell in a Box appears to result in smaller code size\n    static APP: Box<RefCell<App>> = Box::new(RefCell::new(App::new()));\n}\n\n/// A custom panic handler that delegates to console.error so we can see panics inside the browser\n/// console.\nfn panic_handler(info: &panic::PanicInfo) {\n    error(&info.to_string());\n}\n\n/// Import some callbacks that map to console functions.\nextern \"C\" {\n    #[link_name=\"console_log\"]\n    fn _console_log(a_ptr: *const u8, a_len: usize);\n\n    #[link_name=\"console_error\"]\n    fn _console_error(a_ptr: *const u8, a_len: usize);\n}\n\n/// A helper function to wrap an unsafe external callback (that requires memory addresses) with a\n/// function that accepts a &str. The &str is split into an address/length tuple so the\n/// JavaScript-side knows where to find its argument.\nfn wrap(s: &str, f: unsafe extern \"C\" fn(*const u8, usize)) {\n    let ptr = s.as_ptr();\n    let len = s.len();\n\n    unsafe {\n        f(ptr, len);\n    }\n}\n\n/// Forward the provided &str to JavaScript's console.log\npub fn log(s: &str) {\n    wrap(s, _console_log);\n}\n\n/// Forward the provided &str to JavaScript's console.error\npub fn error(s: &str) {\n    wrap(s, _console_error);\n}\n\n/// Initialization entry point for the WebAssembly module. This sets a new panic handler and calls\n/// the initialize function on the global App instance.\n#[no_mangle]\npub extern \"C\" fn initialize() {\n    panic::set_hook(Box::new(panic_handler));\n\n    APP.with(|k| k.borrow_mut().initialize());\n}\n\n/// Example exported custom function. This one calls a method on the App instance and returns its\n/// result. Note that calling methods from the App instance is optional, but this approach makes\n/// things more flexible by providing a container for global state.\n#[no_mangle]\npub extern \"C\" fn hello(arg: u32) -> u32 {\n    APP.with(|k| k.borrow_mut().hello(arg))\n}\n\n/// The WebAssembly application's global state struct.\nstruct App {\n}\n\nimpl App {\n    /// Create a new App instance. This is called by thread_local! on first use of the global\n    /// instance.\n    fn new() -> Self {\n        Self {\n        }\n    }\n\n    /// Initialize the application here.\n    fn initialize(&self) {\n        log(\"App initialized\");\n    }\n\n    /// Example custom function\n    fn hello(&self, arg: u32) -> u32 {\n        log(\"Hello, world!\");\n\n        // Return an example value. Note that WebAssembly's calling convention only allows us to\n        // accept/return primitive types and pointers to said types.\n        arg * arg\n    }\n}\n"
  }
]