Skip to main content

hazard3_sync/
watch.rs

1//! A synchronization primitive for passing the latest value to **multiple** receivers.
2
3use core::cell::RefCell;
4use core::future::{Future, poll_fn};
5use core::marker::PhantomData;
6use core::ops::{Deref, DerefMut};
7use core::task::{Context, Poll};
8
9use crate::blocking_mutex::Mutex;
10use crate::blocking_mutex::raw::RawMutex;
11use crate::waitqueue::MultiWakerRegistration;
12
13/// The `Watch` is a single-slot signaling primitive that allows _multiple_ (`N`) receivers to concurrently await
14/// changes to the value. Unlike a [`Signal`](crate::signal::Signal), `Watch` supports multiple receivers,
15/// and unlike a [`PubSubChannel`](crate::pubsub::PubSubChannel), `Watch` immediately overwrites the previous
16/// value when a new one is sent, without waiting for all receivers to read the previous value.
17///
18/// This makes `Watch` particularly useful when a single task updates a value or "state", and multiple other tasks
19/// need to be notified about changes to this value asynchronously. Receivers may "lose" stale values, as they are
20/// always provided with the latest value.
21///
22/// Typically, `Watch` instances are declared as `static`, and a [`Sender`] and [`Receiver`]
23/// (or [`DynSender`] and/or [`DynReceiver`]) are obtained where relevant. An [`AnonReceiver`]
24/// and [`DynAnonReceiver`] are also available, which do not increase the receiver count for the
25/// channel, and unwrapping is therefore not required, but it is not possible to `.await` the channel.
26/// ```
27///
28/// use futures_executor::block_on;
29/// use hazard3_sync::watch::Watch;
30/// use hazard3_sync::blocking_mutex::raw::CriticalSectionRawMutex;
31///
32/// let f = async {
33///
34/// static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
35///
36/// // Obtain receivers and sender
37/// let mut rcv0 = WATCH.receiver().unwrap();
38/// let mut rcv1 = WATCH.dyn_receiver().unwrap();
39/// let mut snd = WATCH.sender();
40///
41/// // No more receivers, and no update
42/// assert!(WATCH.receiver().is_none());
43/// assert_eq!(rcv1.try_changed(), None);
44///
45/// snd.send(10);
46///
47/// // Receive the new value (async or try)
48/// assert_eq!(rcv0.changed().await, 10);
49/// assert_eq!(rcv1.try_changed(), Some(10));
50///
51/// // No update
52/// assert_eq!(rcv0.try_changed(), None);
53/// assert_eq!(rcv1.try_changed(), None);
54///
55/// snd.send(20);
56///
57/// // Using `get` marks the value as seen
58/// assert_eq!(rcv1.get().await, 20);
59/// assert_eq!(rcv1.try_changed(), None);
60///
61/// // But `get` also returns when unchanged
62/// assert_eq!(rcv1.get().await, 20);
63/// assert_eq!(rcv1.get().await, 20);
64///
65/// };
66/// block_on(f);
67/// ```
68#[derive(Debug)]
69pub struct Watch<M: RawMutex, T: Clone, const N: usize> {
70    mutex: Mutex<M, RefCell<WatchState<T, N>>>,
71}
72
73#[derive(Debug)]
74struct WatchState<T: Clone, const N: usize> {
75    data: Option<T>,
76    current_id: u64,
77    wakers: MultiWakerRegistration<N>,
78    receiver_count: usize,
79}
80
81trait SealedWatchBehavior<T> {
82    /// Poll the `Watch` for the current value, making it as seen.
83    fn poll_get(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll<T>;
84
85    /// Poll the `Watch` for the value if it matches the predicate function
86    /// `f`, making it as seen.
87    fn poll_get_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll<T>;
88
89    /// Poll the `Watch` for a changed value, marking it as seen, if an id is given.
90    fn poll_changed(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll<T>;
91
92    /// Tries to retrieve the value of the `Watch` if it has changed, marking it as seen.
93    fn try_changed(&self, id: &mut u64) -> Option<T>;
94
95    /// Poll the `Watch` for a changed value that matches the predicate function
96    /// `f`, marking it as seen.
97    fn poll_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll<T>;
98
99    /// Tries to retrieve the value of the `Watch` if it has changed and matches the
100    /// predicate function `f`, marking it as seen.
101    fn try_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool) -> Option<T>;
102
103    /// Used when a receiver is dropped to decrement the receiver count.
104    ///
105    /// ## This method should not be called by the user.
106    fn drop_receiver(&self);
107
108    /// Clears the value of the `Watch`.
109    fn clear(&self);
110
111    /// Sends a new value to the `Watch`.
112    fn send(&self, val: T);
113
114    /// Modify the value of the `Watch` using a closure. Returns `false` if the
115    /// `Watch` does not already contain a value.
116    fn send_modify(&self, f: &mut dyn Fn(&mut Option<T>));
117
118    /// Modify the value of the `Watch` using a closure. Returns `false` if the
119    /// `Watch` does not already contain a value.
120    fn send_if_modified(&self, f: &mut dyn Fn(&mut Option<T>) -> bool);
121}
122
123/// A trait representing the 'inner' behavior of the `Watch`.
124#[allow(private_bounds)]
125pub trait WatchBehavior<T: Clone>: SealedWatchBehavior<T> {
126    /// Tries to get the value of the `Watch`, marking it as seen, if an id is given.
127    fn try_get(&self, id: Option<&mut u64>) -> Option<T>;
128
129    /// Tries to get the value of the `Watch` if it matches the predicate function
130    /// `f`, marking it as seen.
131    fn try_get_and(&self, id: Option<&mut u64>, f: &mut dyn Fn(&T) -> bool) -> Option<T>;
132
133    /// Checks if the `Watch` is been initialized with a value.
134    fn contains_value(&self) -> bool;
135}
136
137impl<M: RawMutex, T: Clone, const N: usize> SealedWatchBehavior<T> for Watch<M, T, N> {
138    fn poll_get(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll<T> {
139        self.mutex.lock(|state| {
140            let mut s = state.borrow_mut();
141            match &s.data {
142                Some(data) => {
143                    *id = s.current_id;
144                    Poll::Ready(data.clone())
145                }
146                None => {
147                    s.wakers.register(cx.waker());
148                    Poll::Pending
149                }
150            }
151        })
152    }
153
154    fn poll_get_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll<T> {
155        self.mutex.lock(|state| {
156            let mut s = state.borrow_mut();
157            match s.data {
158                Some(ref data) if f(data) => {
159                    *id = s.current_id;
160                    Poll::Ready(data.clone())
161                }
162                _ => {
163                    s.wakers.register(cx.waker());
164                    Poll::Pending
165                }
166            }
167        })
168    }
169
170    fn poll_changed(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll<T> {
171        self.mutex.lock(|state| {
172            let mut s = state.borrow_mut();
173            match (&s.data, s.current_id > *id) {
174                (Some(data), true) => {
175                    *id = s.current_id;
176                    Poll::Ready(data.clone())
177                }
178                _ => {
179                    s.wakers.register(cx.waker());
180                    Poll::Pending
181                }
182            }
183        })
184    }
185
186    fn try_changed(&self, id: &mut u64) -> Option<T> {
187        self.mutex.lock(|state| {
188            let s = state.borrow();
189            match s.current_id > *id {
190                true => {
191                    *id = s.current_id;
192                    s.data.clone()
193                }
194                false => None,
195            }
196        })
197    }
198
199    fn poll_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll<T> {
200        self.mutex.lock(|state| {
201            let mut s = state.borrow_mut();
202            match (&s.data, s.current_id > *id) {
203                (Some(data), true) if f(data) => {
204                    *id = s.current_id;
205                    Poll::Ready(data.clone())
206                }
207                _ => {
208                    s.wakers.register(cx.waker());
209                    Poll::Pending
210                }
211            }
212        })
213    }
214
215    fn try_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool) -> Option<T> {
216        self.mutex.lock(|state| {
217            let s = state.borrow();
218            match (&s.data, s.current_id > *id) {
219                (Some(data), true) if f(data) => {
220                    *id = s.current_id;
221                    s.data.clone()
222                }
223                _ => None,
224            }
225        })
226    }
227
228    fn drop_receiver(&self) {
229        self.mutex.lock(|state| {
230            let mut s = state.borrow_mut();
231            s.receiver_count -= 1;
232        })
233    }
234
235    fn clear(&self) {
236        self.mutex.lock(|state| {
237            let mut s = state.borrow_mut();
238            s.data = None;
239        })
240    }
241
242    fn send(&self, val: T) {
243        self.mutex.lock(|state| {
244            let mut s = state.borrow_mut();
245            s.data = Some(val);
246            s.current_id += 1;
247            s.wakers.wake();
248        })
249    }
250
251    fn send_modify(&self, f: &mut dyn Fn(&mut Option<T>)) {
252        self.mutex.lock(|state| {
253            let mut s = state.borrow_mut();
254            f(&mut s.data);
255            s.current_id += 1;
256            s.wakers.wake();
257        })
258    }
259
260    fn send_if_modified(&self, f: &mut dyn Fn(&mut Option<T>) -> bool) {
261        self.mutex.lock(|state| {
262            let mut s = state.borrow_mut();
263            if f(&mut s.data) {
264                s.current_id += 1;
265                s.wakers.wake();
266            }
267        })
268    }
269}
270
271impl<M: RawMutex, T: Clone, const N: usize> WatchBehavior<T> for Watch<M, T, N> {
272    fn try_get(&self, id: Option<&mut u64>) -> Option<T> {
273        self.mutex.lock(|state| {
274            let s = state.borrow();
275            if let Some(id) = id {
276                *id = s.current_id;
277            }
278            s.data.clone()
279        })
280    }
281
282    fn try_get_and(&self, id: Option<&mut u64>, f: &mut dyn Fn(&T) -> bool) -> Option<T> {
283        self.mutex.lock(|state| {
284            let s = state.borrow();
285            match s.data {
286                Some(ref data) if f(data) => {
287                    if let Some(id) = id {
288                        *id = s.current_id;
289                    }
290                    Some(data.clone())
291                }
292                _ => None,
293            }
294        })
295    }
296
297    fn contains_value(&self) -> bool {
298        self.mutex.lock(|state| state.borrow().data.is_some())
299    }
300}
301
302impl<M: RawMutex, T: Clone, const N: usize> Watch<M, T, N> {
303    /// Create a new `Watch` channel for `N` receivers.
304    pub const fn new() -> Self {
305        Self {
306            mutex: Mutex::new(RefCell::new(WatchState {
307                data: None,
308                current_id: 0,
309                wakers: MultiWakerRegistration::new(),
310                receiver_count: 0,
311            })),
312        }
313    }
314
315    /// Create a new `Watch` channel with default data.
316    pub const fn new_with(data: T) -> Self {
317        Self {
318            mutex: Mutex::new(RefCell::new(WatchState {
319                data: Some(data),
320                current_id: 0,
321                wakers: MultiWakerRegistration::new(),
322                receiver_count: 0,
323            })),
324        }
325    }
326
327    /// Create a new [`Sender`] for the `Watch`.
328    pub fn sender(&self) -> Sender<'_, M, T, N> {
329        Sender(Snd::new(self))
330    }
331
332    /// Create a new [`DynSender`] for the `Watch`.
333    pub fn dyn_sender(&self) -> DynSender<'_, T> {
334        DynSender(Snd::new(self))
335    }
336
337    /// Try to create a new [`Receiver`] for the `Watch`. If the
338    /// maximum number of receivers has been reached, `None` is returned.
339    pub fn receiver(&self) -> Option<Receiver<'_, M, T, N>> {
340        self.mutex.lock(|state| {
341            let mut s = state.borrow_mut();
342            if s.receiver_count < N {
343                s.receiver_count += 1;
344                Some(Receiver(Rcv::new(self, 0)))
345            } else {
346                None
347            }
348        })
349    }
350
351    /// Try to create a new [`DynReceiver`] for the `Watch`. If the
352    /// maximum number of receivers has been reached, `None` is returned.
353    pub fn dyn_receiver(&self) -> Option<DynReceiver<'_, T>> {
354        self.mutex.lock(|state| {
355            let mut s = state.borrow_mut();
356            if s.receiver_count < N {
357                s.receiver_count += 1;
358                Some(DynReceiver(Rcv::new(self, 0)))
359            } else {
360                None
361            }
362        })
363    }
364
365    /// Try to create a new [`AnonReceiver`] for the `Watch`.
366    pub fn anon_receiver(&self) -> AnonReceiver<'_, M, T, N> {
367        AnonReceiver(AnonRcv::new(self, 0))
368    }
369
370    /// Try to create a new [`DynAnonReceiver`] for the `Watch`.
371    pub fn dyn_anon_receiver(&self) -> DynAnonReceiver<'_, T> {
372        DynAnonReceiver(AnonRcv::new(self, 0))
373    }
374
375    /// Returns the message ID of the latest message sent to the `Watch`.
376    ///
377    /// This counter is monotonic, and is incremented every time a new message is sent.
378    pub fn get_msg_id(&self) -> u64 {
379        self.mutex.lock(|state| state.borrow().current_id)
380    }
381
382    /// Tries to get the value of the `Watch`.
383    pub fn try_get(&self) -> Option<T> {
384        WatchBehavior::try_get(self, None)
385    }
386
387    /// Tries to get the value of the `Watch` if it matches the predicate function `f`.
388    pub fn try_get_and<F>(&self, mut f: F) -> Option<T>
389    where
390        F: Fn(&T) -> bool,
391    {
392        WatchBehavior::try_get_and(self, None, &mut f)
393    }
394}
395
396/// A receiver can `.await` a change in the `Watch` value.
397#[derive(Debug)]
398pub struct Snd<'a, T: Clone, W: WatchBehavior<T> + ?Sized> {
399    watch: &'a W,
400    _phantom: PhantomData<T>,
401}
402
403impl<'a, T: Clone, W: WatchBehavior<T> + ?Sized> Clone for Snd<'a, T, W> {
404    fn clone(&self) -> Self {
405        Self {
406            watch: self.watch,
407            _phantom: PhantomData,
408        }
409    }
410}
411
412impl<'a, T: Clone, W: WatchBehavior<T> + ?Sized> Snd<'a, T, W> {
413    /// Creates a new `Receiver` with a reference to the `Watch`.
414    fn new(watch: &'a W) -> Self {
415        Self {
416            watch,
417            _phantom: PhantomData,
418        }
419    }
420
421    /// Sends a new value to the `Watch`.
422    pub fn send(&self, val: T) {
423        self.watch.send(val)
424    }
425
426    /// Clears the value of the `Watch`.
427    /// This will cause calls to [`Rcv::get`] to be pending.
428    pub fn clear(&self) {
429        self.watch.clear()
430    }
431
432    /// Tries to retrieve the value of the `Watch`.
433    pub fn try_get(&self) -> Option<T> {
434        self.watch.try_get(None)
435    }
436
437    /// Tries to peek the current value of the `Watch` if it matches the predicate
438    /// function `f`.
439    pub fn try_get_and<F>(&self, mut f: F) -> Option<T>
440    where
441        F: Fn(&T) -> bool,
442    {
443        self.watch.try_get_and(None, &mut f)
444    }
445
446    /// Returns true if the `Watch` contains a value.
447    pub fn contains_value(&self) -> bool {
448        self.watch.contains_value()
449    }
450
451    /// Modify the value of the `Watch` using a closure.
452    pub fn send_modify<F>(&self, mut f: F)
453    where
454        F: Fn(&mut Option<T>),
455    {
456        self.watch.send_modify(&mut f)
457    }
458
459    /// Modify the value of the `Watch` using a closure. The closure must return
460    /// `true` if the value was modified, which notifies all receivers.
461    pub fn send_if_modified<F>(&self, mut f: F)
462    where
463        F: Fn(&mut Option<T>) -> bool,
464    {
465        self.watch.send_if_modified(&mut f)
466    }
467}
468
469/// A sender of a `Watch` channel.
470///
471/// For a simpler type definition, consider [`DynSender`] at the expense of
472/// some runtime performance due to dynamic dispatch.
473#[derive(Debug)]
474pub struct Sender<'a, M: RawMutex, T: Clone, const N: usize>(Snd<'a, T, Watch<M, T, N>>);
475
476impl<'a, M: RawMutex, T: Clone, const N: usize> Clone for Sender<'a, M, T, N> {
477    fn clone(&self) -> Self {
478        Self(self.0.clone())
479    }
480}
481
482impl<'a, M: RawMutex, T: Clone, const N: usize> Sender<'a, M, T, N> {
483    /// Converts the `Sender` into a [`DynSender`].
484    pub fn as_dyn(self) -> DynSender<'a, T> {
485        DynSender(Snd::new(self.watch))
486    }
487}
488
489impl<'a, M: RawMutex, T: Clone, const N: usize> Into<DynSender<'a, T>> for Sender<'a, M, T, N> {
490    fn into(self) -> DynSender<'a, T> {
491        self.as_dyn()
492    }
493}
494
495impl<'a, M: RawMutex, T: Clone, const N: usize> Deref for Sender<'a, M, T, N> {
496    type Target = Snd<'a, T, Watch<M, T, N>>;
497
498    fn deref(&self) -> &Self::Target {
499        &self.0
500    }
501}
502
503impl<'a, M: RawMutex, T: Clone, const N: usize> DerefMut for Sender<'a, M, T, N> {
504    fn deref_mut(&mut self) -> &mut Self::Target {
505        &mut self.0
506    }
507}
508
509/// A sender which holds a **dynamic** reference to a `Watch` channel.
510///
511/// This is an alternative to [`Sender`] with a simpler type definition,
512pub struct DynSender<'a, T: Clone>(Snd<'a, T, dyn WatchBehavior<T> + 'a>);
513
514impl<'a, T: Clone> Clone for DynSender<'a, T> {
515    fn clone(&self) -> Self {
516        Self(self.0.clone())
517    }
518}
519
520impl<'a, T: Clone> Deref for DynSender<'a, T> {
521    type Target = Snd<'a, T, dyn WatchBehavior<T> + 'a>;
522
523    fn deref(&self) -> &Self::Target {
524        &self.0
525    }
526}
527
528impl<'a, T: Clone> DerefMut for DynSender<'a, T> {
529    fn deref_mut(&mut self) -> &mut Self::Target {
530        &mut self.0
531    }
532}
533
534/// A receiver can `.await` a change in the `Watch` value.
535pub struct Rcv<'a, T: Clone, W: WatchBehavior<T> + ?Sized> {
536    watch: &'a W,
537    at_id: u64,
538    _phantom: PhantomData<T>,
539}
540
541impl<'a, T: Clone, W: WatchBehavior<T> + ?Sized> Rcv<'a, T, W> {
542    /// Creates a new `Receiver` with a reference to the `Watch`.
543    fn new(watch: &'a W, at_id: u64) -> Self {
544        Self {
545            watch,
546            at_id,
547            _phantom: PhantomData,
548        }
549    }
550
551    /// Returns the current value of the `Watch` once it is initialized, marking it as seen.
552    ///
553    /// **Note**: Futures do nothing unless you `.await` or poll them.
554    pub fn get(&mut self) -> impl Future<Output = T> + '_ {
555        poll_fn(|cx| self.watch.poll_get(&mut self.at_id, cx))
556    }
557
558    /// Tries to get the current value of the `Watch` without waiting, marking it as seen.
559    pub fn try_get(&mut self) -> Option<T> {
560        self.watch.try_get(Some(&mut self.at_id))
561    }
562
563    /// Returns the value of the `Watch` if it matches the predicate function `f`,
564    /// or waits for it to match, marking it as seen.
565    ///
566    /// **Note**: Futures do nothing unless you `.await` or poll them.
567    pub async fn get_and<F>(&mut self, mut f: F) -> T
568    where
569        F: Fn(&T) -> bool,
570    {
571        poll_fn(|cx| self.watch.poll_get_and(&mut self.at_id, &mut f, cx)).await
572    }
573
574    /// Tries to get the current value of the `Watch` if it matches the predicate
575    /// function `f` without waiting, marking it as seen.
576    pub fn try_get_and<F>(&mut self, mut f: F) -> Option<T>
577    where
578        F: Fn(&T) -> bool,
579    {
580        self.watch.try_get_and(Some(&mut self.at_id), &mut f)
581    }
582
583    /// Waits for the `Watch` to change and returns the new value, marking it as seen.
584    ///
585    /// **Note**: Futures do nothing unless you `.await` or poll them.
586    pub async fn changed(&mut self) -> T {
587        poll_fn(|cx| self.watch.poll_changed(&mut self.at_id, cx)).await
588    }
589
590    /// Poll the `Watch` for a changed value, marking it as seen.
591    pub fn poll_changed(&mut self, cx: &mut Context<'_>) -> Poll<T> {
592        self.watch.poll_changed(&mut self.at_id, cx)
593    }
594
595    /// Tries to get the new value of the watch without waiting, marking it as seen.
596    pub fn try_changed(&mut self) -> Option<T> {
597        self.watch.try_changed(&mut self.at_id)
598    }
599
600    /// Waits for the `Watch` to change to a value which satisfies the predicate
601    /// function `f` and returns the new value, marking it as seen.
602    ///
603    /// **Note**: Futures do nothing unless you `.await` or poll them.
604    pub async fn changed_and<F>(&mut self, mut f: F) -> T
605    where
606        F: Fn(&T) -> bool,
607    {
608        poll_fn(|cx| self.watch.poll_changed_and(&mut self.at_id, &mut f, cx)).await
609    }
610
611    /// Tries to get the new value of the watch which satisfies the predicate
612    /// function `f` and returns the new value without waiting, marking it as seen.
613    pub fn try_changed_and<F>(&mut self, mut f: F) -> Option<T>
614    where
615        F: Fn(&T) -> bool,
616    {
617        self.watch.try_changed_and(&mut self.at_id, &mut f)
618    }
619
620    /// Checks if the `Watch` contains a value. If this returns true,
621    /// then awaiting [`Rcv::get`] will return immediately.
622    pub fn contains_value(&self) -> bool {
623        self.watch.contains_value()
624    }
625}
626
627impl<'a, T: Clone, W: WatchBehavior<T> + ?Sized> Drop for Rcv<'a, T, W> {
628    fn drop(&mut self) {
629        self.watch.drop_receiver();
630    }
631}
632
633/// A anonymous receiver can NOT `.await` a change in the `Watch` value.
634#[derive(Debug)]
635pub struct AnonRcv<'a, T: Clone, W: WatchBehavior<T> + ?Sized> {
636    watch: &'a W,
637    at_id: u64,
638    _phantom: PhantomData<T>,
639}
640
641impl<'a, T: Clone, W: WatchBehavior<T> + ?Sized> AnonRcv<'a, T, W> {
642    /// Creates a new `Receiver` with a reference to the `Watch`.
643    fn new(watch: &'a W, at_id: u64) -> Self {
644        Self {
645            watch,
646            at_id,
647            _phantom: PhantomData,
648        }
649    }
650
651    /// Tries to get the current value of the `Watch` without waiting, marking it as seen.
652    pub fn try_get(&mut self) -> Option<T> {
653        self.watch.try_get(Some(&mut self.at_id))
654    }
655
656    /// Tries to get the current value of the `Watch` if it matches the predicate
657    /// function `f` without waiting, marking it as seen.
658    pub fn try_get_and<F>(&mut self, mut f: F) -> Option<T>
659    where
660        F: Fn(&T) -> bool,
661    {
662        self.watch.try_get_and(Some(&mut self.at_id), &mut f)
663    }
664
665    /// Tries to get the new value of the watch without waiting, marking it as seen.
666    pub fn try_changed(&mut self) -> Option<T> {
667        self.watch.try_changed(&mut self.at_id)
668    }
669
670    /// Tries to get the new value of the watch which satisfies the predicate
671    /// function `f` and returns the new value without waiting, marking it as seen.
672    pub fn try_changed_and<F>(&mut self, mut f: F) -> Option<T>
673    where
674        F: Fn(&T) -> bool,
675    {
676        self.watch.try_changed_and(&mut self.at_id, &mut f)
677    }
678
679    /// Checks if the `Watch` contains a value. If this returns true,
680    /// then awaiting [`Rcv::get`] will return immediately.
681    pub fn contains_value(&self) -> bool {
682        self.watch.contains_value()
683    }
684}
685
686/// A receiver of a `Watch` channel.
687pub struct Receiver<'a, M: RawMutex, T: Clone, const N: usize>(Rcv<'a, T, Watch<M, T, N>>);
688
689impl<'a, M: RawMutex, T: Clone, const N: usize> Receiver<'a, M, T, N> {
690    /// Converts the `Receiver` into a [`DynReceiver`].
691    pub fn as_dyn(self) -> DynReceiver<'a, T> {
692        let rcv = DynReceiver(Rcv::new(self.0.watch, self.at_id));
693        core::mem::forget(self); // Ensures the destructor is not called
694        rcv
695    }
696}
697
698impl<'a, M: RawMutex, T: Clone, const N: usize> Into<DynReceiver<'a, T>> for Receiver<'a, M, T, N> {
699    fn into(self) -> DynReceiver<'a, T> {
700        self.as_dyn()
701    }
702}
703
704impl<'a, M: RawMutex, T: Clone, const N: usize> Deref for Receiver<'a, M, T, N> {
705    type Target = Rcv<'a, T, Watch<M, T, N>>;
706
707    fn deref(&self) -> &Self::Target {
708        &self.0
709    }
710}
711
712impl<'a, M: RawMutex, T: Clone, const N: usize> DerefMut for Receiver<'a, M, T, N> {
713    fn deref_mut(&mut self) -> &mut Self::Target {
714        &mut self.0
715    }
716}
717
718/// A receiver which holds a **dynamic** reference to a `Watch` channel.
719///
720/// This is an alternative to [`Receiver`] with a simpler type definition, at the expense of
721/// some runtime performance due to dynamic dispatch.
722pub struct DynReceiver<'a, T: Clone>(Rcv<'a, T, dyn WatchBehavior<T> + 'a>);
723
724impl<'a, T: Clone> Deref for DynReceiver<'a, T> {
725    type Target = Rcv<'a, T, dyn WatchBehavior<T> + 'a>;
726
727    fn deref(&self) -> &Self::Target {
728        &self.0
729    }
730}
731
732impl<'a, T: Clone> DerefMut for DynReceiver<'a, T> {
733    fn deref_mut(&mut self) -> &mut Self::Target {
734        &mut self.0
735    }
736}
737
738/// A receiver of a `Watch` channel that cannot `.await` values.
739#[derive(Debug)]
740pub struct AnonReceiver<'a, M: RawMutex, T: Clone, const N: usize>(AnonRcv<'a, T, Watch<M, T, N>>);
741
742impl<'a, M: RawMutex, T: Clone, const N: usize> AnonReceiver<'a, M, T, N> {
743    /// Converts the `Receiver` into a [`DynReceiver`].
744    pub fn as_dyn(self) -> DynAnonReceiver<'a, T> {
745        let rcv = DynAnonReceiver(AnonRcv::new(self.0.watch, self.at_id));
746        core::mem::forget(self); // Ensures the destructor is not called
747        rcv
748    }
749}
750
751impl<'a, M: RawMutex, T: Clone, const N: usize> Into<DynAnonReceiver<'a, T>> for AnonReceiver<'a, M, T, N> {
752    fn into(self) -> DynAnonReceiver<'a, T> {
753        self.as_dyn()
754    }
755}
756
757impl<'a, M: RawMutex, T: Clone, const N: usize> Deref for AnonReceiver<'a, M, T, N> {
758    type Target = AnonRcv<'a, T, Watch<M, T, N>>;
759
760    fn deref(&self) -> &Self::Target {
761        &self.0
762    }
763}
764
765impl<'a, M: RawMutex, T: Clone, const N: usize> DerefMut for AnonReceiver<'a, M, T, N> {
766    fn deref_mut(&mut self) -> &mut Self::Target {
767        &mut self.0
768    }
769}
770
771/// A receiver that cannot `.await` value, which holds a **dynamic** reference to a `Watch` channel.
772///
773/// This is an alternative to [`AnonReceiver`] with a simpler type definition, at the expense of
774/// some runtime performance due to dynamic dispatch.
775pub struct DynAnonReceiver<'a, T: Clone>(AnonRcv<'a, T, dyn WatchBehavior<T> + 'a>);
776
777impl<'a, T: Clone> Deref for DynAnonReceiver<'a, T> {
778    type Target = AnonRcv<'a, T, dyn WatchBehavior<T> + 'a>;
779
780    fn deref(&self) -> &Self::Target {
781        &self.0
782    }
783}
784
785impl<'a, T: Clone> DerefMut for DynAnonReceiver<'a, T> {
786    fn deref_mut(&mut self) -> &mut Self::Target {
787        &mut self.0
788    }
789}
790
791#[cfg(test)]
792mod tests {
793    use futures_executor::block_on;
794
795    use super::Watch;
796    use crate::blocking_mutex::raw::CriticalSectionRawMutex;
797
798    #[test]
799    fn multiple_sends() {
800        let f = async {
801            static WATCH: Watch<CriticalSectionRawMutex, u8, 1> = Watch::new();
802
803            // Obtain receiver and sender
804            let mut rcv = WATCH.receiver().unwrap();
805            let snd = WATCH.sender();
806
807            // Not initialized
808            assert_eq!(rcv.try_changed(), None);
809
810            // Receive the new value
811            snd.send(10);
812            assert_eq!(rcv.changed().await, 10);
813
814            // Receive another value
815            snd.send(20);
816            assert_eq!(rcv.try_changed(), Some(20));
817
818            // No update
819            assert_eq!(rcv.try_changed(), None);
820        };
821        block_on(f);
822    }
823
824    #[test]
825    fn all_try_get() {
826        let f = async {
827            static WATCH: Watch<CriticalSectionRawMutex, u8, 1> = Watch::new();
828
829            // Obtain receiver and sender
830            let mut rcv = WATCH.receiver().unwrap();
831            let snd = WATCH.sender();
832
833            // Not initialized
834            assert_eq!(WATCH.try_get(), None);
835            assert_eq!(rcv.try_get(), None);
836            assert_eq!(snd.try_get(), None);
837
838            // Receive the new value
839            snd.send(10);
840            assert_eq!(WATCH.try_get(), Some(10));
841            assert_eq!(rcv.try_get(), Some(10));
842            assert_eq!(snd.try_get(), Some(10));
843
844            assert_eq!(WATCH.try_get_and(|x| x > &5), Some(10));
845            assert_eq!(rcv.try_get_and(|x| x > &5), Some(10));
846            assert_eq!(snd.try_get_and(|x| x > &5), Some(10));
847
848            assert_eq!(WATCH.try_get_and(|x| x < &5), None);
849            assert_eq!(rcv.try_get_and(|x| x < &5), None);
850            assert_eq!(snd.try_get_and(|x| x < &5), None);
851        };
852        block_on(f);
853    }
854
855    #[test]
856    fn once_lock_like() {
857        let f = async {
858            static CONFIG0: u8 = 10;
859            static CONFIG1: u8 = 20;
860
861            static WATCH: Watch<CriticalSectionRawMutex, &'static u8, 1> = Watch::new();
862
863            // Obtain receiver and sender
864            let mut rcv = WATCH.receiver().unwrap();
865            let snd = WATCH.sender();
866
867            // Not initialized
868            assert_eq!(rcv.try_changed(), None);
869
870            // Receive the new value
871            snd.send(&CONFIG0);
872            let rcv0 = rcv.changed().await;
873            assert_eq!(rcv0, &10);
874
875            // Receive another value
876            snd.send(&CONFIG1);
877            let rcv1 = rcv.try_changed();
878            assert_eq!(rcv1, Some(&20));
879
880            // No update
881            assert_eq!(rcv.try_changed(), None);
882
883            // Ensure similarity with original static
884            assert_eq!(rcv0, &CONFIG0);
885            assert_eq!(rcv1, Some(&CONFIG1));
886        };
887        block_on(f);
888    }
889
890    #[test]
891    fn sender_modify() {
892        let f = async {
893            static WATCH: Watch<CriticalSectionRawMutex, u8, 1> = Watch::new();
894
895            // Obtain receiver and sender
896            let mut rcv = WATCH.receiver().unwrap();
897            let snd = WATCH.sender();
898
899            // Receive the new value
900            snd.send(10);
901            assert_eq!(rcv.try_changed(), Some(10));
902
903            // Modify the value inplace
904            snd.send_modify(|opt| {
905                if let Some(inner) = opt {
906                    *inner += 5;
907                }
908            });
909
910            // Get the modified value
911            assert_eq!(rcv.try_changed(), Some(15));
912            assert_eq!(rcv.try_changed(), None);
913        };
914        block_on(f);
915    }
916
917    #[test]
918    fn predicate_fn() {
919        let f = async {
920            static WATCH: Watch<CriticalSectionRawMutex, u8, 1> = Watch::new();
921
922            // Obtain receiver and sender
923            let mut rcv = WATCH.receiver().unwrap();
924            let snd = WATCH.sender();
925
926            snd.send(15);
927            assert_eq!(rcv.try_get_and(|x| x > &5), Some(15));
928            assert_eq!(rcv.try_get_and(|x| x < &5), None);
929            assert!(rcv.try_changed().is_none());
930
931            snd.send(20);
932            assert_eq!(rcv.try_changed_and(|x| x > &5), Some(20));
933            assert_eq!(rcv.try_changed_and(|x| x > &5), None);
934
935            snd.send(25);
936            assert_eq!(rcv.try_changed_and(|x| x < &5), None);
937            assert_eq!(rcv.try_changed(), Some(25));
938
939            snd.send(30);
940            assert_eq!(rcv.changed_and(|x| x > &5).await, 30);
941            assert_eq!(rcv.get_and(|x| x > &5).await, 30);
942        };
943        block_on(f);
944    }
945
946    #[test]
947    fn receive_after_create() {
948        let f = async {
949            static WATCH: Watch<CriticalSectionRawMutex, u8, 1> = Watch::new();
950
951            // Obtain sender and send value
952            let snd = WATCH.sender();
953            snd.send(10);
954
955            // Obtain receiver and receive value
956            let mut rcv = WATCH.receiver().unwrap();
957            assert_eq!(rcv.try_changed(), Some(10));
958        };
959        block_on(f);
960    }
961
962    #[test]
963    fn max_receivers_drop() {
964        let f = async {
965            static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
966
967            // Try to create 3 receivers (only 2 can exist at once)
968            let rcv0 = WATCH.receiver();
969            let rcv1 = WATCH.receiver();
970            let rcv2 = WATCH.receiver();
971
972            // Ensure the first two are successful and the third is not
973            assert!(rcv0.is_some());
974            assert!(rcv1.is_some());
975            assert!(rcv2.is_none());
976
977            // Drop the first receiver
978            drop(rcv0);
979
980            // Create another receiver and ensure it is successful
981            let rcv3 = WATCH.receiver();
982            assert!(rcv3.is_some());
983        };
984        block_on(f);
985    }
986
987    #[test]
988    fn multiple_receivers() {
989        let f = async {
990            static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
991
992            // Obtain receivers and sender
993            let mut rcv0 = WATCH.receiver().unwrap();
994            let mut rcv1 = WATCH.anon_receiver();
995            let snd = WATCH.sender();
996
997            // No update for both
998            assert_eq!(rcv0.try_changed(), None);
999            assert_eq!(rcv1.try_changed(), None);
1000
1001            // Send a new value
1002            snd.send(0);
1003
1004            // Both receivers receive the new value
1005            assert_eq!(rcv0.try_changed(), Some(0));
1006            assert_eq!(rcv1.try_changed(), Some(0));
1007        };
1008        block_on(f);
1009    }
1010
1011    #[test]
1012    fn clone_senders() {
1013        let f = async {
1014            // Obtain different ways to send
1015            static WATCH: Watch<CriticalSectionRawMutex, u8, 1> = Watch::new();
1016            let snd0 = WATCH.sender();
1017            let snd1 = snd0.clone();
1018
1019            // Obtain Receiver
1020            let mut rcv = WATCH.receiver().unwrap().as_dyn();
1021
1022            // Send a value from first sender
1023            snd0.send(10);
1024            assert_eq!(rcv.try_changed(), Some(10));
1025
1026            // Send a value from second sender
1027            snd1.send(20);
1028            assert_eq!(rcv.try_changed(), Some(20));
1029        };
1030        block_on(f);
1031    }
1032
1033    #[test]
1034    fn use_dynamics() {
1035        let f = async {
1036            static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
1037
1038            // Obtain receiver and sender
1039            let mut anon_rcv = WATCH.dyn_anon_receiver();
1040            let mut dyn_rcv = WATCH.dyn_receiver().unwrap();
1041            let dyn_snd = WATCH.dyn_sender();
1042
1043            // Send a value
1044            dyn_snd.send(10);
1045
1046            // Ensure the dynamic receiver receives the value
1047            assert_eq!(anon_rcv.try_changed(), Some(10));
1048            assert_eq!(dyn_rcv.try_changed(), Some(10));
1049            assert_eq!(dyn_rcv.try_changed(), None);
1050        };
1051        block_on(f);
1052    }
1053
1054    #[test]
1055    fn convert_to_dyn() {
1056        let f = async {
1057            static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
1058
1059            // Obtain receiver and sender
1060            let anon_rcv = WATCH.anon_receiver();
1061            let rcv = WATCH.receiver().unwrap();
1062            let snd = WATCH.sender();
1063
1064            // Convert to dynamic
1065            let mut dyn_anon_rcv = anon_rcv.as_dyn();
1066            let mut dyn_rcv = rcv.as_dyn();
1067            let dyn_snd = snd.as_dyn();
1068
1069            // Send a value
1070            dyn_snd.send(10);
1071
1072            // Ensure the dynamic receiver receives the value
1073            assert_eq!(dyn_anon_rcv.try_changed(), Some(10));
1074            assert_eq!(dyn_rcv.try_changed(), Some(10));
1075            assert_eq!(dyn_rcv.try_changed(), None);
1076        };
1077        block_on(f);
1078    }
1079
1080    #[test]
1081    fn dynamic_receiver_count() {
1082        let f = async {
1083            static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
1084
1085            // Obtain receiver and sender
1086            let rcv0 = WATCH.receiver();
1087            let rcv1 = WATCH.receiver();
1088            let rcv2 = WATCH.receiver();
1089
1090            // Ensure the first two are successful and the third is not
1091            assert!(rcv0.is_some());
1092            assert!(rcv1.is_some());
1093            assert!(rcv2.is_none());
1094
1095            // Convert to dynamic
1096            let dyn_rcv0 = rcv0.unwrap().as_dyn();
1097
1098            // Drop the (now dynamic) receiver
1099            drop(dyn_rcv0);
1100
1101            // Create another receiver and ensure it is successful
1102            let rcv3 = WATCH.receiver();
1103            let rcv4 = WATCH.receiver();
1104            assert!(rcv3.is_some());
1105            assert!(rcv4.is_none());
1106        };
1107        block_on(f);
1108    }
1109
1110    #[test]
1111    fn contains_value() {
1112        let f = async {
1113            static WATCH: Watch<CriticalSectionRawMutex, u8, 2> = Watch::new();
1114
1115            // Obtain receiver and sender
1116            let rcv = WATCH.receiver().unwrap();
1117            let snd = WATCH.sender();
1118
1119            // check if the watch contains a value
1120            assert_eq!(rcv.contains_value(), false);
1121            assert_eq!(snd.contains_value(), false);
1122
1123            // Send a value
1124            snd.send(10);
1125
1126            // check if the watch contains a value
1127            assert_eq!(rcv.contains_value(), true);
1128            assert_eq!(snd.contains_value(), true);
1129        };
1130        block_on(f);
1131    }
1132}