You write custom allocators in Rust by implementing the GlobalAlloc trait and using the #[global_allocator] attribute on a static instance. This replaces the default system allocator for your entire binary.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicBool, Ordering};
static MY_ALLOC: MyAlloc = MyAlloc;
struct MyAlloc;
unsafe impl GlobalAlloc for MyAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
System.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout)
}
}
#[global_allocator]
static GLOBAL: MyAlloc = MyAlloc;
fn main() {
println!("Custom allocator active");
}