Module object

Module object 

Source
Expand description

Object pool API

§Example usage

use core::ptr::addr_of_mut;
use heapless::{object_pool, pool::object::{Object, ObjectBlock}};

object_pool!(MyObjectPool: [u8; 128]);

// cannot request objects without first giving object blocks to the pool
assert!(MyObjectPool.request().is_none());

// (some `no_std` runtimes have safe APIs to create `&'static mut` references)
let block: &'static mut ObjectBlock<[u8; 128]> = unsafe {
    // unlike the memory pool APIs, an initial value must be specified here
    static mut BLOCK: ObjectBlock<[u8; 128]>= ObjectBlock::new([0; 128]);
    addr_of_mut!(BLOCK).as_mut().unwrap()
};

// give object block to the pool
MyObjectPool.manage(block);

// it's now possible to request objects
// unlike the memory pool APIs, no initial value is required here
let mut object = MyObjectPool.request().unwrap();

// mutation is possible
object.iter_mut().for_each(|byte| *byte = byte.wrapping_add(1));

// the number of live objects is limited to the number of blocks managed by the pool
let res = MyObjectPool.request();
assert!(res.is_none());

// `object`'s destructor returns the object to the pool
drop(object);

// it's possible to request an `Object` again
let res = MyObjectPool.request();

assert!(res.is_some());

§Array block initialization

You can create a static variable that contains an array of memory blocks and give all the blocks to the ObjectPool. This requires an intermediate const value as shown below:

use core::ptr::addr_of_mut;
use heapless::{object_pool, pool::object::ObjectBlock};

object_pool!(MyObjectPool: [u8; 128]);

const POOL_CAPACITY: usize = 8;

let blocks: &'static mut [ObjectBlock<[u8; 128]>] = {
    const BLOCK: ObjectBlock<[u8; 128]> = ObjectBlock::new([0; 128]); // <=
    static mut BLOCKS: [ObjectBlock<[u8; 128]>; POOL_CAPACITY] = [BLOCK; POOL_CAPACITY];
    unsafe { addr_of_mut!(BLOCKS).as_mut().unwrap() }
};

for block in blocks {
    MyObjectPool.manage(block);
}

Structs§

Object
An object managed by object pool P
ObjectBlock
An object “block” of data type T that has not yet been associated to an ObjectPool

Traits§

ObjectPool
A singleton that manages pool::object::Objects