1#[cfg(test)]
2pub(crate) use self::inner::AllocError;
3pub(crate) use self::inner::{Allocator, Global, do_alloc};
4
5#[cfg(feature = "nightly")]
10mod inner {
11 use core::alloc::Layout;
12 use core::ptr::NonNull;
13 #[cfg(test)]
14 pub(crate) use stdalloc::alloc::AllocError;
15 pub(crate) use stdalloc::alloc::{Allocator, Global};
16
17 pub(crate) fn do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<[u8]>, ()> {
18 match alloc.allocate(layout) {
19 Ok(ptr) => Ok(ptr),
20 Err(_) => Err(()),
21 }
22 }
23}
24
25#[cfg(all(not(feature = "nightly"), feature = "allocator-api2"))]
32mod inner {
33 #[cfg(test)]
34 pub(crate) use allocator_api2::alloc::AllocError;
35 pub(crate) use allocator_api2::alloc::{Allocator, Global};
36 use core::alloc::Layout;
37 use core::ptr::NonNull;
38
39 pub(crate) fn do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<[u8]>, ()> {
40 match alloc.allocate(layout) {
41 Ok(ptr) => Ok(ptr),
42 Err(_) => Err(()),
43 }
44 }
45}
46
47#[cfg(not(any(feature = "nightly", feature = "allocator-api2")))]
56mod inner {
57 use core::alloc::Layout;
58 use core::ptr::NonNull;
59 use stdalloc::alloc::{alloc, dealloc};
60
61 #[expect(clippy::missing_safety_doc)] pub unsafe trait Allocator {
63 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, ()>;
64 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
65 }
66
67 #[derive(Copy, Clone)]
68 pub struct Global;
69
70 unsafe impl Allocator for Global {
71 #[inline]
72 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, ()> {
73 match unsafe { NonNull::new(alloc(layout)) } {
74 Some(data) => {
75 Ok(unsafe {
77 NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(
78 data.as_ptr(),
79 layout.size(),
80 ))
81 })
82 }
83 None => Err(()),
84 }
85 }
86 #[inline]
87 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
88 unsafe {
89 dealloc(ptr.as_ptr(), layout);
90 }
91 }
92 }
93
94 impl Default for Global {
95 #[inline]
96 fn default() -> Self {
97 Global
98 }
99 }
100
101 pub(crate) fn do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<[u8]>, ()> {
102 alloc.allocate(layout)
103 }
104}