composable_allocators/
as_global.rs1use crate::base::*;
2use const_default::ConstDefault;
3use core::alloc::{self, GlobalAlloc};
4use core::ptr::{NonNull, null_mut};
5
6#[derive(Debug, Copy, Clone)]
7pub struct AsGlobal<A: NonUnwinding + ?Sized>(pub A);
8
9impl<A: NonUnwinding + ConstDefault> ConstDefault for AsGlobal<A> {
10 const DEFAULT: Self = AsGlobal(A::DEFAULT);
11}
12
13unsafe impl<A: NonUnwinding + ?Sized> GlobalAlloc for AsGlobal<A> {
14 unsafe fn alloc(&self, layout: alloc::Layout) -> *mut u8 {
15 self.0.allocate(layout).map_or_else(|_| null_mut(), |x| x.as_mut_ptr())
16 }
17
18 unsafe fn alloc_zeroed(&self, layout: alloc::Layout) -> *mut u8 {
19 self.0.allocate_zeroed(layout).map_or_else(|_| null_mut(), |x| x.as_mut_ptr())
20 }
21
22 unsafe fn dealloc(&self, ptr: *mut u8, layout: alloc::Layout) {
23 self.0.deallocate(NonNull::new_unchecked(ptr), layout)
24 }
25
26 unsafe fn realloc(
27 &self,
28 ptr: *mut u8,
29 layout: alloc::Layout,
30 new_size: usize
31 ) -> *mut u8 {
32 let ptr = NonNull::new_unchecked(ptr);
33 let new_layout = alloc::Layout::from_size_align_unchecked(new_size, layout.align());
34 if new_size > layout.size() {
35 self.0.grow(ptr, layout, new_layout)
36 } else {
37 self.0.shrink(ptr, layout, new_layout)
38 }.map_or_else(|_| null_mut(), |x| x.as_mut_ptr())
39 }
40}