1use core::{
12 fmt,
13 sync::atomic::{AtomicUsize, Ordering, fence},
14};
15use heapless::spsc::{Consumer, Producer, Queue};
16
17#[derive(Debug)]
19pub struct Mailbox<T> {
20 queue: Queue<T, 2>, state: Publication,
22}
23
24impl<T: Send> Mailbox<T> {
25 #[must_use]
27 pub const fn new() -> Self {
28 Self {
29 queue: Queue::new(),
30 state: Publication(AtomicUsize::new(0)),
31 }
32 }
33
34 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#[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
82pub 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 #[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
110pub 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 #[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}