heapless::pool

Module object

Source
Expand description

Object pool API

§Example usage

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

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

// cannot request objects without first giving object blocks to the pool
assert!(P.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 B: ObjectBlock<[u8; 128]>= ObjectBlock::new([0; 128]);
    &mut B
};

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

// it's now possible to request objects
// unlike the memory pool APIs, no initial value is required here
let mut object = P.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 = P.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 = P.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 heapless::{object_pool, pool::object::ObjectBlock};

object_pool!(P: [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 { &mut BLOCKS }
};

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

Structs§

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

Traits§

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