1use 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#[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 pub fn send(&self, message: T) -> SendFuture<'ch, M, T, N> {
108 self.channel.send(message)
109 }
110
111 pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
115 self.channel.try_send(message)
116 }
117
118 pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
122 self.channel.poll_ready_to_send(cx)
123 }
124
125 pub const fn capacity(&self) -> usize {
129 self.channel.capacity()
130 }
131
132 pub fn free_capacity(&self) -> usize {
136 self.channel.free_capacity()
137 }
138
139 pub fn clear(&self) {
143 self.channel.clear();
144 }
145
146 pub fn len(&self) -> usize {
150 self.channel.len()
151 }
152
153 pub fn is_empty(&self) -> bool {
157 self.channel.is_empty()
158 }
159
160 pub fn is_full(&self) -> bool {
164 self.channel.is_full()
165 }
166}
167
168pub 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 pub fn send(&self, message: T) -> DynamicSendFuture<'ch, T> {
195 DynamicSendFuture {
196 channel: self.channel,
197 message: Some(message),
198 }
199 }
200
201 pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
205 self.channel.try_send_with_context(message, None)
206 }
207
208 pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
212 self.channel.poll_ready_to_send(cx)
213 }
214
215 pub fn is_full(&self) -> bool {
219 self.channel.is_full()
220 }
221}
222
223pub 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 pub fn send(&self, message: T) -> DynamicSendFuture<'ch, T> {
253 DynamicSendFuture {
254 channel: self.channel,
255 message: Some(message),
256 }
257 }
258
259 pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
263 self.channel.try_send_with_context(message, None)
264 }
265
266 pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
270 self.channel.poll_ready_to_send(cx)
271 }
272}
273
274#[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 pub fn receive(&self) -> ReceiveFuture<'_, M, T, N> {
302 self.channel.receive()
303 }
304
305 pub fn ready_to_receive(&self) -> ReceiveReadyFuture<'_, M, T, N> {
309 self.channel.ready_to_receive()
310 }
311
312 pub fn try_receive(&self) -> Result<T, TryReceiveError> {
316 self.channel.try_receive()
317 }
318
319 pub fn try_peek(&self) -> Result<T, TryReceiveError>
323 where
324 T: Clone,
325 {
326 self.channel.try_peek()
327 }
328
329 pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
333 self.channel.poll_ready_to_receive(cx)
334 }
335
336 pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
340 self.channel.poll_receive(cx)
341 }
342
343 pub const fn capacity(&self) -> usize {
347 self.channel.capacity()
348 }
349
350 pub fn free_capacity(&self) -> usize {
354 self.channel.free_capacity()
355 }
356
357 pub fn clear(&self) {
361 self.channel.clear();
362 }
363
364 pub fn len(&self) -> usize {
368 self.channel.len()
369 }
370
371 pub fn is_empty(&self) -> bool {
375 self.channel.is_empty()
376 }
377
378 pub fn is_full(&self) -> bool {
382 self.channel.is_full()
383 }
384}
385
386pub 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 pub fn receive(&self) -> DynamicReceiveFuture<'_, T> {
404 DynamicReceiveFuture { channel: self.channel }
405 }
406
407 pub fn try_receive(&self) -> Result<T, TryReceiveError> {
411 self.channel.try_receive_with_context(None)
412 }
413
414 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 pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
428 self.channel.poll_ready_to_receive(cx)
429 }
430
431 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
448pub struct SendDynamicReceiver<'ch, T> {
451 pub(crate) channel: &'ch dyn DynamicChannel<T>,
452}
453
454#[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 pub fn receive(&self) -> DynamicReceiveFuture<'_, T> {
474 DynamicReceiveFuture { channel: self.channel }
475 }
476
477 pub fn try_receive(&self) -> Result<T, TryReceiveError> {
481 self.channel.try_receive_with_context(None)
482 }
483
484 pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
488 self.channel.poll_ready_to_receive(cx)
489 }
490
491 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#[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#[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#[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#[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#[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#[derive(PartialEq, Eq, Clone, Copy, Debug)]
671#[cfg_attr(feature = "defmt", derive(defmt::Format))]
672pub enum TryReceiveError {
673 Empty,
675}
676
677#[derive(PartialEq, Eq, Clone, Copy, Debug)]
679#[cfg_attr(feature = "defmt", derive(defmt::Format))]
680pub enum TrySendError<T> {
681 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#[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 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 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 pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
879 self.lock(|c| c.poll_ready_to_receive(cx))
880 }
881
882 pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
884 self.lock(|c| c.poll_ready_to_send(cx))
885 }
886
887 pub const fn sender(&self) -> Sender<'_, M, T, N> {
889 Sender { channel: self }
890 }
891
892 pub const fn receiver(&self) -> Receiver<'_, M, T, N> {
894 Receiver { channel: self }
895 }
896
897 pub fn dyn_sender(&self) -> DynamicSender<'_, T> {
899 DynamicSender { channel: self }
900 }
901
902 pub fn dyn_receiver(&self) -> DynamicReceiver<'_, T> {
904 DynamicReceiver { channel: self }
905 }
906
907 pub fn send(&self, message: T) -> SendFuture<'_, M, T, N> {
912 SendFuture {
913 channel: self,
914 message: Some(message),
915 }
916 }
917
918 pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
929 self.lock(|c| c.try_send(message))
930 }
931
932 pub fn receive(&self) -> ReceiveFuture<'_, M, T, N> {
937 ReceiveFuture { channel: self }
938 }
939
940 pub fn ready_to_receive(&self) -> ReceiveReadyFuture<'_, M, T, N> {
945 ReceiveReadyFuture { channel: self }
946 }
947
948 pub fn try_receive(&self) -> Result<T, TryReceiveError> {
953 self.lock(|c| c.try_receive())
954 }
955
956 pub fn try_peek(&self) -> Result<T, TryReceiveError>
961 where
962 T: Clone,
963 {
964 self.lock(|c| c.try_peek())
965 }
966
967 pub const fn capacity(&self) -> usize {
969 N
970 }
971
972 pub fn free_capacity(&self) -> usize {
976 N - self.len()
977 }
978
979 pub fn clear(&self) {
981 self.lock(|c| c.clear());
982 }
983
984 pub fn len(&self) -> usize {
986 self.lock(|c| c.len())
987 }
988
989 pub fn is_empty(&self) -> bool {
991 self.lock(|c| c.is_empty())
992 }
993
994 pub fn is_full(&self) -> bool {
996 self.lock(|c| c.is_full())
997 }
998}
999
1000impl<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 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}