Skip to main content

hazard3_sync/
zerocopy_channel.rs

1//! A zero-copy queue for sending values between asynchronous tasks.
2//!
3//! It can be used concurrently by a producer (sender) and a
4//! consumer (receiver), i.e. it is an  "SPSC channel".
5//!
6//! This queue takes a Mutex type so that various
7//! targets can be attained. For example, a ThreadModeMutex can be used
8//! for single-core Cortex-M targets where messages are only passed
9//! between tasks running in thread mode. Similarly, a CriticalSectionMutex
10//! can also be used for single-core targets where messages are to be
11//! passed from exception mode e.g. out of an interrupt handler.
12//!
13//! This module provides a bounded channel that has a limit on the number of
14//! messages that it can store. If this limit is reached, trying to send
15//! another message either waits or returns an error depending on the function.
16
17use core::cell::RefCell;
18use core::future::poll_fn;
19use core::marker::PhantomData;
20use core::ops::{Deref, DerefMut};
21use core::task::{Context, Poll};
22
23use crate::blocking_mutex::Mutex;
24use crate::blocking_mutex::raw::RawMutex;
25use crate::waitqueue::WakerRegistration;
26
27/// A bounded zero-copy channel for communicating between asynchronous tasks
28/// with backpressure.
29///
30/// The channel will buffer up to the provided number of messages.  Once the
31/// buffer is full, attempts to `send` new messages will wait until a message is
32/// received from the channel.
33///
34/// All data sent will become available in the same order as it was sent.
35///
36/// The channel requires a buffer of recyclable elements.  Writing to the channel is done through
37/// an `&mut T`.
38#[derive(Debug)]
39pub struct Channel<'a, M: RawMutex, T> {
40    buf: BufferPtr<T>,
41    phantom: PhantomData<&'a mut T>,
42    state: Mutex<M, RefCell<State>>,
43}
44
45impl<'a, M: RawMutex, T> Channel<'a, M, T> {
46    /// Initialize a new [`Channel`].
47    ///
48    /// The provided buffer will be used and reused by the channel's logic, and thus dictates the
49    /// channel's capacity.
50    pub const fn new(buf: &'a mut [T]) -> Self {
51        let len = buf.len();
52        core::assert!(len != 0);
53
54        Self {
55            buf: BufferPtr(buf.as_mut_ptr()),
56            phantom: PhantomData,
57            state: Mutex::new(RefCell::new(State {
58                capacity: len,
59                front: 0,
60                back: 0,
61                full: false,
62                send_waker: WakerRegistration::new(),
63                receive_waker: WakerRegistration::new(),
64            })),
65        }
66    }
67
68    /// Creates a [`Sender`] and [`Receiver`] from an existing channel.
69    ///
70    /// Further Senders and Receivers can be created through [`Sender::borrow`] and
71    /// [`Receiver::borrow`] respectively.
72    pub fn split(&mut self) -> (Sender<'_, M, T>, Receiver<'_, M, T>) {
73        (Sender { channel: self }, Receiver { channel: self })
74    }
75
76    /// Clears all elements in the channel.
77    pub fn clear(&mut self) {
78        self.state.lock(|s| {
79            s.borrow_mut().clear();
80        });
81    }
82
83    /// Returns the number of elements currently in the channel.
84    pub fn len(&self) -> usize {
85        self.state.lock(|s| s.borrow().len())
86    }
87
88    /// Returns whether the channel is empty.
89    pub fn is_empty(&self) -> bool {
90        self.state.lock(|s| s.borrow().is_empty())
91    }
92
93    /// Returns whether the channel is full.
94    pub fn is_full(&self) -> bool {
95        self.state.lock(|s| s.borrow().is_full())
96    }
97}
98
99#[repr(transparent)]
100#[derive(Debug)]
101struct BufferPtr<T>(*mut T);
102
103impl<T> BufferPtr<T> {
104    unsafe fn add(&self, count: usize) -> *mut T {
105        self.0.add(count)
106    }
107}
108
109unsafe impl<T> Send for BufferPtr<T> {}
110unsafe impl<T> Sync for BufferPtr<T> {}
111
112/// Send-only access to a [`Channel`].
113#[derive(Debug)]
114pub struct Sender<'a, M: RawMutex, T> {
115    channel: &'a Channel<'a, M, T>,
116}
117
118impl<'a, M: RawMutex, T> Sender<'a, M, T> {
119    /// Creates one further [`Sender`] over the same channel.
120    pub fn borrow(&mut self) -> Sender<'_, M, T> {
121        Sender { channel: self.channel }
122    }
123
124    /// Attempts to send a value over the channel.
125    pub fn try_send(&mut self) -> Option<SendSlot<'_, M, T>> {
126        self.channel.state.lock(|s| {
127            let s = &mut *s.borrow_mut();
128            match s.push_index() {
129                Some(i) => Some(SendSlot {
130                    value: unsafe { &mut *self.channel.buf.add(i) },
131                    state: &self.channel.state,
132                }),
133                None => None,
134            }
135        })
136    }
137
138    /// Attempts to send a value over the channel.
139    pub fn poll_send(&mut self, cx: &mut Context) -> Poll<SendSlot<'_, M, T>> {
140        self.channel.state.lock(move |s| {
141            let s = &mut *s.borrow_mut();
142            match s.push_index() {
143                Some(i) => Poll::Ready(SendSlot {
144                    value: unsafe { &mut *self.channel.buf.add(i) },
145                    state: &self.channel.state,
146                }),
147                None => {
148                    s.receive_waker.register(cx.waker());
149                    Poll::Pending
150                }
151            }
152        })
153    }
154
155    /// Asynchronously send a value over the channel.
156    pub fn send(&mut self) -> impl Future<Output = SendSlot<'_, M, T>> {
157        poll_fn(|cx| {
158            self.channel.state.lock(|s| {
159                let s = &mut *s.borrow_mut();
160                match s.push_index() {
161                    Some(i) => Poll::Ready(SendSlot {
162                        value: unsafe { &mut *self.channel.buf.add(i) },
163                        state: &self.channel.state,
164                    }),
165                    None => {
166                        s.receive_waker.register(cx.waker());
167                        Poll::Pending
168                    }
169                }
170            })
171        })
172    }
173
174    /// Returns the number of elements currently in the channel.
175    pub fn len(&self) -> usize {
176        self.channel.state.lock(|s| s.borrow().len())
177    }
178
179    /// Returns whether the channel is empty.
180    pub fn is_empty(&self) -> bool {
181        self.channel.state.lock(|s| s.borrow().is_empty())
182    }
183
184    /// Returns whether the channel is full.
185    pub fn is_full(&self) -> bool {
186        self.channel.state.lock(|s| s.borrow().is_full())
187    }
188}
189
190/// A slot for sending in the channel
191///
192/// The slot is only marked as sent when [`SendSlot::send_done`] is called.
193pub struct SendSlot<'a, M: RawMutex, T> {
194    state: &'a Mutex<M, RefCell<State>>,
195    value: &'a mut T,
196}
197
198impl<M: RawMutex, T> Deref for SendSlot<'_, M, T> {
199    type Target = T;
200
201    fn deref(&self) -> &Self::Target {
202        self.value
203    }
204}
205
206impl<M: RawMutex, T> DerefMut for SendSlot<'_, M, T> {
207    fn deref_mut(&mut self) -> &mut Self::Target {
208        self.value
209    }
210}
211
212impl<M: RawMutex, T> SendSlot<'_, M, T> {
213    /// Notify the channel that the sending of the value has been finalized.
214    pub fn send_done(self) {
215        self.state.lock(|s| s.borrow_mut().push_done());
216    }
217}
218
219/// Receive-only access to a [`Channel`].
220#[derive(Debug)]
221pub struct Receiver<'a, M: RawMutex, T> {
222    channel: &'a Channel<'a, M, T>,
223}
224
225impl<'a, M: RawMutex, T> Receiver<'a, M, T> {
226    /// Creates one further [`Receiver`] over the same channel.
227    pub fn borrow(&mut self) -> Receiver<'_, M, T> {
228        Receiver { channel: self.channel }
229    }
230
231    /// Attempts to receive a value over the channel.
232    pub fn try_receive(&mut self) -> Option<ReceiveSlot<'_, M, T>> {
233        self.channel.state.lock(|s| {
234            let s = &mut *s.borrow_mut();
235            match s.pop_index() {
236                Some(i) => Some(ReceiveSlot {
237                    value: unsafe { &mut *self.channel.buf.add(i) },
238                    state: &self.channel.state,
239                }),
240                None => None,
241            }
242        })
243    }
244
245    /// Attempts to asynchronously receive a value over the channel.
246    pub fn poll_receive(&mut self, cx: &mut Context) -> Poll<ReceiveSlot<'_, M, T>> {
247        self.channel.state.lock(|s| {
248            let s = &mut *s.borrow_mut();
249            match s.pop_index() {
250                Some(i) => Poll::Ready(ReceiveSlot {
251                    value: unsafe { &mut *self.channel.buf.add(i) },
252                    state: &self.channel.state,
253                }),
254                None => {
255                    s.send_waker.register(cx.waker());
256                    Poll::Pending
257                }
258            }
259        })
260    }
261
262    /// Asynchronously receive a value over the channel.
263    pub fn receive(&mut self) -> impl Future<Output = ReceiveSlot<'_, M, T>> {
264        poll_fn(|cx| {
265            self.channel.state.lock(|s| {
266                let s = &mut *s.borrow_mut();
267                match s.pop_index() {
268                    Some(i) => Poll::Ready(ReceiveSlot {
269                        value: unsafe { &mut *self.channel.buf.add(i) },
270                        state: &self.channel.state,
271                    }),
272                    None => {
273                        s.send_waker.register(cx.waker());
274                        Poll::Pending
275                    }
276                }
277            })
278        })
279    }
280
281    /// Clears all elements in the channel.
282    pub fn clear(&mut self) {
283        self.channel.state.lock(|s| {
284            s.borrow_mut().clear();
285        });
286    }
287
288    /// Returns the number of elements currently in the channel.
289    pub fn len(&self) -> usize {
290        self.channel.state.lock(|s| s.borrow().len())
291    }
292
293    /// Returns whether the channel is empty.
294    pub fn is_empty(&self) -> bool {
295        self.channel.state.lock(|s| s.borrow().is_empty())
296    }
297
298    /// Returns whether the channel is full.
299    pub fn is_full(&self) -> bool {
300        self.channel.state.lock(|s| s.borrow().is_full())
301    }
302}
303
304/// A slot for receiving in the channel.
305///
306/// The slot is only marked as received when [`ReceiveSlot::receive_done`] is called.
307pub struct ReceiveSlot<'a, M: RawMutex, T> {
308    state: &'a Mutex<M, RefCell<State>>,
309    value: &'a mut T,
310}
311
312impl<M: RawMutex, T> Deref for ReceiveSlot<'_, M, T> {
313    type Target = T;
314
315    fn deref(&self) -> &Self::Target {
316        self.value
317    }
318}
319
320impl<M: RawMutex, T> DerefMut for ReceiveSlot<'_, M, T> {
321    fn deref_mut(&mut self) -> &mut Self::Target {
322        self.value
323    }
324}
325
326impl<M: RawMutex, T> ReceiveSlot<'_, M, T> {
327    /// Notify the channel that the receiving of the value has been finalized.
328    pub fn receive_done(self) {
329        self.state.lock(|s| s.borrow_mut().pop_done());
330    }
331}
332
333#[derive(Debug)]
334struct State {
335    /// Maximum number of elements the channel can hold.
336    capacity: usize,
337
338    /// Front index. Always 0..=(N-1)
339    front: usize,
340    /// Back index. Always 0..=(N-1).
341    back: usize,
342
343    /// Used to distinguish "empty" and "full" cases when `front == back`.
344    /// May only be `true` if `front == back`, always `false` otherwise.
345    full: bool,
346
347    send_waker: WakerRegistration,
348    receive_waker: WakerRegistration,
349}
350
351impl State {
352    fn increment(&self, i: usize) -> usize {
353        if i + 1 == self.capacity { 0 } else { i + 1 }
354    }
355
356    fn clear(&mut self) {
357        if self.full {
358            self.receive_waker.wake();
359        }
360        self.front = 0;
361        self.back = 0;
362        self.full = false;
363    }
364
365    fn len(&self) -> usize {
366        if !self.full {
367            if self.back >= self.front {
368                self.back - self.front
369            } else {
370                self.capacity + self.back - self.front
371            }
372        } else {
373            self.capacity
374        }
375    }
376
377    fn is_full(&self) -> bool {
378        self.full
379    }
380
381    fn is_empty(&self) -> bool {
382        self.front == self.back && !self.full
383    }
384
385    fn push_index(&mut self) -> Option<usize> {
386        match self.is_full() {
387            true => None,
388            false => Some(self.back),
389        }
390    }
391
392    fn push_done(&mut self) {
393        self.back = self.increment(self.back);
394        if self.back == self.front {
395            self.full = true;
396        }
397        self.send_waker.wake();
398    }
399
400    fn pop_index(&mut self) -> Option<usize> {
401        match self.is_empty() {
402            true => None,
403            false => Some(self.front),
404        }
405    }
406
407    fn pop_done(&mut self) {
408        self.front = self.increment(self.front);
409        self.full = false;
410        self.receive_waker.wake();
411    }
412}