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