Exclosured.Inline (exclosured v0.1.4)

Copy Markdown

Define small WASM functions inline in Elixir using defwasm.

The Rust code is compiled to a standalone .wasm file at build time, then processed with wasm-bindgen for JS interop. No Cargo workspace, no .rs files needed. Just Rust inside Elixir.

Example

defmodule MyApp.Math do
  use Exclosured.Inline
  defwasm :add, args: [a: :i32, b: :i32], do: ~RUST"a + b"
end

defmodule MyApp.Filters do
  use Exclosured.Inline

  defwasm :grayscale, args: [pixels: :binary] do
    ~RUST"""
    for chunk in pixels.chunks_exact_mut(4) {
        let gray = (0.299 * chunk[0] as f32
                  + 0.587 * chunk[1] as f32
                  + 0.114 * chunk[2] as f32) as u8;
        chunk[0] = gray;
        chunk[1] = gray;
        chunk[2] = gray;
    }
    """
  end
end

Use ~RUST instead of ~S to enable Rust syntax highlighting in editors.

After mix compile:

  • priv/static/wasm/my_app_filters/my_app_filters_bg.wasm is generated
  • MyApp.Filters.wasm_url() returns "/wasm/my_app_filters/my_app_filters_bg.wasm"
  • MyApp.Filters.wasm_js_url() returns "/wasm/my_app_filters/my_app_filters.js"
  • Functions are callable from the browser via the JS loader

Supported Arg Types

  • :binary: allocated in WASM memory, passed as (ptr, len), mutable
  • :string: allocated in WASM memory, passed as (ptr, len), read-only
  • :i32, :u32, :f32, :f64: passed directly as WASM values

Summary

Functions

Define an inline WASM function.

A sigil for inline Rust code. Works like ~S (no interpolation), but signals to editor extensions that the content is Rust source.

Functions

defwasm(name, opts)

(macro)

Define an inline WASM function.

The body must be a string containing Rust code that operates on the declared arguments. The generated Rust function receives proper FFI types automatically based on the arg type declarations.

Options

  • :args - keyword list of name: type (default: [])
  • :return - return type (default: :i32)
  • :deps - list of extra Cargo dependencies as {name, version} tuples (default: []). These are added to the generated Cargo.toml. Example: deps: [{"serde", "1"}, {"serde_json", "1"}]

defwasm(name, opts, list)

(macro)

sigil_RUST(term, modifiers)

(macro)

A sigil for inline Rust code. Works like ~S (no interpolation), but signals to editor extensions that the content is Rust source.

Example

defwasm :add, args: [a: :i32, b: :i32] do
  ~RUST"a + b"
end

defwasm :hash, args: [data: :binary] do
  ~RUST\"\"\"
  let mut hash: u32 = 5381;
  for &byte in data.iter() {
      hash = hash.wrapping_mul(33).wrapping_add(byte as u32);
  }
  hash as i32
  \"\"\"
end