1 pub(crate) use self::inner::{do_alloc, Allocator, Global}; 2 3 #[cfg(feature = "nightly")] 4 mod inner { 5 use crate::alloc::alloc::Layout; 6 pub use crate::alloc::alloc::{Allocator, Global}; 7 use core::ptr::NonNull; 8 9 #[allow(clippy::map_err_ignore)] do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<u8>, ()>10 pub fn do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<u8>, ()> { 11 alloc 12 .allocate(layout) 13 .map(|ptr| ptr.as_non_null_ptr()) 14 .map_err(|_| ()) 15 } 16 17 #[cfg(feature = "bumpalo")] 18 unsafe impl Allocator for crate::BumpWrapper<'_> { 19 #[inline] allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, core::alloc::AllocError>20 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, core::alloc::AllocError> { 21 match self.0.try_alloc_layout(layout) { 22 Ok(ptr) => Ok(NonNull::slice_from_raw_parts(ptr, layout.size())), 23 Err(_) => Err(core::alloc::AllocError), 24 } 25 } 26 #[inline] deallocate(&self, _ptr: NonNull<u8>, _layout: Layout)27 unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {} 28 } 29 } 30 31 #[cfg(not(feature = "nightly"))] 32 mod inner { 33 use crate::alloc::alloc::{alloc, dealloc, Layout}; 34 use core::ptr::NonNull; 35 36 pub unsafe trait Allocator { allocate(&self, layout: Layout) -> Result<NonNull<u8>, ()>37 fn allocate(&self, layout: Layout) -> Result<NonNull<u8>, ()>; deallocate(&self, ptr: NonNull<u8>, layout: Layout)38 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout); 39 } 40 41 #[derive(Copy, Clone)] 42 pub struct Global; 43 unsafe impl Allocator for Global { 44 #[inline] allocate(&self, layout: Layout) -> Result<NonNull<u8>, ()>45 fn allocate(&self, layout: Layout) -> Result<NonNull<u8>, ()> { 46 unsafe { NonNull::new(alloc(layout)).ok_or(()) } 47 } 48 #[inline] deallocate(&self, ptr: NonNull<u8>, layout: Layout)49 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { 50 dealloc(ptr.as_ptr(), layout) 51 } 52 } 53 impl Default for Global { 54 #[inline] default() -> Self55 fn default() -> Self { 56 Global 57 } 58 } 59 do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<u8>, ()>60 pub fn do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<u8>, ()> { 61 alloc.allocate(layout) 62 } 63 64 #[cfg(feature = "bumpalo")] 65 unsafe impl Allocator for crate::BumpWrapper<'_> { 66 #[allow(clippy::map_err_ignore)] allocate(&self, layout: Layout) -> Result<NonNull<u8>, ()>67 fn allocate(&self, layout: Layout) -> Result<NonNull<u8>, ()> { 68 self.0.try_alloc_layout(layout).map_err(|_| ()) 69 } deallocate(&self, _ptr: NonNull<u8>, _layout: Layout)70 unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {} 71 } 72 } 73