use r_efi::efi;
pub struct Allocator {
system_table: *mut efi::SystemTable,
memory_type: efi::MemoryType,
}
impl Allocator {
pub unsafe fn from_system_table(
st: *mut efi::SystemTable,
memtype: efi::MemoryType,
) -> Allocator {
Allocator {
system_table: st,
memory_type: memtype,
}
}
pub unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 {
crate::raw::alloc(self.system_table, layout, self.memory_type)
}
pub unsafe fn dealloc(&self, ptr: *mut u8, layout: core::alloc::Layout) {
crate::raw::dealloc(self.system_table, ptr, layout)
}
}
#[cfg(feature = "allocator_api")]
unsafe impl core::alloc::Allocator for Allocator {
fn allocate(
&self,
layout: core::alloc::Layout,
) -> Result<core::ptr::NonNull<[u8]>, core::alloc::AllocError> {
let size = layout.size();
let ptr = if size > 0 {
unsafe {
crate::raw::alloc(self.system_table, layout, self.memory_type)
}
} else {
layout.dangling().as_ptr() as *mut _
};
if ptr.is_null() {
Err(core::alloc::AllocError)
} else {
Ok(
core::ptr::NonNull::new(
core::ptr::slice_from_raw_parts(ptr, size) as *mut _,
).unwrap(),
)
}
}
unsafe fn deallocate(
&self,
ptr: core::ptr::NonNull<u8>,
layout: core::alloc::Layout,
) {
if layout.size() != 0 {
crate::raw::dealloc(self.system_table, ptr.as_ptr(), layout)
}
}
}