Skip to main content

wavegraph_dsp/
mailbox.rs

1//! Move one owned value at a time between a synchronous renderer and its host.
2//!
3//! Split the mailbox once and give each endpoint its own task or core. Neither
4//! operation allocates, waits for its peer, or calls a task waker. A failed
5//! send returns the original value. Use two mailboxes to lend a render buffer
6//! to a worker and get it back after the worker has finished writing.
7//!
8//! Both cores must access the same coherent memory. A CPU-only mailbox does
9//! not perform cache maintenance for a DMA device.
10
11use core::{
12    fmt,
13    sync::atomic::{AtomicUsize, Ordering, fence},
14};
15use heapless::spsc::{Consumer, Producer, Queue};
16
17/// Storage for a one-item, single-producer, single-consumer channel.
18#[derive(Debug)]
19pub struct Mailbox<T> {
20    queue: Queue<T, 2>, // heapless reserves one of the two entries.
21    state: Publication,
22}
23
24impl<T: Send> Mailbox<T> {
25    /// Create an empty mailbox.
26    #[must_use]
27    pub const fn new() -> Self {
28        Self {
29            queue: Queue::new(),
30            state: Publication(AtomicUsize::new(0)),
31        }
32    }
33
34    /// Borrow the unique sender and receiver. A value still in the mailbox
35    /// when the endpoints are dropped is available after splitting it again.
36    pub fn split(&mut self) -> (Sender<'_, T>, Receiver<'_, T>) {
37        let (producer, consumer) = self.queue.split();
38        (
39            Sender {
40                producer,
41                state: &self.state,
42            },
43            Receiver {
44                consumer,
45                state: &self.state,
46            },
47        )
48    }
49}
50
51impl<T: Send> Default for Mailbox<T> {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57// The queue moves T safely. This word publishes the completed move across
58// a full hardware barrier in either direction. Some weakly ordered embedded
59// targets lower acquire/release word operations to plain loads and stores.
60// A fence outside enqueue alone cannot order its internal payload/index stores.
61#[derive(Debug)]
62struct Publication(AtomicUsize);
63
64impl Publication {
65    #[inline]
66    fn ready(&self, full: bool) -> bool {
67        if self.0.load(Ordering::Acquire) != usize::from(full) {
68            return false;
69        }
70        fence(Ordering::SeqCst);
71        true
72    }
73
74    #[inline]
75    fn set(&self, full: bool) {
76        fence(Ordering::SeqCst);
77        self.0.store(usize::from(full), Ordering::Release);
78        fence(Ordering::SeqCst);
79    }
80}
81
82/// The sole sender of a mailbox.
83pub struct Sender<'a, T> {
84    producer: Producer<'a, T>,
85    state: &'a Publication,
86}
87
88impl<T> fmt::Debug for Sender<'_, T> {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.debug_struct("Sender").finish_non_exhaustive()
91    }
92}
93
94impl<T> Sender<'_, T> {
95    /// Transfer ownership immediately if the slot is free.
96    ///
97    /// # Errors
98    /// Returns the original value if the receiver has not taken its predecessor.
99    #[inline]
100    pub fn try_send(&mut self, value: T) -> Result<(), T> {
101        if !self.state.ready(false) {
102            return Err(value);
103        }
104        self.producer.enqueue(value)?;
105        self.state.set(true);
106        Ok(())
107    }
108}
109
110/// The sole receiver of a mailbox.
111pub struct Receiver<'a, T> {
112    consumer: Consumer<'a, T>,
113    state: &'a Publication,
114}
115
116impl<T> fmt::Debug for Receiver<'_, T> {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("Receiver").finish_non_exhaustive()
119    }
120}
121
122impl<T> Receiver<'_, T> {
123    /// Take the published value, or return immediately if the slot is empty.
124    #[inline]
125    pub fn try_recv(&mut self) -> Option<T> {
126        if !self.state.ready(true) {
127            return None;
128        }
129        let value = self.consumer.dequeue()?;
130        self.state.set(false);
131        Some(value)
132    }
133}