multiversx_sc_wasm_adapter/wasm_alloc/
static_allocator.rsuse core::{
alloc::{GlobalAlloc, Layout},
cell::UnsafeCell,
};
pub const SIZE_64K: usize = 64 * 1024;
pub type StaticAllocator64K = StaticAllocator<SIZE_64K>;
#[repr(C, align(32))]
pub struct StaticAllocator<const SIZE: usize> {
arena: UnsafeCell<[u8; SIZE]>,
head: UnsafeCell<usize>,
}
impl<const SIZE: usize> StaticAllocator<SIZE> {
#[allow(clippy::new_without_default)]
pub const fn new() -> Self {
StaticAllocator {
arena: UnsafeCell::new([0; SIZE]),
head: UnsafeCell::new(0),
}
}
}
unsafe impl<const SIZE: usize> Sync for StaticAllocator<SIZE> {}
unsafe impl<const SIZE: usize> GlobalAlloc for StaticAllocator<SIZE> {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let size = layout.size();
let align = layout.align();
let idx = (*self.head.get()).next_multiple_of(align);
*self.head.get() = idx + size;
let arena: &mut [u8; SIZE] = &mut (*self.arena.get());
match arena.get_mut(idx) {
Some(item) => item as *mut u8,
_ => super::mem_alloc_error(),
}
}
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
}