skip to content

With Rust's wasm-bindgen, what is copied when JavaScript calls `label(filter_name: &str) -> String` and `blur_row(pixels: &mut [u8], kernel: &Kernel)`?

level: middleimportance: should knowfreq 32%

answer

  1. two heaps, one linear memory
  2. TextEncoder in, TextDecoder out
  3. unpaired surrogates become U+FFFD
  4. mutable slices are copied back
  5. an exported struct is a handle

basics

~20 s

The string is re-encoded as UTF-8 into linear memory, the returned String is decoded into a new JavaScript string, and the pixels are copied in and back out. The #[wasm_bindgen] struct stays in wasm memory behind a handle.

solid answer

~50 s

JavaScript strings are UTF-16 values in the JavaScript heap, and Rust reads only linear memory. For the `&str` parameter the generated glue allocates with the module's exported allocator and encodes with `TextEncoder`; Rust borrows those UTF-8 bytes for the call, and any unpaired surrogate arrives as U+FFFD. The returned `String` is decoded with `TextDecoder` into a fresh JavaScript string. For `&mut [u8]`, wasm-bindgen copies the typed array's contents into a Rust buffer and, when the borrow ends, copies them back into the original array, so the page sees the edits. `kernel: &Kernel` copies nothing: a `#[wasm_bindgen]` struct lives in linear memory and JavaScript holds a class instance wrapping its pointer. A plain struct cannot appear in the signature: rustc rejects it with E0277, naming `FromWasmAbi` by value or `RefFromWasmAbi` by reference. To avoid copies, pass `js_sys::JsString` handles or keep buffers on the Rust side.

code

rust · 33 lines
rust
use wasm_bindgen::prelude::*;

/// Lives in wasm memory; JavaScript holds a handle made by `new Kernel(1)`.
#[wasm_bindgen]
pub struct Kernel {
    radius: usize,
}

#[wasm_bindgen]
impl Kernel {
    #[wasm_bindgen(constructor)]
    pub fn new(radius: usize) -> Kernel {
        Kernel { radius }
    }
}

/// Box-blurs one row of RGBA pixels in place, channel by channel.
#[wasm_bindgen]
pub fn blur_row(pixels: &mut [u8], kernel: &Kernel) {
    let (src, n) = (pixels.to_vec(), pixels.len() / 4);
    for i in 0..n {
        let (lo, hi) = (i.saturating_sub(kernel.radius), (i + kernel.radius).min(n - 1));
        for c in 0..3 {
            let sum: usize = (lo..=hi).map(|j| src[j * 4 + c] as usize).sum();
            pixels[i * 4 + c] = (sum / (hi - lo + 1)) as u8;
        }
    }
}

#[wasm_bindgen]
pub fn label(filter_name: &str) -> String {
    format!("{filter_name}: {} bytes of UTF-8", filter_name.len())
}

go deeper

for a junior

Recall that strings and byte slices are copied between JavaScript and linear memory, and that a struct needs #[wasm_bindgen] before it can appear in an exported signature.

for a middle

Walk through the mechanics: the exported allocator, TextEncoder for a &str argument, TextDecoder for a returned String, and the copy back into the typed array after a &mut [u8] call.

for a senior

Bring the performance and correctness consequences: per-frame copies of large buffers, unpaired surrogates turned into U+FFFD, and unsafe views that a memory growth invalidates.

for a principal

Frame the interface design: which data should live in Rust behind handles and which should cross as copies, given how often the page calls in and how large each payload is.

## Two heaps and one shared byte array A WebAssembly instance owns one **linear memory**: a resizable array of bytes that Rust uses for its stack, statics and heap. JavaScript can see that memory as an `ArrayBuffer`, but its own values, strings, objects and typed arrays, live in the **JavaScript heap**, which Rust cannot address. Every non-numeric value that crosses therefore either gets **copied** into or out of linear memory, or stays where it is and crosses as a **handle**. wasm-bindgen picks one per type; the type in the signature decides the cost. The image-filter crate below exports a string function, a mutable-slice function and a struct; the CLI then generates the matching JavaScript. ## Strings: re-encoded both ways JavaScript strings are **UTF-16**, while a Rust `&str` must be valid **UTF-8**. wasm-bindgen's guide states that string contents are copied back and forth between the JavaScript heap and linear memory with `TextEncoder` and `TextDecoder`. 1. For a `&str` **parameter**, the glue allocates through the module's exported allocator (`__wbindgen_malloc`), encodes the string into that buffer, and passes a pointer and a byte length; Rust borrows it for the duration of the call. 2. For a `String` **return value**, Rust hands back a pointer and length to its UTF-8 bytes; the glue decodes them into a new JavaScript string and the allocation is released. 3. The `str` type is supported only as a borrowed `&str` parameter; owned text in either direction is `String`. The conversion is not always lossless. JavaScript strings may contain **unpaired surrogates**, half of a UTF-16 pair. `TextEncoder` replaces each with **U+FFFD**, so the Rust string can differ from the JavaScript one. When identity matters, take a `js_sys::JsString`, which stays in JavaScript; `JsString::is_valid_utf16` tests for the problem and `JsString::iter` yields raw `u16` units. ## A call to `blur_row`, step by step 1. The page creates the kernel with `new Kernel(1)`: Rust allocates the struct in linear memory and the JavaScript object keeps its pointer. 2. The page calls `blur_row(pixels, kernel)` with a `Uint8Array` or `Uint8ClampedArray` of canvas pixels. 3. The glue copies the array's bytes into linear memory and passes a pointer, a length, a handle to the original array and the kernel's pointer. 4. Rust borrows the kernel in place and edits the copied bytes. 5. When the call ends, the bytes are copied back into the original array; nothing is returned. Only step 3 and step 5 move pixel data, which is why the cost grows with image size rather than with the work the filter does. ## Mutable slices: copied in and copied back A `&mut [u8]` parameter is passed from a JavaScript typed array. wasm-bindgen 0.2.129 copies the array's contents into a Rust-owned buffer; the guard holding that buffer copies the bytes **back into the original JavaScript array** when it is dropped at the end of the call. The page therefore sees `blur_row`'s edits, at the price of two copies per call. For a large canvas frame those copies can rival the filter itself. ## Structs: handles, not copies A struct marked `#[wasm_bindgen]` is **exported as a JavaScript class**. The value lives in linear memory; the JavaScript object holds its pointer, and methods and functions taking `&Kernel` receive that pointer without copying fields. The object is released through a generated free export (its `free()` method). A struct **without** the attribute cannot cross: - by value, rustc reports E0277 "the trait bound `Kernel: FromWasmAbi` is not satisfied"; - by reference, the same E0277 names `RefFromWasmAbi`. Arbitrary structured data can also cross as a `JsValue` built through a serialisation layer, which is a copy of a different kind. ## Choosing the cheaper crossing | Rust type in the signature | What crosses | Copies | |---|---|---| | `&str` parameter | UTF-8 bytes in linear memory | one, plus re-encoding | | `String` return | UTF-8 bytes, decoded by the glue | one, plus re-encoding | | `&mut [u8]` parameter | buffer in linear memory | in and back out | | `#[wasm_bindgen]` struct | pointer inside a JavaScript class | none | | `JsValue`, `js_sys::JsString` | handle to a JavaScript value | none | Habits that follow from the table: - keep long-lived pixel buffers on the Rust side, for example a `Vec<u8>` inside an exported struct, and copy only when the page must read the result; - `js_sys::Uint8Array::view` creates a JavaScript view of Rust memory without copying, but it is `unsafe`: any allocation that grows linear memory invalidates the view; - prefer `&str` for short labels, where the copy is cheap and Rust code stays idiomatic. Text encoding in general is the strings material; this is only about where wasm-bindgen copies.

  • How would you avoid copying a 4K canvas frame into and out of linear memory on every call?
    Keep the pixel buffer in Rust, for example a `Vec<u8>` inside a `#[wasm_bindgen]` struct, filter it in place, and give JavaScript a view only when it must draw. `js_sys::Uint8Array::view` builds that view without copying, but it is `unsafe` because any allocation that grows linear memory invalidates it, so create it right before use and never hold it across calls into Rust.
  • Why might a string differ after a round trip from JavaScript to Rust and back?
    JavaScript strings may contain unpaired UTF-16 surrogates, which are not valid Unicode. Encoding into UTF-8 for a `&str` replaces each with U+FFFD, so the Rust value, and anything returned from it, no longer equals the original. Take a `js_sys::JsString` when identity matters; it stays a handle to the JavaScript value and offers `is_valid_utf16` and a raw `u16` iterator.

Passing a string is like sending a letter through a translator: the other side receives its own copy in its own alphabet, and replying produces a second translated copy. A js_sys::JsString is a claim ticket for the original letter, which never leaves the JavaScript side.

  • A `&str` parameter lets Rust read the JavaScript string in place, without copying.
  • JavaScript strings are UTF-8, so the bytes cross unchanged.
  • Rust's edits to a `&mut [u8]` are lost, because wasm-bindgen only copies the data in.
  • Any `pub struct` can be a parameter of a `#[wasm_bindgen]` function.
  • `js_sys::Uint8Array::view` is a safe, permanent window into Rust memory.