Queue

Type Alias Queue 

Source
pub type Queue<T, const N: usize> = QueueInner<T, OwnedStorage<N>>;
Expand description

A statically allocated single-producer, single-consumer queue with a capacity of N - 1 elements.

To get better performance, use a value for N that is a power of 2.

You will likely want to use split to create a producer-consumer pair.

Aliased Type§

pub struct Queue<T, const N: usize> { /* private fields */ }

Implementations§

Source§

impl<T, const N: usize> Queue<T, N>

Source

pub const fn new() -> Self

Creates an empty queue.

Source§

impl<T, const N: usize> Queue<T, N>

Source

pub const fn split_const(&mut self) -> (Producer<'_, T>, Consumer<'_, T>)

Splits a queue into producer and consumer endpoints.

Unlike Queue::split, this method can be used in a const context

§Example

Create and split a queue at compile time, and pass it to the main function and an interrupt handler via a mutex at runtime.

use core::cell::RefCell;

use critical_section::Mutex;
use heapless::spsc::{Consumer, Producer, Queue};

static PC: (
    Mutex<RefCell<Option<Producer<'_, ()>>>>,
    Mutex<RefCell<Option<Consumer<'_, ()>>>>,
) = {
    static mut Q: Queue<(), 4> = Queue::new();
    // SAFETY: `Q` is only accessible in this scope.
    #[allow(static_mut_refs)]
    let (p, c) = unsafe { Q.split_const() };

    (
        Mutex::new(RefCell::new(Some(p))),
        Mutex::new(RefCell::new(Some(c))),
    )
};

fn interrupt() {
    let mut producer = {
        static mut P: Option<Producer<'_, ()>> = None;
        // SAFETY: Mutable access to `P` is allowed exclusively in this scope
        // and `interrupt` cannot be called directly or preempt itself.
        unsafe { &mut P }
    }
    .get_or_insert_with(|| {
        critical_section::with(|cs| PC.0.borrow_ref_mut(cs).take().unwrap())
    });

    producer.enqueue(()).unwrap();
}

fn main() {
    let mut consumer = critical_section::with(|cs| PC.1.borrow_ref_mut(cs).take().unwrap());

    // Interrupt occurs.

    consumer.dequeue().unwrap();
}

Trait Implementations§

Source§

impl<T, const N: usize> Clone for Queue<T, N>
where T: Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, const N: usize> Default for Queue<T, N>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more