Expand description
std::boxed::Box-like API on top of a lock-free memory pool
§Example usage
use core::ptr::addr_of_mut;
use heapless::{box_pool, pool::boxed::{Box, BoxBlock}};
box_pool!(MyBoxPool: u128);
// cannot allocate without first giving memory blocks to the pool
assert!(MyBoxPool.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 BLOCK: BoxBlock <u128>= BoxBlock::new();
addr_of_mut!(BLOCK).as_mut().unwrap()
};
// give block of memory to the pool
MyBoxPool.manage(block);
// it's now possible to allocate
let mut boxed = MyBoxPool.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 = MyBoxPool.alloc(3);
assert!(res.is_err());
// give another memory block to the pool
MyBoxPool.manage(unsafe {
static mut BLOCK: BoxBlock<u128> = BoxBlock::new();
addr_of_mut!(BLOCK).as_mut().unwrap()
});
// 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 = MyBoxPool.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 = MyBoxPool.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 core::ptr::addr_of_mut;
use heapless::{box_pool, pool::boxed::BoxBlock};
box_pool!(MyBoxPool: u128);
const POOL_CAPACITY: usize = 8;
let blocks: &'static mut [BoxBlock<u128>] = {
#[allow(clippy::declare_interior_mutable_const)]
const BLOCK: BoxBlock<u128> = BoxBlock::new(); // <=
static mut BLOCKS: [BoxBlock<u128>; POOL_CAPACITY] = [BLOCK; POOL_CAPACITY];
unsafe { addr_of_mut!(BLOCKS).as_mut().unwrap() }
};
for block in blocks {
MyBoxPool.manage(block);
}Structs§
- Box
- Like
std::boxed::Boxbut managed by memory poolPrather than#[global_allocator] - BoxBlock
- A chunk of memory that a
BoxPoolsingleton can manage
Traits§
- BoxPool
- A singleton that manages
pool::boxed::Box-es