heapless::pool::singleton

Module arc

source
Expand description

Like std::sync::Arc but backed by a memory Pool rather than #[global_allocator]

Note that the same limitations that apply to “Box” pool also apply to the “Arc” pool.

§Examples

use heapless::{arc_pool, Arc};

pub struct BigStruct { // <- does NOT implement Clone
    data: [u8; 128],
    // ..
}

// declare a memory pool
arc_pool!(P: BigStruct);


#[cortex_m_rt::entry]
fn main() -> ! {
    static mut MEMORY: [u8; 1024] = [0; 1024];

    // give some static memory to the pool
    P::grow(MEMORY);

    let x: Arc<P> = P::alloc(BigStruct::new()).ok().expect("OOM");
    //         ^ NOTE: this is the Pool type, not the data type

    // cloning is cheap; it increases the refcount
    let y = x.clone();

    // same data address
    assert_eq!(&*x as *const _, &*y as *const _);

    // auto-deref
    let data: &[u8] = &x.data;

    // decrease refcount
    drop(x);

    // refcount decreased to 0; memory is returned to the pool
    drop(y);

    // ..
}

The grow_exact API is also available on the “Arc pool”. It requires using Node<ArcInner<Type>> as the array element type. Example below:

use heapless::pool::{singleton::arc::ArcInner, Node};

pub struct BigStruct { /* .. */ }

arc_pool!(P: BigStruct);

#[cortex_m_rt::entry]
fn main() -> ! {
    static mut MEMORY: MaybeUninit<[Node<ArcInner<BigStruct>>; 2]> = MaybeUninit::uninit();

    P::grow_exact(MEMORY);

    // 2 allocations are guaranteed to work
    let x = P::alloc(BigStruct::new()).ok().expect("OOM");
    let y = P::alloc(BigStruct::new()).ok().expect("OOM");

    // ..
}

Structs§

  • std::sync::Arc but backed by a memory Pool rather than #[global_allocator]
  • Unfortunate implementation detail required to use the grow_exact API

Traits§

  • Pool of Arc pointers