allocator_api/
lib.rs

1#![no_std]
2
3#[cfg(feature = "std")]
4macro_rules! global_alloc {
5    ([$($t:tt)*] Alloc $($rest:tt)*) => {
6        global_alloc! { [ $($t)* Alloc = Global ] $($rest)* }
7    };
8    ([$($t:tt)*] $first:tt $($rest:tt)*) => {
9        global_alloc! { [ $($t)* $first ] $($rest)* }
10    };
11    ([$($t:tt)*]) => {
12        $($t)*
13    };
14    ($($t:tt)*) => {
15        global_alloc! { [] $($t)* }
16    };
17}
18#[cfg(not(feature = "std"))]
19macro_rules! global_alloc {
20    ($($t:tt)*) => { $($t)* };
21}
22
23#[cfg(feature = "std")]
24#[doc(hidden)]
25#[macro_export]
26macro_rules! test_using_global {
27    ($($t:tt)*) => { $($t)* };
28}
29
30#[cfg(not(feature = "std"))]
31#[doc(hidden)]
32#[macro_export]
33macro_rules! test_using_global {
34    ($($t:tt)*) => { fn main() {} };
35}
36
37#[path = "libcore/alloc.rs"]
38mod core_alloc;
39#[path = "libstd/alloc.rs"]
40mod std_alloc;
41#[path = "liballoc/boxed.rs"]
42pub mod boxed;
43#[path = "liballoc/collections/mod.rs"]
44pub mod collections;
45#[path = "liballoc/raw_vec.rs"]
46pub mod raw_vec;
47
48#[cfg(feature = "std")]
49extern crate std;
50
51#[cfg(feature = "std")]
52mod global {
53    use core::ptr::NonNull;
54    use crate::core_alloc::{AllocErr, Layout};
55
56    use std::alloc::{alloc, alloc_zeroed, dealloc, realloc};
57
58    #[derive(Copy, Clone, Default, Debug)]
59    pub struct Global;
60
61    unsafe impl crate::core_alloc::Alloc for Global {
62        unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
63            NonNull::new(alloc(layout.into())).ok_or(AllocErr)
64        }
65
66        unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
67            dealloc(ptr.as_ptr(), layout.into())
68        }
69
70        unsafe fn realloc(&mut self,
71                          ptr: NonNull<u8>,
72                          layout: Layout,
73                          new_size: usize) -> Result<NonNull<u8>, AllocErr> {
74            NonNull::new(realloc(ptr.as_ptr(), layout.into(), new_size)).ok_or(AllocErr)
75        }
76
77        unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
78            NonNull::new(alloc_zeroed(layout.into())).ok_or(AllocErr)
79        }
80    }
81}
82
83pub mod alloc {
84    pub use crate::core_alloc::*;
85    pub use crate::std_alloc::rust_oom as handle_alloc_error;
86    pub use crate::std_alloc::{set_alloc_error_hook, take_alloc_error_hook};
87
88    #[cfg(feature = "std")]
89    pub use crate::global::Global;
90}
91
92pub use crate::alloc::*;
93pub use crate::boxed::*;
94pub use crate::raw_vec::*;