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::ptr::NonNull;
12 #[cfg(test)]
13 pub(crate) use stdalloc::alloc::AllocError;
14 use stdalloc::alloc::Layout;
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::ptr::NonNull;
37 use stdalloc::alloc::Layout;
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::ptr::NonNull;
58 use stdalloc::alloc::{Layout, alloc, dealloc};
59
60 #[expect(clippy::missing_safety_doc)] pub unsafe trait Allocator {
62 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, ()>;
63 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
64 }
65
66 #[derive(Copy, Clone)]
67 pub struct Global;
68
69 unsafe impl Allocator for Global {
70 #[inline]
71 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, ()> {
72 match unsafe { NonNull::new(alloc(layout)) } {
73 Some(data) => {
74 Ok(unsafe {
76 NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(
77 data.as_ptr(),
78 layout.size(),
79 ))
80 })
81 }
82 None => Err(()),
83 }
84 }
85 #[inline]
86 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
87 unsafe {
88 dealloc(ptr.as_ptr(), layout);
89 }
90 }
91 }
92
93 impl Default for Global {
94 #[inline]
95 fn default() -> Self {
96 Global
97 }
98 }
99
100 pub(crate) fn do_alloc<A: Allocator>(alloc: &A, layout: Layout) -> Result<NonNull<[u8]>, ()> {
101 alloc.allocate(layout)
102 }
103}