use crate::{AllocationEntry, Allocator, DropFn}; use boxcar::Vec; use std::alloc::Layout; #[derive(Default)] pub struct GlobalAllocator { allocations: Vec, } impl Allocator for GlobalAllocator { unsafe fn alloc_unsafe(&self, data: *const u8, layout: Layout, drop_fn: DropFn) -> *mut u8 { unsafe { let ptr = std::alloc::alloc(layout); std::ptr::copy_nonoverlapping(data, ptr, layout.size()); self.allocations.push(AllocationEntry { ptr, layout, drop_fn, }); ptr } } } impl Drop for GlobalAllocator { fn drop(&mut self) { unsafe { for AllocationEntry { ptr, layout, drop_fn, } in std::mem::take(&mut self.allocations) { if let Some(drop) = drop_fn { drop(ptr); } std::alloc::dealloc(ptr, layout); } } } }