Skip to main content

hazard3_sync/pubsub/
subscriber.rs

1//! Implementation of anything directly subscriber related
2
3use core::future::Future;
4use core::marker::PhantomData;
5use core::ops::{Deref, DerefMut};
6use core::pin::Pin;
7use core::task::{Context, Poll};
8
9use super::{PubSubBehavior, PubSubChannel, WaitResult};
10use crate::blocking_mutex::raw::RawMutex;
11
12/// A subscriber to a channel
13#[derive(Debug)]
14pub struct Sub<'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> {
15    /// The message id of the next message we are yet to receive
16    next_message_id: u64,
17    /// The channel we are a subscriber to
18    channel: &'a PSB,
19    _phantom: PhantomData<T>,
20}
21
22impl<'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> Sub<'a, PSB, T> {
23    pub(super) fn new(next_message_id: u64, channel: &'a PSB) -> Self {
24        Self {
25            next_message_id,
26            channel,
27            _phantom: Default::default(),
28        }
29    }
30
31    /// Wait for a published message
32    pub fn next_message<'s>(&'s mut self) -> SubscriberWaitFuture<'s, 'a, PSB, T> {
33        SubscriberWaitFuture { subscriber: self }
34    }
35
36    /// Poll for the next published message, preserving lag results.
37    pub fn poll_next_message(&mut self, cx: &mut Context<'_>) -> Poll<WaitResult<T>> {
38        self.channel
39            .get_message_with_context(&mut self.next_message_id, Some(cx))
40    }
41
42    /// Wait for a published message (ignoring lag results)
43    pub async fn next_message_pure(&mut self) -> T {
44        loop {
45            match self.next_message().await {
46                WaitResult::Lagged(_) => continue,
47                WaitResult::Message(message) => break message,
48            }
49        }
50    }
51
52    /// Try to see if there's a published message we haven't received yet.
53    ///
54    /// This function does not peek. The message is received if there is one.
55    pub fn try_next_message(&mut self) -> Option<WaitResult<T>> {
56        match self.channel.get_message_with_context(&mut self.next_message_id, None) {
57            Poll::Ready(result) => Some(result),
58            Poll::Pending => None,
59        }
60    }
61
62    /// Try to see if there's a published message we haven't received yet (ignoring lag results).
63    ///
64    /// This function does not peek. The message is received if there is one.
65    pub fn try_next_message_pure(&mut self) -> Option<T> {
66        loop {
67            match self.try_next_message() {
68                Some(WaitResult::Lagged(_)) => continue,
69                Some(WaitResult::Message(message)) => break Some(message),
70                None => break None,
71            }
72        }
73    }
74
75    /// The amount of messages this subscriber hasn't received yet. This is like [Self::len] but specifically
76    /// for this subscriber.
77    pub fn available(&self) -> u64 {
78        self.channel.available(self.next_message_id)
79    }
80
81    /// Returns the maximum number of elements the ***channel*** can hold.
82    pub fn capacity(&self) -> usize {
83        self.channel.capacity()
84    }
85
86    /// Returns the free capacity of the ***channel***.
87    ///
88    /// This is equivalent to `capacity() - len()`
89    pub fn free_capacity(&self) -> usize {
90        self.channel.free_capacity()
91    }
92
93    /// Clears all elements in the ***channel***.
94    pub fn clear(&self) {
95        self.channel.clear();
96    }
97
98    /// Returns the number of elements currently in the ***channel***.
99    /// See [Self::available] for how many messages are available for this subscriber.
100    pub fn len(&self) -> usize {
101        self.channel.len()
102    }
103
104    /// Returns whether the ***channel*** is empty.
105    pub fn is_empty(&self) -> bool {
106        self.channel.is_empty()
107    }
108
109    /// Returns whether the ***channel*** is full.
110    pub fn is_full(&self) -> bool {
111        self.channel.is_full()
112    }
113}
114
115impl<'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> Drop for Sub<'a, PSB, T> {
116    fn drop(&mut self) {
117        self.channel.unregister_subscriber(self.next_message_id)
118    }
119}
120
121impl<'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> Unpin for Sub<'a, PSB, T> {}
122
123/// Warning: The stream implementation ignores lag results and returns all messages.
124/// This might miss some messages without you knowing it.
125impl<'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> futures_core::Stream for Sub<'a, PSB, T> {
126    type Item = T;
127
128    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
129        match self
130            .channel
131            .get_message_with_context(&mut self.next_message_id, Some(cx))
132        {
133            Poll::Ready(WaitResult::Message(message)) => Poll::Ready(Some(message)),
134            Poll::Ready(WaitResult::Lagged(_)) => {
135                cx.waker().wake_by_ref();
136                Poll::Pending
137            }
138            Poll::Pending => Poll::Pending,
139        }
140    }
141}
142
143/// A subscriber that holds a dynamic reference to the channel
144pub struct DynSubscriber<'a, T: Clone>(pub(super) Sub<'a, dyn PubSubBehavior<T> + 'a, T>);
145
146impl<'a, T: Clone> Deref for DynSubscriber<'a, T> {
147    type Target = Sub<'a, dyn PubSubBehavior<T> + 'a, T>;
148
149    fn deref(&self) -> &Self::Target {
150        &self.0
151    }
152}
153
154impl<'a, T: Clone> DerefMut for DynSubscriber<'a, T> {
155    fn deref_mut(&mut self) -> &mut Self::Target {
156        &mut self.0
157    }
158}
159
160/// A subscriber that holds a dynamic reference to the channel.
161/// This version can be sent between threads but can only be created if the underlying mutex is Send + Sync.
162pub struct SendDynSubscriber<'a, T: Clone>(pub(super) Sub<'a, dyn PubSubBehavior<T> + 'a, T>);
163
164unsafe impl<'a, T: Clone + Send> Send for SendDynSubscriber<'a, T> {}
165unsafe impl<'a, T: Clone + Send> Sync for SendDynSubscriber<'a, T> {}
166
167impl<'a, T: Clone> Deref for SendDynSubscriber<'a, T> {
168    type Target = Sub<'a, dyn PubSubBehavior<T> + 'a, T>;
169
170    fn deref(&self) -> &Self::Target {
171        &self.0
172    }
173}
174
175impl<'a, T: Clone> DerefMut for SendDynSubscriber<'a, T> {
176    fn deref_mut(&mut self) -> &mut Self::Target {
177        &mut self.0
178    }
179}
180
181impl<'a, M, T, const CAP: usize, const SUBS: usize, const PUBS: usize> From<Subscriber<'a, M, T, CAP, SUBS, PUBS>>
182    for SendDynSubscriber<'a, T>
183where
184    M: RawMutex + Send + Sync,
185    T: Clone,
186{
187    fn from(s: Subscriber<'a, M, T, CAP, SUBS, PUBS>) -> Self {
188        let s = core::mem::ManuallyDrop::new(s);
189        Self(Sub::new(s.0.next_message_id, s.0.channel))
190    }
191}
192
193/// A subscriber that holds a generic reference to the channel
194#[derive(Debug)]
195pub struct Subscriber<'a, M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize>(
196    pub(super) Sub<'a, PubSubChannel<M, T, CAP, SUBS, PUBS>, T>,
197);
198
199impl<'a, M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> Deref
200    for Subscriber<'a, M, T, CAP, SUBS, PUBS>
201{
202    type Target = Sub<'a, PubSubChannel<M, T, CAP, SUBS, PUBS>, T>;
203
204    fn deref(&self) -> &Self::Target {
205        &self.0
206    }
207}
208
209impl<'a, M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> DerefMut
210    for Subscriber<'a, M, T, CAP, SUBS, PUBS>
211{
212    fn deref_mut(&mut self) -> &mut Self::Target {
213        &mut self.0
214    }
215}
216
217/// Future for the subscriber wait action
218#[must_use = "futures do nothing unless you `.await` or poll them"]
219#[derive(Debug)]
220pub struct SubscriberWaitFuture<'s, 'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> {
221    subscriber: &'s mut Sub<'a, PSB, T>,
222}
223
224impl<'s, 'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> Future for SubscriberWaitFuture<'s, 'a, PSB, T> {
225    type Output = WaitResult<T>;
226
227    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
228        self.subscriber
229            .channel
230            .get_message_with_context(&mut self.subscriber.next_message_id, Some(cx))
231    }
232}
233
234impl<'s, 'a, PSB: PubSubBehavior<T> + ?Sized, T: Clone> Unpin for SubscriberWaitFuture<'s, 'a, PSB, T> {}