pub trait MemoryController {
// Required methods
fn alloc(&mut self, len: u32) -> Result<u32>;
fn free(&mut self, ptr: u32, len: u32) -> Result<()>;
fn mut_mem(&mut self, ptr: u32, len: u32) -> &mut [u8] ⓘ;
}Expand description
Synchronous memory controller for WASM linear memory (guest side).
This trait provides the interface for managing memory allocations within a WASM module. It’s designed to be used on the guest side where all operations are synchronous.
§Implementation Notes
Implementers typically:
- Use the WASM allocator (
__alloc,__freeexports) - Track allocations for cleanup
- Validate alignment and bounds
§Example
use surrealism_types::MemoryController;
struct MyController {
memory: Vec<u8>,
}
impl MemoryController for MyController {
fn alloc(&mut self, len: u32, align: u32) -> Result<u32> {
// Allocate aligned memory...
Ok(ptr)
}
fn free(&mut self, ptr: u32, len: u32) -> Result<()> {
// Deallocate memory...
Ok(())
}
fn mut_mem(&mut self, ptr: u32, len: u32) -> &mut [u8] {
// Return mutable slice to memory region...
&mut self.memory[ptr as usize..(ptr + len) as usize]
}
}Required Methods§
Sourcefn alloc(&mut self, len: u32) -> Result<u32>
fn alloc(&mut self, len: u32) -> Result<u32>
Allocate a region of WASM linear memory.
§Parameters
len: Number of bytes to allocatealign: Alignment requirement in bytes (must be a power of 2)
§Returns
A pointer (u32) to the start of the allocated region.
§Errors
Returns an error if:
- Allocation fails (out of memory)
- Alignment is invalid (not a power of 2)
- Memory limit would be exceeded
Sourcefn free(&mut self, ptr: u32, len: u32) -> Result<()>
fn free(&mut self, ptr: u32, len: u32) -> Result<()>
Free a previously allocated region of memory.
§Parameters
ptr: Pointer to the start of the region (from a previousalloccall)len: Size of the region in bytes (must match the original allocation)
§Errors
Returns an error if:
- The pointer is invalid or wasn’t allocated
- The length doesn’t match the original allocation
- Double-free is detected
§Safety Notes
After calling free, the pointer and any references to that memory region
become invalid and must not be used.
Sourcefn mut_mem(&mut self, ptr: u32, len: u32) -> &mut [u8] ⓘ
fn mut_mem(&mut self, ptr: u32, len: u32) -> &mut [u8] ⓘ
Get mutable access to a region of WASM linear memory.
§Parameters
ptr: Pointer to the start of the regionlen: Length of the region in bytes
§Returns
A mutable slice to the memory region.
§Panics
May panic if the pointer or length are out of bounds. Implementations should validate bounds before returning the slice.