#![expect(unsafe_code, reason = "implements the global allocator")]
use std::{
alloc::{GlobalAlloc, Layout, System},
sync::atomic::{AtomicUsize, Ordering},
};
const PAGE: usize = 64 * 1024;
const AHEAD_ALIGN: usize = 16;
#[derive(Default)]
pub struct Heap {
pages: AtomicUsize,
}
impl Heap {
pub const fn new() -> Self {
Self {
pages: AtomicUsize::new(0),
}
}
fn grow_ahead(&self) {
let pages = core::arch::wasm32::memory_size(0);
if pages == self.pages.load(Ordering::Relaxed) {
return;
}
if let Ok(ahead) = Layout::from_size_align(pages * PAGE / 2, AHEAD_ALIGN) {
let block = unsafe { System.alloc(ahead) };
if !block.is_null() {
unsafe { System.dealloc(block, ahead) };
}
}
self.pages
.store(core::arch::wasm32::memory_size(0), Ordering::Relaxed);
}
}
unsafe impl GlobalAlloc for Heap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let block = unsafe { System.alloc(layout) };
self.grow_ahead();
block
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let block = unsafe { System.alloc_zeroed(layout) };
self.grow_ahead();
block
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let block = unsafe { System.realloc(ptr, layout, new_size) };
self.grow_ahead();
block
}
}