Skip to main content

hazard3_sync/
channel.rs

1//! A queue for sending values between asynchronous tasks.
2//!
3//! It can be used concurrently by multiple producers (senders) and multiple
4//! consumers (receivers), i.e. it is an  "MPMC channel".
5//!
6//! Receivers are competing for messages. So a message that is received by
7//! one receiver is not received by any other.
8//!
9//! This queue takes a Mutex type so that various
10//! targets can be attained. For example, a ThreadModeMutex can be used
11//! for single-core Cortex-M targets where messages are only passed
12//! between tasks running in thread mode. Similarly, a CriticalSectionMutex
13//! can also be used for single-core targets where messages are to be
14//! passed from exception mode e.g. out of an interrupt handler.
15//!
16//! This module provides a bounded channel that has a limit on the number of
17//! messages that it can store. If this limit is reached, trying to send
18//! another message either waits or returns an error depending on the function.
19//!
20//! # Example: Message passing between task and interrupt handler
21//!
22//! ```rust
23//! use hazard3_sync::channel::Channel;
24//! use hazard3_sync::blocking_mutex::raw::CriticalSectionRawMutex;
25//!
26//! static SHARED_CHANNEL: Channel<CriticalSectionRawMutex, u32, 8> = Channel::new();
27//!
28//! fn my_interrupt_handler() {
29//!     // Do some work..
30//!     // ...
31//!     if let Err(e) = SHARED_CHANNEL.sender().try_send(42) {
32//!         // Channel is full..
33//!     }
34//! }
35//!
36//! async fn my_async_task() {
37//!     // ...
38//!     let receiver = SHARED_CHANNEL.receiver();
39//!     loop {
40//!         let data_from_interrupt = receiver.receive().await;
41//!         // Do something with the data.
42//!     }
43//! }
44//! ```
45
46use core::cell::RefCell;
47use core::future::Future;
48use core::pin::Pin;
49use core::task::{Context, Poll};
50
51use heapless::Deque;
52
53use crate::blocking_mutex::Mutex;
54use crate::blocking_mutex::raw::RawMutex;
55use crate::waitqueue::WakerRegistration;
56
57/// Send-only access to a [`Channel`].
58#[derive(Debug)]
59pub struct Sender<'ch, M, T, const N: usize>
60where
61    M: RawMutex,
62{
63    channel: &'ch Channel<M, T, N>,
64}
65
66impl<'ch, M, T, const N: usize> Clone for Sender<'ch, M, T, N>
67where
68    M: RawMutex,
69{
70    fn clone(&self) -> Self {
71        *self
72    }
73}
74
75impl<'ch, M, T, const N: usize> Copy for Sender<'ch, M, T, N> where M: RawMutex {}
76
77impl<'ch, M, T, const N: usize> futures_sink::Sink<T> for Sender<'ch, M, T, N>
78where
79    M: RawMutex,
80{
81    type Error = TrySendError<T>;
82
83    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
84        self.poll_ready_to_send(cx).map(|()| Ok(()))
85    }
86
87    fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
88        self.try_send(item)
89    }
90
91    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
92        Poll::Ready(Ok(()))
93    }
94
95    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
96        Poll::Ready(Ok(()))
97    }
98}
99
100impl<'ch, M, T, const N: usize> Sender<'ch, M, T, N>
101where
102    M: RawMutex,
103{
104    /// Sends a value.
105    ///
106    /// See [`Channel::send()`]
107    pub fn send(&self, message: T) -> SendFuture<'ch, M, T, N> {
108        self.channel.send(message)
109    }
110
111    /// Attempt to immediately send a message.
112    ///
113    /// See [`Channel::send()`]
114    pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
115        self.channel.try_send(message)
116    }
117
118    /// Allows a poll_fn to poll until the channel is ready to send
119    ///
120    /// See [`Channel::poll_ready_to_send()`]
121    pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
122        self.channel.poll_ready_to_send(cx)
123    }
124
125    /// Returns the maximum number of elements the channel can hold.
126    ///
127    /// See [`Channel::capacity()`]
128    pub const fn capacity(&self) -> usize {
129        self.channel.capacity()
130    }
131
132    /// Returns the free capacity of the channel.
133    ///
134    /// See [`Channel::free_capacity()`]
135    pub fn free_capacity(&self) -> usize {
136        self.channel.free_capacity()
137    }
138
139    /// Clears all elements in the channel.
140    ///
141    /// See [`Channel::clear()`]
142    pub fn clear(&self) {
143        self.channel.clear();
144    }
145
146    /// Returns the number of elements currently in the channel.
147    ///
148    /// See [`Channel::len()`]
149    pub fn len(&self) -> usize {
150        self.channel.len()
151    }
152
153    /// Returns whether the channel is empty.
154    ///
155    /// See [`Channel::is_empty()`]
156    pub fn is_empty(&self) -> bool {
157        self.channel.is_empty()
158    }
159
160    /// Returns whether the channel is full.
161    ///
162    /// See [`Channel::is_full()`]
163    pub fn is_full(&self) -> bool {
164        self.channel.is_full()
165    }
166}
167
168/// Send-only access to a [`Channel`] without knowing channel size.
169pub struct DynamicSender<'ch, T> {
170    pub(crate) channel: &'ch dyn DynamicChannel<T>,
171}
172
173impl<'ch, T> Clone for DynamicSender<'ch, T> {
174    fn clone(&self) -> Self {
175        *self
176    }
177}
178
179impl<'ch, T> Copy for DynamicSender<'ch, T> {}
180
181impl<'ch, M, T, const N: usize> From<Sender<'ch, M, T, N>> for DynamicSender<'ch, T>
182where
183    M: RawMutex,
184{
185    fn from(s: Sender<'ch, M, T, N>) -> Self {
186        Self { channel: s.channel }
187    }
188}
189
190impl<'ch, T> DynamicSender<'ch, T> {
191    /// Sends a value.
192    ///
193    /// See [`Channel::send()`]
194    pub fn send(&self, message: T) -> DynamicSendFuture<'ch, T> {
195        DynamicSendFuture {
196            channel: self.channel,
197            message: Some(message),
198        }
199    }
200
201    /// Attempt to immediately send a message.
202    ///
203    /// See [`Channel::send()`]
204    pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
205        self.channel.try_send_with_context(message, None)
206    }
207
208    /// Allows a poll_fn to poll until the channel is ready to send
209    ///
210    /// See [`Channel::poll_ready_to_send()`]
211    pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
212        self.channel.poll_ready_to_send(cx)
213    }
214
215    /// Returns whether the channel is full.
216    ///
217    /// See [`Channel::is_full()`]
218    pub fn is_full(&self) -> bool {
219        self.channel.is_full()
220    }
221}
222
223/// Send-only access to a [`Channel`] without knowing channel size.
224/// This version can be sent between threads but can only be created if the underlying mutex is Sync.
225pub struct SendDynamicSender<'ch, T> {
226    pub(crate) channel: &'ch dyn DynamicChannel<T>,
227}
228
229impl<'ch, T> Clone for SendDynamicSender<'ch, T> {
230    fn clone(&self) -> Self {
231        *self
232    }
233}
234
235impl<'ch, T> Copy for SendDynamicSender<'ch, T> {}
236unsafe impl<'ch, T: Send> Send for SendDynamicSender<'ch, T> {}
237unsafe impl<'ch, T: Send> Sync for SendDynamicSender<'ch, T> {}
238
239impl<'ch, M, T, const N: usize> From<Sender<'ch, M, T, N>> for SendDynamicSender<'ch, T>
240where
241    M: RawMutex + Sync + Send,
242{
243    fn from(s: Sender<'ch, M, T, N>) -> Self {
244        Self { channel: s.channel }
245    }
246}
247
248impl<'ch, T> SendDynamicSender<'ch, T> {
249    /// Sends a value.
250    ///
251    /// See [`Channel::send()`]
252    pub fn send(&self, message: T) -> DynamicSendFuture<'ch, T> {
253        DynamicSendFuture {
254            channel: self.channel,
255            message: Some(message),
256        }
257    }
258
259    /// Attempt to immediately send a message.
260    ///
261    /// See [`Channel::send()`]
262    pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
263        self.channel.try_send_with_context(message, None)
264    }
265
266    /// Allows a poll_fn to poll until the channel is ready to send
267    ///
268    /// See [`Channel::poll_ready_to_send()`]
269    pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
270        self.channel.poll_ready_to_send(cx)
271    }
272}
273
274/// Receive-only access to a [`Channel`].
275#[derive(Debug)]
276pub struct Receiver<'ch, M, T, const N: usize>
277where
278    M: RawMutex,
279{
280    channel: &'ch Channel<M, T, N>,
281}
282
283impl<'ch, M, T, const N: usize> Clone for Receiver<'ch, M, T, N>
284where
285    M: RawMutex,
286{
287    fn clone(&self) -> Self {
288        *self
289    }
290}
291
292impl<'ch, M, T, const N: usize> Copy for Receiver<'ch, M, T, N> where M: RawMutex {}
293
294impl<'ch, M, T, const N: usize> Receiver<'ch, M, T, N>
295where
296    M: RawMutex,
297{
298    /// Receive the next value.
299    ///
300    /// See [`Channel::receive()`].
301    pub fn receive(&self) -> ReceiveFuture<'_, M, T, N> {
302        self.channel.receive()
303    }
304
305    /// Is a value ready to be received in the channel
306    ///
307    /// See [`Channel::ready_to_receive()`].
308    pub fn ready_to_receive(&self) -> ReceiveReadyFuture<'_, M, T, N> {
309        self.channel.ready_to_receive()
310    }
311
312    /// Attempt to immediately receive the next value.
313    ///
314    /// See [`Channel::try_receive()`]
315    pub fn try_receive(&self) -> Result<T, TryReceiveError> {
316        self.channel.try_receive()
317    }
318
319    /// Peek at the next value without removing it from the queue.
320    ///
321    /// See [`Channel::try_peek()`]
322    pub fn try_peek(&self) -> Result<T, TryReceiveError>
323    where
324        T: Clone,
325    {
326        self.channel.try_peek()
327    }
328
329    /// Allows a poll_fn to poll until the channel is ready to receive
330    ///
331    /// See [`Channel::poll_ready_to_receive()`]
332    pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
333        self.channel.poll_ready_to_receive(cx)
334    }
335
336    /// Poll the channel for the next item
337    ///
338    /// See [`Channel::poll_receive()`]
339    pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
340        self.channel.poll_receive(cx)
341    }
342
343    /// Returns the maximum number of elements the channel can hold.
344    ///
345    /// See [`Channel::capacity()`]
346    pub const fn capacity(&self) -> usize {
347        self.channel.capacity()
348    }
349
350    /// Returns the free capacity of the channel.
351    ///
352    /// See [`Channel::free_capacity()`]
353    pub fn free_capacity(&self) -> usize {
354        self.channel.free_capacity()
355    }
356
357    /// Clears all elements in the channel.
358    ///
359    /// See [`Channel::clear()`]
360    pub fn clear(&self) {
361        self.channel.clear();
362    }
363
364    /// Returns the number of elements currently in the channel.
365    ///
366    /// See [`Channel::len()`]
367    pub fn len(&self) -> usize {
368        self.channel.len()
369    }
370
371    /// Returns whether the channel is empty.
372    ///
373    /// See [`Channel::is_empty()`]
374    pub fn is_empty(&self) -> bool {
375        self.channel.is_empty()
376    }
377
378    /// Returns whether the channel is full.
379    ///
380    /// See [`Channel::is_full()`]
381    pub fn is_full(&self) -> bool {
382        self.channel.is_full()
383    }
384}
385
386/// Receive-only access to a [`Channel`] without knowing channel size.
387pub struct DynamicReceiver<'ch, T> {
388    pub(crate) channel: &'ch dyn DynamicChannel<T>,
389}
390
391impl<'ch, T> Clone for DynamicReceiver<'ch, T> {
392    fn clone(&self) -> Self {
393        *self
394    }
395}
396
397impl<'ch, T> Copy for DynamicReceiver<'ch, T> {}
398
399impl<'ch, T> DynamicReceiver<'ch, T> {
400    /// Receive the next value.
401    ///
402    /// See [`Channel::receive()`].
403    pub fn receive(&self) -> DynamicReceiveFuture<'_, T> {
404        DynamicReceiveFuture { channel: self.channel }
405    }
406
407    /// Attempt to immediately receive the next value.
408    ///
409    /// See [`Channel::try_receive()`]
410    pub fn try_receive(&self) -> Result<T, TryReceiveError> {
411        self.channel.try_receive_with_context(None)
412    }
413
414    /// Peek at the next value without removing it from the queue.
415    ///
416    /// See [`Channel::try_peek()`]
417    pub fn try_peek(&self) -> Result<T, TryReceiveError>
418    where
419        T: Clone,
420    {
421        self.channel.try_peek_with_context(None)
422    }
423
424    /// Allows a poll_fn to poll until the channel is ready to receive
425    ///
426    /// See [`Channel::poll_ready_to_receive()`]
427    pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
428        self.channel.poll_ready_to_receive(cx)
429    }
430
431    /// Poll the channel for the next item
432    ///
433    /// See [`Channel::poll_receive()`]
434    pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
435        self.channel.poll_receive(cx)
436    }
437}
438
439impl<'ch, M, T, const N: usize> From<Receiver<'ch, M, T, N>> for DynamicReceiver<'ch, T>
440where
441    M: RawMutex,
442{
443    fn from(s: Receiver<'ch, M, T, N>) -> Self {
444        Self { channel: s.channel }
445    }
446}
447
448/// Receive-only access to a [`Channel`] without knowing channel size.
449/// This version can be sent between threads but can only be created if the underlying mutex is Sync.
450pub struct SendDynamicReceiver<'ch, T> {
451    pub(crate) channel: &'ch dyn DynamicChannel<T>,
452}
453
454/// Receive-only access to a [`Channel`] without knowing channel size.
455/// This version can be sent between threads but can only be created if the underlying mutex is Sync.
456#[deprecated(since = "0.7.1", note = "please use `SendDynamicReceiver` instead")]
457pub type SendableDynamicReceiver<'ch, T> = SendDynamicReceiver<'ch, T>;
458
459impl<'ch, T> Clone for SendDynamicReceiver<'ch, T> {
460    fn clone(&self) -> Self {
461        *self
462    }
463}
464
465impl<'ch, T> Copy for SendDynamicReceiver<'ch, T> {}
466unsafe impl<'ch, T: Send> Send for SendDynamicReceiver<'ch, T> {}
467unsafe impl<'ch, T: Send> Sync for SendDynamicReceiver<'ch, T> {}
468
469impl<'ch, T> SendDynamicReceiver<'ch, T> {
470    /// Receive the next value.
471    ///
472    /// See [`Channel::receive()`].
473    pub fn receive(&self) -> DynamicReceiveFuture<'_, T> {
474        DynamicReceiveFuture { channel: self.channel }
475    }
476
477    /// Attempt to immediately receive the next value.
478    ///
479    /// See [`Channel::try_receive()`]
480    pub fn try_receive(&self) -> Result<T, TryReceiveError> {
481        self.channel.try_receive_with_context(None)
482    }
483
484    /// Allows a poll_fn to poll until the channel is ready to receive
485    ///
486    /// See [`Channel::poll_ready_to_receive()`]
487    pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
488        self.channel.poll_ready_to_receive(cx)
489    }
490
491    /// Poll the channel for the next item
492    ///
493    /// See [`Channel::poll_receive()`]
494    pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
495        self.channel.poll_receive(cx)
496    }
497}
498
499impl<'ch, M, T, const N: usize> From<Receiver<'ch, M, T, N>> for SendDynamicReceiver<'ch, T>
500where
501    M: RawMutex + Sync + Send,
502{
503    fn from(s: Receiver<'ch, M, T, N>) -> Self {
504        Self { channel: s.channel }
505    }
506}
507
508impl<'ch, M, T, const N: usize> futures_core::Stream for Receiver<'ch, M, T, N>
509where
510    M: RawMutex,
511{
512    type Item = T;
513
514    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
515        self.channel.poll_receive(cx).map(Some)
516    }
517}
518
519/// Future returned by [`Channel::receive`] and  [`Receiver::receive`].
520#[must_use = "futures do nothing unless you `.await` or poll them"]
521#[derive(Debug)]
522pub struct ReceiveFuture<'ch, M, T, const N: usize>
523where
524    M: RawMutex,
525{
526    channel: &'ch Channel<M, T, N>,
527}
528
529impl<'ch, M, T, const N: usize> Future for ReceiveFuture<'ch, M, T, N>
530where
531    M: RawMutex,
532{
533    type Output = T;
534
535    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
536        self.channel.poll_receive(cx)
537    }
538}
539
540/// Future returned by [`Channel::ready_to_receive`] and  [`Receiver::ready_to_receive`].
541#[must_use = "futures do nothing unless you `.await` or poll them"]
542#[derive(Debug)]
543pub struct ReceiveReadyFuture<'ch, M, T, const N: usize>
544where
545    M: RawMutex,
546{
547    channel: &'ch Channel<M, T, N>,
548}
549
550impl<'ch, M, T, const N: usize> Future for ReceiveReadyFuture<'ch, M, T, N>
551where
552    M: RawMutex,
553{
554    type Output = ();
555
556    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
557        self.channel.poll_ready_to_receive(cx)
558    }
559}
560
561/// Future returned by [`DynamicReceiver::receive`].
562#[must_use = "futures do nothing unless you `.await` or poll them"]
563pub struct DynamicReceiveFuture<'ch, T> {
564    channel: &'ch dyn DynamicChannel<T>,
565}
566
567impl<'ch, T> Future for DynamicReceiveFuture<'ch, T> {
568    type Output = T;
569
570    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
571        match self.channel.try_receive_with_context(Some(cx)) {
572            Ok(v) => Poll::Ready(v),
573            Err(TryReceiveError::Empty) => Poll::Pending,
574        }
575    }
576}
577
578impl<'ch, M: RawMutex, T, const N: usize> From<ReceiveFuture<'ch, M, T, N>> for DynamicReceiveFuture<'ch, T> {
579    fn from(value: ReceiveFuture<'ch, M, T, N>) -> Self {
580        Self { channel: value.channel }
581    }
582}
583
584/// Future returned by [`Channel::send`] and  [`Sender::send`].
585#[must_use = "futures do nothing unless you `.await` or poll them"]
586#[derive(Debug)]
587pub struct SendFuture<'ch, M, T, const N: usize>
588where
589    M: RawMutex,
590{
591    channel: &'ch Channel<M, T, N>,
592    message: Option<T>,
593}
594
595impl<'ch, M, T, const N: usize> Future for SendFuture<'ch, M, T, N>
596where
597    M: RawMutex,
598{
599    type Output = ();
600
601    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
602        match self.message.take() {
603            Some(m) => match self.channel.try_send_with_context(m, Some(cx)) {
604                Ok(..) => Poll::Ready(()),
605                Err(TrySendError::Full(m)) => {
606                    self.message = Some(m);
607                    Poll::Pending
608                }
609            },
610            None => panic!("Message cannot be None"),
611        }
612    }
613}
614
615impl<'ch, M, T, const N: usize> Unpin for SendFuture<'ch, M, T, N> where M: RawMutex {}
616
617/// Future returned by [`DynamicSender::send`].
618#[must_use = "futures do nothing unless you `.await` or poll them"]
619pub struct DynamicSendFuture<'ch, T> {
620    channel: &'ch dyn DynamicChannel<T>,
621    message: Option<T>,
622}
623
624impl<'ch, T> Future for DynamicSendFuture<'ch, T> {
625    type Output = ();
626
627    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
628        match self.message.take() {
629            Some(m) => match self.channel.try_send_with_context(m, Some(cx)) {
630                Ok(..) => Poll::Ready(()),
631                Err(TrySendError::Full(m)) => {
632                    self.message = Some(m);
633                    Poll::Pending
634                }
635            },
636            None => panic!("Message cannot be None"),
637        }
638    }
639}
640
641impl<'ch, T> Unpin for DynamicSendFuture<'ch, T> {}
642
643impl<'ch, M: RawMutex, T, const N: usize> From<SendFuture<'ch, M, T, N>> for DynamicSendFuture<'ch, T> {
644    fn from(value: SendFuture<'ch, M, T, N>) -> Self {
645        Self {
646            channel: value.channel,
647            message: value.message,
648        }
649    }
650}
651
652pub(crate) trait DynamicChannel<T> {
653    fn try_send_with_context(&self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>>;
654
655    fn try_receive_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError>;
656
657    fn try_peek_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError>
658    where
659        T: Clone;
660
661    fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()>;
662    fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()>;
663
664    fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T>;
665
666    fn is_full(&self) -> bool;
667}
668
669/// Error returned by [`try_receive`](Channel::try_receive).
670#[derive(PartialEq, Eq, Clone, Copy, Debug)]
671#[cfg_attr(feature = "defmt", derive(defmt::Format))]
672pub enum TryReceiveError {
673    /// A message could not be received because the channel is empty.
674    Empty,
675}
676
677/// Error returned by [`try_send`](Channel::try_send).
678#[derive(PartialEq, Eq, Clone, Copy, Debug)]
679#[cfg_attr(feature = "defmt", derive(defmt::Format))]
680pub enum TrySendError<T> {
681    /// The data could not be sent on the channel because the channel is
682    /// currently full and sending would require blocking.
683    Full(T),
684}
685
686#[derive(Debug)]
687struct ChannelState<T, const N: usize> {
688    queue: Deque<T, N>,
689    receiver_waker: WakerRegistration,
690    senders_waker: WakerRegistration,
691}
692
693impl<T, const N: usize> ChannelState<T, N> {
694    const fn new() -> Self {
695        ChannelState {
696            queue: Deque::new(),
697            receiver_waker: WakerRegistration::new(),
698            senders_waker: WakerRegistration::new(),
699        }
700    }
701
702    fn try_receive(&mut self) -> Result<T, TryReceiveError> {
703        self.try_receive_with_context(None)
704    }
705
706    fn try_peek(&mut self) -> Result<T, TryReceiveError>
707    where
708        T: Clone,
709    {
710        self.try_peek_with_context(None)
711    }
712
713    fn try_peek_with_context(&mut self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError>
714    where
715        T: Clone,
716    {
717        if self.queue.is_full() {
718            self.senders_waker.wake();
719        }
720
721        if let Some(message) = self.queue.front() {
722            Ok(message.clone())
723        } else {
724            if let Some(cx) = cx {
725                self.receiver_waker.register(cx.waker());
726            }
727            Err(TryReceiveError::Empty)
728        }
729    }
730
731    fn try_receive_with_context(&mut self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError> {
732        if self.queue.is_full() {
733            self.senders_waker.wake();
734        }
735
736        if let Some(message) = self.queue.pop_front() {
737            Ok(message)
738        } else {
739            if let Some(cx) = cx {
740                self.receiver_waker.register(cx.waker());
741            }
742            Err(TryReceiveError::Empty)
743        }
744    }
745
746    fn poll_receive(&mut self, cx: &mut Context<'_>) -> Poll<T> {
747        if self.queue.is_full() {
748            self.senders_waker.wake();
749        }
750
751        if let Some(message) = self.queue.pop_front() {
752            Poll::Ready(message)
753        } else {
754            self.receiver_waker.register(cx.waker());
755            Poll::Pending
756        }
757    }
758
759    fn poll_ready_to_receive(&mut self, cx: &mut Context<'_>) -> Poll<()> {
760        self.receiver_waker.register(cx.waker());
761
762        if !self.queue.is_empty() {
763            Poll::Ready(())
764        } else {
765            Poll::Pending
766        }
767    }
768
769    fn try_send(&mut self, message: T) -> Result<(), TrySendError<T>> {
770        self.try_send_with_context(message, None)
771    }
772
773    fn try_send_with_context(&mut self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>> {
774        match self.queue.push_back(message) {
775            Ok(()) => {
776                self.receiver_waker.wake();
777                Ok(())
778            }
779            Err(message) => {
780                if let Some(cx) = cx {
781                    self.senders_waker.register(cx.waker());
782                }
783                Err(TrySendError::Full(message))
784            }
785        }
786    }
787
788    fn poll_ready_to_send(&mut self, cx: &mut Context<'_>) -> Poll<()> {
789        self.senders_waker.register(cx.waker());
790
791        if !self.queue.is_full() {
792            Poll::Ready(())
793        } else {
794            Poll::Pending
795        }
796    }
797
798    fn clear(&mut self) {
799        if self.queue.is_full() {
800            self.senders_waker.wake();
801        }
802        self.queue.clear();
803    }
804
805    fn len(&self) -> usize {
806        self.queue.len()
807    }
808
809    fn is_empty(&self) -> bool {
810        self.queue.is_empty()
811    }
812
813    fn is_full(&self) -> bool {
814        self.queue.is_full()
815    }
816}
817
818/// A bounded channel for communicating between asynchronous tasks
819/// with backpressure.
820///
821/// The channel will buffer up to the provided number of messages.  Once the
822/// buffer is full, attempts to `send` new messages will wait until a message is
823/// received from the channel.
824///
825/// All data sent will become available in the same order as it was sent.
826#[derive(Debug)]
827pub struct Channel<M, T, const N: usize>
828where
829    M: RawMutex,
830{
831    inner: Mutex<M, RefCell<ChannelState<T, N>>>,
832}
833
834impl<M, T, const N: usize> Channel<M, T, N>
835where
836    M: RawMutex,
837{
838    /// Establish a new bounded channel. For example, to create one with a NoopMutex:
839    ///
840    /// ```
841    /// use hazard3_sync::channel::Channel;
842    /// use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
843    ///
844    /// // Declare a bounded channel of 3 u32s.
845    /// let mut channel = Channel::<NoopRawMutex, u32, 3>::new();
846    /// ```
847    pub const fn new() -> Self {
848        Self {
849            inner: Mutex::new(RefCell::new(ChannelState::new())),
850        }
851    }
852
853    fn lock<R>(&self, f: impl FnOnce(&mut ChannelState<T, N>) -> R) -> R {
854        self.inner.lock(|rc| f(&mut *unwrap!(rc.try_borrow_mut())))
855    }
856
857    fn try_receive_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError> {
858        self.lock(|c| c.try_receive_with_context(cx))
859    }
860
861    fn try_peek_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError>
862    where
863        T: Clone,
864    {
865        self.lock(|c| c.try_peek_with_context(cx))
866    }
867
868    /// Poll the channel for the next message
869    pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
870        self.lock(|c| c.poll_receive(cx))
871    }
872
873    fn try_send_with_context(&self, m: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>> {
874        self.lock(|c| c.try_send_with_context(m, cx))
875    }
876
877    /// Allows a poll_fn to poll until the channel is ready to receive
878    pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
879        self.lock(|c| c.poll_ready_to_receive(cx))
880    }
881
882    /// Allows a poll_fn to poll until the channel is ready to send
883    pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
884        self.lock(|c| c.poll_ready_to_send(cx))
885    }
886
887    /// Get a sender for this channel.
888    pub const fn sender(&self) -> Sender<'_, M, T, N> {
889        Sender { channel: self }
890    }
891
892    /// Get a receiver for this channel.
893    pub const fn receiver(&self) -> Receiver<'_, M, T, N> {
894        Receiver { channel: self }
895    }
896
897    /// Get a sender for this channel using dynamic dispatch.
898    pub fn dyn_sender(&self) -> DynamicSender<'_, T> {
899        DynamicSender { channel: self }
900    }
901
902    /// Get a receiver for this channel using dynamic dispatch.
903    pub fn dyn_receiver(&self) -> DynamicReceiver<'_, T> {
904        DynamicReceiver { channel: self }
905    }
906
907    /// Send a value, waiting until there is capacity.
908    ///
909    /// Sending completes when the value has been pushed to the channel's queue.
910    /// This doesn't mean the value has been received yet.
911    pub fn send(&self, message: T) -> SendFuture<'_, M, T, N> {
912        SendFuture {
913            channel: self,
914            message: Some(message),
915        }
916    }
917
918    /// Attempt to immediately send a message.
919    ///
920    /// This method differs from [`send`](Channel::send) by returning immediately if the channel's
921    /// buffer is full, instead of waiting.
922    ///
923    /// # Errors
924    ///
925    /// If the channel capacity has been reached, i.e., the channel has `n`
926    /// buffered values where `n` is the argument passed to [`Channel`], then an
927    /// error is returned.
928    pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
929        self.lock(|c| c.try_send(message))
930    }
931
932    /// Receive the next value.
933    ///
934    /// If there are no messages in the channel's buffer, this method will
935    /// wait until a message is sent.
936    pub fn receive(&self) -> ReceiveFuture<'_, M, T, N> {
937        ReceiveFuture { channel: self }
938    }
939
940    /// Is a value ready to be received in the channel
941    ///
942    /// If there are no messages in the channel's buffer, this method will
943    /// wait until there is at least one
944    pub fn ready_to_receive(&self) -> ReceiveReadyFuture<'_, M, T, N> {
945        ReceiveReadyFuture { channel: self }
946    }
947
948    /// Attempt to immediately receive a message.
949    ///
950    /// This method will either receive a message from the channel immediately or return an error
951    /// if the channel is empty.
952    pub fn try_receive(&self) -> Result<T, TryReceiveError> {
953        self.lock(|c| c.try_receive())
954    }
955
956    /// Peek at the next value without removing it from the queue.
957    ///
958    /// This method will either receive a copy of the message from the channel immediately or return
959    /// an error if the channel is empty.
960    pub fn try_peek(&self) -> Result<T, TryReceiveError>
961    where
962        T: Clone,
963    {
964        self.lock(|c| c.try_peek())
965    }
966
967    /// Returns the maximum number of elements the channel can hold.
968    pub const fn capacity(&self) -> usize {
969        N
970    }
971
972    /// Returns the free capacity of the channel.
973    ///
974    /// This is equivalent to `capacity() - len()`
975    pub fn free_capacity(&self) -> usize {
976        N - self.len()
977    }
978
979    /// Clears all elements in the channel.
980    pub fn clear(&self) {
981        self.lock(|c| c.clear());
982    }
983
984    /// Returns the number of elements currently in the channel.
985    pub fn len(&self) -> usize {
986        self.lock(|c| c.len())
987    }
988
989    /// Returns whether the channel is empty.
990    pub fn is_empty(&self) -> bool {
991        self.lock(|c| c.is_empty())
992    }
993
994    /// Returns whether the channel is full.
995    pub fn is_full(&self) -> bool {
996        self.lock(|c| c.is_full())
997    }
998}
999
1000/// Implements the DynamicChannel to allow creating types that are unaware of the queue size with the
1001/// tradeoff cost of dynamic dispatch.
1002impl<M, T, const N: usize> DynamicChannel<T> for Channel<M, T, N>
1003where
1004    M: RawMutex,
1005{
1006    fn try_send_with_context(&self, m: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>> {
1007        Channel::try_send_with_context(self, m, cx)
1008    }
1009
1010    fn try_receive_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError> {
1011        Channel::try_receive_with_context(self, cx)
1012    }
1013
1014    fn try_peek_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError>
1015    where
1016        T: Clone,
1017    {
1018        Channel::try_peek_with_context(self, cx)
1019    }
1020
1021    fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
1022        Channel::poll_ready_to_send(self, cx)
1023    }
1024
1025    fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
1026        Channel::poll_ready_to_receive(self, cx)
1027    }
1028
1029    fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
1030        Channel::poll_receive(self, cx)
1031    }
1032
1033    fn is_full(&self) -> bool {
1034        Channel::is_full(self)
1035    }
1036}
1037
1038impl<M, T, const N: usize> futures_core::Stream for Channel<M, T, N>
1039where
1040    M: RawMutex,
1041{
1042    type Item = T;
1043
1044    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1045        self.poll_receive(cx).map(Some)
1046    }
1047}
1048
1049impl<M, T, const N: usize> futures_sink::Sink<T> for Channel<M, T, N>
1050where
1051    M: RawMutex,
1052{
1053    type Error = TrySendError<T>;
1054
1055    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1056        self.poll_ready_to_send(cx).map(|()| Ok(()))
1057    }
1058
1059    fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
1060        self.try_send(item)
1061    }
1062
1063    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1064        Poll::Ready(Ok(()))
1065    }
1066
1067    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1068        Poll::Ready(Ok(()))
1069    }
1070}
1071
1072impl core::fmt::Display for TryReceiveError {
1073    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1074        match self {
1075            Self::Empty => f.write_str("Empty"),
1076        }
1077    }
1078}
1079impl core::error::Error for TryReceiveError {}
1080
1081impl<T> core::fmt::Display for TrySendError<T> {
1082    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1083        match self {
1084            Self::Full(_) => f.write_str("Full"),
1085        }
1086    }
1087}
1088impl<T: core::fmt::Debug> core::error::Error for TrySendError<T> {}
1089
1090#[cfg(test)]
1091mod tests {
1092    use core::time::Duration;
1093
1094    use futures_executor::ThreadPool;
1095    use futures_timer::Delay;
1096    use futures_util::task::SpawnExt;
1097    use static_cell::StaticCell;
1098
1099    use super::*;
1100    use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
1101
1102    fn capacity<T, const N: usize>(c: &ChannelState<T, N>) -> usize {
1103        c.queue.capacity() - c.queue.len()
1104    }
1105
1106    #[test]
1107    fn sending_once() {
1108        let mut c = ChannelState::<u32, 3>::new();
1109        assert!(c.try_send(1).is_ok());
1110        assert_eq!(capacity(&c), 2);
1111    }
1112
1113    #[test]
1114    fn sending_when_full() {
1115        let mut c = ChannelState::<u32, 3>::new();
1116        let _ = c.try_send(1);
1117        let _ = c.try_send(1);
1118        let _ = c.try_send(1);
1119        match c.try_send(2) {
1120            Err(TrySendError::Full(2)) => assert!(true),
1121            _ => assert!(false),
1122        }
1123        assert_eq!(capacity(&c), 0);
1124    }
1125
1126    #[test]
1127    fn receiving_once_with_one_send() {
1128        let mut c = ChannelState::<u32, 3>::new();
1129        assert!(c.try_send(1).is_ok());
1130        assert_eq!(c.try_receive().unwrap(), 1);
1131        assert_eq!(capacity(&c), 3);
1132    }
1133
1134    #[test]
1135    fn receiving_when_empty() {
1136        let mut c = ChannelState::<u32, 3>::new();
1137        match c.try_receive() {
1138            Err(TryReceiveError::Empty) => assert!(true),
1139            _ => assert!(false),
1140        }
1141        assert_eq!(capacity(&c), 3);
1142    }
1143
1144    #[test]
1145    fn simple_send_and_receive() {
1146        let c = Channel::<NoopRawMutex, u32, 3>::new();
1147        assert!(c.try_send(1).is_ok());
1148        assert_eq!(c.try_peek().unwrap(), 1);
1149        assert_eq!(c.try_peek().unwrap(), 1);
1150        assert_eq!(c.try_receive().unwrap(), 1);
1151    }
1152
1153    #[test]
1154    fn cloning() {
1155        let c = Channel::<NoopRawMutex, u32, 3>::new();
1156        let r1 = c.receiver();
1157        let s1 = c.sender();
1158
1159        let _ = r1.clone();
1160        let _ = s1.clone();
1161    }
1162
1163    #[test]
1164    fn dynamic_dispatch_into() {
1165        let c = Channel::<NoopRawMutex, u32, 3>::new();
1166        let s: DynamicSender<'_, u32> = c.sender().into();
1167        let r: DynamicReceiver<'_, u32> = c.receiver().into();
1168
1169        assert!(s.try_send(1).is_ok());
1170        assert_eq!(r.try_receive().unwrap(), 1);
1171    }
1172
1173    #[test]
1174    fn dynamic_dispatch_constructor() {
1175        let c = Channel::<NoopRawMutex, u32, 3>::new();
1176        let s = c.dyn_sender();
1177        let r = c.dyn_receiver();
1178
1179        assert!(s.try_send(1).is_ok());
1180        assert_eq!(r.try_peek().unwrap(), 1);
1181        assert_eq!(r.try_peek().unwrap(), 1);
1182        assert_eq!(r.try_receive().unwrap(), 1);
1183    }
1184
1185    #[futures_test::test]
1186    async fn receiver_receives_given_try_send_async() {
1187        let executor = ThreadPool::new().unwrap();
1188
1189        static CHANNEL: StaticCell<Channel<CriticalSectionRawMutex, u32, 3>> = StaticCell::new();
1190        let c = &*CHANNEL.init(Channel::new());
1191        let c2 = c;
1192        assert!(
1193            executor
1194                .spawn(async move {
1195                    assert!(c2.try_send(1).is_ok());
1196                })
1197                .is_ok()
1198        );
1199        assert_eq!(c.receive().await, 1);
1200    }
1201
1202    #[futures_test::test]
1203    async fn sender_send_completes_if_capacity() {
1204        let c = Channel::<CriticalSectionRawMutex, u32, 1>::new();
1205        c.send(1).await;
1206        assert_eq!(c.receive().await, 1);
1207    }
1208
1209    #[futures_test::test]
1210    async fn senders_sends_wait_until_capacity() {
1211        let executor = ThreadPool::new().unwrap();
1212
1213        static CHANNEL: StaticCell<Channel<CriticalSectionRawMutex, u32, 1>> = StaticCell::new();
1214        let c = &*CHANNEL.init(Channel::new());
1215        assert!(c.try_send(1).is_ok());
1216
1217        let c2 = c;
1218        let send_task_1 = executor.spawn_with_handle(async move { c2.send(2).await });
1219        let c2 = c;
1220        let send_task_2 = executor.spawn_with_handle(async move { c2.send(3).await });
1221        // Wish I could think of a means of determining that the async send is waiting instead.
1222        // However, I've used the debugger to observe that the send does indeed wait.
1223        Delay::new(Duration::from_millis(500)).await;
1224        assert_eq!(c.receive().await, 1);
1225        assert!(
1226            executor
1227                .spawn(async move {
1228                    loop {
1229                        c.receive().await;
1230                    }
1231                })
1232                .is_ok()
1233        );
1234        send_task_1.unwrap().await;
1235        send_task_2.unwrap().await;
1236    }
1237}