embedded_alloc/
lib.rs

1#![doc = include_str!("../README.md")]
2#![no_std]
3#![cfg_attr(feature = "allocator_api", feature(allocator_api, alloc_layout_extra))]
4#![warn(missing_docs)]
5
6#[cfg(feature = "llff")]
7mod llff;
8#[cfg(feature = "tlsf")]
9mod tlsf;
10
11#[cfg(feature = "llff")]
12pub use llff::Heap as LlffHeap;
13#[cfg(feature = "tlsf")]
14pub use tlsf::Heap as TlsfHeap;
15
16/// Initialize the global heap.
17///
18/// This macro creates a static, uninitialized memory buffer of the specified size and
19/// initializes the heap instance with that buffer.
20///
21/// # Parameters
22///
23/// - `$heap:ident`: The identifier of the global heap instance to initialize.
24/// - `$size:expr`: An expression evaluating to a `usize` that specifies the size of the
25///   static memory buffer in bytes. It must be **greater than zero**.
26///
27/// # Safety
28///
29/// This macro must be called first, before any operations on the heap, and **only once**.
30/// It internally calls `Heap::init(...)` on the heap,
31/// so `Heap::init(...)` should not be called directly if this macro is used.
32///
33/// # Panics
34///
35/// This macro will panic if either of the following are true:
36///
37/// - this function is called more than ONCE.
38/// - `size == 0`.
39///
40/// # Example
41///
42/// ```rust
43/// use cortex_m_rt::entry;
44/// use embedded_alloc::LlffHeap as Heap;
45///
46/// #[global_allocator]
47/// static HEAP: Heap = Heap::empty();
48///
49/// #[entry]
50/// fn main() -> ! {
51///     // Initialize the allocator BEFORE you use it
52///     unsafe {
53///         embedded_alloc::init!(HEAP, 1024);
54///     }
55///     let mut xs = Vec::new();
56///     // ...
57/// }
58/// ```
59#[macro_export]
60macro_rules! init {
61    ($heap:ident, $size:expr) => {
62        static mut HEAP_MEM: [::core::mem::MaybeUninit<u8>; $size] =
63            [::core::mem::MaybeUninit::uninit(); $size];
64        $heap.init(&raw mut HEAP_MEM as usize, $size)
65    };
66}