Skip to main content

clawless_core/event/
receiver.rs

1use tokio::sync::mpsc;
2
3use super::Event;
4
5/// Receiver handle for the event channel
6///
7/// `EventReceiver` is the consuming end of the event channel. The Presenter holds this handle and
8/// reads events for rendering. Because the underlying channel is multi-producer single-consumer,
9/// there is exactly one `EventReceiver` per channel.
10///
11/// `EventReceiver` is [`Send`] but not [`Sync`], matching the semantics of
12/// [`tokio::sync::mpsc::Receiver`].
13#[derive(Debug)]
14pub struct EventReceiver {
15    /// The half of the Tokio channel that reads events
16    inner: mpsc::Receiver<Event>,
17}
18
19impl EventReceiver {
20    /// Wraps a Tokio receiver in an [`EventReceiver`]
21    ///
22    /// Only [`event_channel`] makes a receiver. Each channel therefore has exactly one
23    /// receiver.
24    ///
25    /// [`event_channel`]: super::event_channel
26    pub(super) fn new(inner: mpsc::Receiver<Event>) -> Self {
27        Self { inner }
28    }
29
30    /// Receives the next event from the channel
31    ///
32    /// Returns `None` when all [`EventSender`]s have been dropped and the channel is empty.
33    ///
34    /// [`EventSender`]: super::EventSender
35    pub async fn recv(&mut self) -> Option<Event> {
36        self.inner.recv().await
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    // An assertion in a test panics by design. A `# Panics` section on every test
43    // would repeat that and give the reader no information.
44    #![allow(clippy::missing_panics_doc)]
45
46    use super::*;
47
48    #[test]
49    fn trait_send() {
50        fn assert_send<T: Send>() {}
51        assert_send::<EventReceiver>();
52    }
53
54    #[test]
55    fn trait_unpin() {
56        fn assert_unpin<T: Unpin>() {}
57        assert_unpin::<EventReceiver>();
58    }
59}