heapless::pool

Module arc

Source
Expand description

std::sync::Arc-like API on top of a lock-free memory pool

§Example usage

use heapless::{arc_pool, pool::arc::{Arc, ArcBlock}};

arc_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 ArcBlock<u128> = unsafe {
    static mut B: ArcBlock<u128> = ArcBlock::new();
    &mut B
};

P.manage(block);

let arc = P.alloc(1).unwrap();

// number of smart pointers is limited to the number of blocks managed by the pool
let res = P.alloc(2);
assert!(res.is_err());

// but cloning does not consume an `ArcBlock`
let arc2 = arc.clone();

assert_eq!(1, *arc2);

// `arc`'s destructor returns the memory block to the pool
drop(arc2); // decrease reference counter
drop(arc); // release memory

// it's now possible to allocate a new `Arc` smart pointer
let res = P.alloc(3);

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 ArcPool. This requires an intermediate const value as shown below:

use heapless::{arc_pool, pool::arc::ArcBlock};

arc_pool!(P: u128);

const POOL_CAPACITY: usize = 8;

let blocks: &'static mut [ArcBlock<u128>] = {
    const BLOCK: ArcBlock<u128> = ArcBlock::new(); // <=
    static mut BLOCKS: [ArcBlock<u128>; POOL_CAPACITY] = [BLOCK; POOL_CAPACITY];
    unsafe { &mut BLOCKS }
};

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

Structs§

  • Like std::sync::Arc but managed by memory pool P
  • A chunk of memory that an ArcPool can manage

Traits§

  • A singleton that manages pool::arc::Arc smart pointers