Host interfaces and memory
Quick answer
A Wasm module may import functions from a host and export functions to it. Linear memory is a contiguous byte-addressed region within the module, not a Rust reference shared directly with JavaScript.
Validate the boundary
A raw ABI often uses an offset and a length for byte data. Check both the arithmetic and bounds; a valid range alone does not establish ownership, alignment, initialized data or UTF-8. Define which side allocates and frees the buffer. A host view may become stale after memory growth; obtain a fresh view when required. These examples model the contract with ordinary slices and do not expose raw pointers.
fn region(memory: &[u8], offset: usize, len: usize) -> Option<&[u8]> { memory.get(offset..offset.checked_add(len)?)}fn main() { let m = [10, 20, 30]; println!("{:?} {:?}", region(&m, 1, 2), region(&m, usize::MAX, 2)); }Expected stdout (not executed):
Some([20, 30]) NoneInvalid ranges are rejected before indexing.
fn main() { println!("{:?}", std::str::from_utf8(b"ok")); println!("{}", std::str::from_utf8(&[0xff]).is_err());}Expected stdout (not executed):
Ok("ok")trueA byte sequence is not automatically UTF-8.
Common mistake
Do not retain a host-side view indefinitely or free guest memory using an unrelated allocator.
Try it yourself
Test a zero-length region at the end of memory and a range one byte beyond it.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Host interfaces and memory — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A host retains a view of linear memory while the guest grows memory. What should the host do before further access?
Host interfaces and memory — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn region(memory: &[u8], offset: usize, len: usize) -> Option<&[u8]> { memory.get(offset..offset.checked_add(len)?) } fn main() { let m = [10, 20, 30]; println!("{:?} {:?}", region(&m, 1, 2), region(&m, usize::MAX, 2)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Host interfaces and memory — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { println!("{:?}", std::str::from_utf8(b"ok")); println!("{}", std::str::from_utf8(&[0xff]).is_err()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.