Expand description
std::boxed::Box-like API on top of a lock-free memory pool
§Example usage
use heapless::{box_pool, pool::boxed::{Box, BoxBlock}};
box_pool!(P: u128);
// cannot allocate without first giving memory blocks to the pool
assert!(P.alloc(42).is_err());
// (some `no_std` runtimes have safe APIs to create `&'static mut` references)
let block: &'static mut BoxBlock<u128> = unsafe {
    static mut B: BoxBlock <u128>= BoxBlock::new();
    &mut B
};
// give block of memory to the pool
P.manage(block);
// it's now possible to allocate
let mut boxed = P.alloc(1).unwrap();
// mutation is possible
*boxed += 1;
assert_eq!(2, *boxed);
// number of boxes is limited to the number of blocks managed by the pool
let res = P.alloc(3);
assert!(res.is_err());
// give another memory block to the pool
P.manage(unsafe {
    static mut B: BoxBlock<u128> = BoxBlock::new();
    &mut B
});
// cloning also consumes a memory block from the pool
let mut separate_box = boxed.clone();
*separate_box += 1;
assert_eq!(3, *separate_box);
// after the clone it's not possible to allocate again
let res = P.alloc(4);
assert!(res.is_err());
// `boxed`'s destructor returns the memory block to the pool
drop(boxed);
// it's possible to allocate again
let res = P.alloc(5);
assert!(res.is_ok());§Array block initialization
You can create a static variable that contains an array of memory blocks and give all the blocks
to the BoxPool. This requires an intermediate const value as shown below:
use heapless::{box_pool, pool::boxed::BoxBlock};
box_pool!(P: u128);
const POOL_CAPACITY: usize = 8;
let blocks: &'static mut [BoxBlock<u128>] = {
    const BLOCK: BoxBlock<u128> = BoxBlock::new(); // <=
    static mut BLOCKS: [BoxBlock<u128>; POOL_CAPACITY] = [BLOCK; POOL_CAPACITY];
    unsafe { &mut BLOCKS }
};
for block in blocks {
    P.manage(block);
}Structs§
- Like
std::boxed::Boxbut managed by memory poolPrather than#[global_allocator] - A chunk of memory that a
BoxPoolsingleton can manage 
Traits§
- A singleton that manages
pool::boxed::Box-es