Skip to main content

hazard3_sync/
signal.rs

1//! A synchronization primitive for passing the latest value to a task.
2use core::cell::Cell;
3use core::convert::Infallible;
4use core::future::{Future, poll_fn};
5use core::pin::Pin;
6use core::task::{Context, Poll, Waker};
7
8use crate::blocking_mutex::Mutex;
9use crate::blocking_mutex::raw::RawMutex;
10
11/// Single-slot signaling primitive for a _single_ consumer.
12///
13/// This is similar to a [`Channel`](crate::channel::Channel) with a buffer size of 1, except
14/// "sending" to it (calling [`Signal::signal`]) when full will overwrite the previous value instead
15/// of waiting for the receiver to pop the previous value.
16///
17/// It is useful for sending data between tasks when the receiver only cares about
18/// the latest data, and therefore it's fine to "lose" messages. This is often the case for "state"
19/// updates.
20///
21/// For more advanced use cases, you might want to use [`Channel`](crate::channel::Channel) instead.
22/// For multiple consumers, use [`Watch`](crate::watch::Watch) instead.
23///
24/// Signals are generally declared as `static`s and then borrowed as required.
25///
26/// ```
27/// use hazard3_sync::signal::Signal;
28/// use hazard3_sync::blocking_mutex::raw::CriticalSectionRawMutex;
29///
30/// enum SomeCommand {
31///   On,
32///   Off,
33/// }
34///
35/// static SOME_SIGNAL: Signal<CriticalSectionRawMutex, SomeCommand> = Signal::new();
36/// ```
37pub struct Signal<M, T>
38where
39    M: RawMutex,
40{
41    state: Mutex<M, Cell<State<T>>>,
42}
43
44#[derive(Debug)]
45enum State<T> {
46    None,
47    Waiting(Waker),
48    Signaled(T),
49}
50
51impl<M, T> Signal<M, T>
52where
53    M: RawMutex,
54{
55    /// Create a new `Signal`.
56    pub const fn new() -> Self {
57        Self {
58            state: Mutex::new(Cell::new(State::None)),
59        }
60    }
61}
62
63impl<M, T> Default for Signal<M, T>
64where
65    M: RawMutex,
66{
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72impl<M, T> Signal<M, T>
73where
74    M: RawMutex,
75{
76    /// Mark this Signal as signaled.
77    pub fn signal(&self, val: T) {
78        self.state.lock(|cell| {
79            let state = cell.replace(State::Signaled(val));
80            if let State::Waiting(waker) = state {
81                waker.wake();
82            }
83        })
84    }
85
86    /// Remove the queued value in this `Signal`, if any.
87    pub fn reset(&self) {
88        self.try_take();
89    }
90
91    /// Poll for state changes of this Signal.
92    pub fn poll_wait(&self, cx: &mut Context<'_>) -> Poll<T> {
93        self.state.lock(|cell| {
94            let state = cell.replace(State::None);
95            match state {
96                State::None => {
97                    cell.set(State::Waiting(cx.waker().clone()));
98                    Poll::Pending
99                }
100                State::Waiting(w) if w.will_wake(cx.waker()) => {
101                    cell.set(State::Waiting(w));
102                    Poll::Pending
103                }
104                State::Waiting(w) => {
105                    cell.set(State::Waiting(cx.waker().clone()));
106                    w.wake();
107                    Poll::Pending
108                }
109                State::Signaled(res) => Poll::Ready(res),
110            }
111        })
112    }
113
114    /// Future that completes when this Signal has been signaled, taking the value out of the signal.
115    ///
116    /// The returned Future is cancel-safe. No value will be lost even if it isn't polled to completion.
117    pub fn wait(&self) -> impl Future<Output = T> + '_ {
118        poll_fn(move |cx| self.poll_wait(cx))
119    }
120
121    /// non-blocking method to try and take the signal value.
122    pub fn try_take(&self) -> Option<T> {
123        self.state.lock(|cell| {
124            let state = cell.replace(State::None);
125            match state {
126                State::Signaled(res) => Some(res),
127                state => {
128                    cell.set(state);
129                    None
130                }
131            }
132        })
133    }
134
135    /// non-blocking method to check whether this signal has been signaled. This does not clear the signal.
136    pub fn signaled(&self) -> bool {
137        self.state.lock(|cell| {
138            let state = cell.replace(State::None);
139
140            let res = matches!(state, State::Signaled(_));
141
142            cell.set(state);
143
144            res
145        })
146    }
147}
148
149macro_rules! impl_stream_sink {
150    ($($ref:tt)?) => {
151        impl<M, T> futures_core::Stream for $($ref)? Signal<M, T>
152        where
153            M: RawMutex,
154        {
155            type Item = T;
156
157            fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
158                self.poll_wait(cx).map(Some)
159            }
160        }
161
162        impl<M, T> futures_sink::Sink<T> for $($ref)? Signal<M, T>
163        where
164            M: RawMutex,
165        {
166            type Error = Infallible;
167
168            fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
169                Poll::Ready(Ok(()))
170            }
171
172            fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
173                self.signal(item);
174                Ok(())
175            }
176
177            fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
178                Poll::Ready(Ok(()))
179            }
180
181            fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
182                Poll::Ready(Ok(()))
183            }
184        }
185    };
186}
187
188impl_stream_sink!();
189impl_stream_sink!(&);