42 lines
1.0 KiB
Rust
42 lines
1.0 KiB
Rust
|
|
use crate::{AllocationEntry, Allocator, DropFn};
|
||
|
|
use boxcar::Vec;
|
||
|
|
use std::alloc::Layout;
|
||
|
|
|
||
|
|
#[derive(Default)]
|
||
|
|
pub struct GlobalAllocator {
|
||
|
|
allocations: Vec<AllocationEntry>,
|
||
|
|
}
|
||
|
|
|
||
|
|
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);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|