Skip to main content

hazard3_sync/pubsub/
mod.rs

1//! Implementation of [PubSubChannel], a queue where published messages get received by all subscribers.
2
3#![deny(missing_docs)]
4
5use core::cell::RefCell;
6use core::fmt::Debug;
7use core::task::{Context, Poll};
8
9use heapless::Deque;
10
11use self::publisher::{ImmediatePub, Pub};
12use self::subscriber::Sub;
13use crate::blocking_mutex::Mutex;
14use crate::blocking_mutex::raw::RawMutex;
15use crate::waitqueue::MultiWakerRegistration;
16
17pub mod publisher;
18pub mod subscriber;
19
20pub use publisher::{
21    DynImmediatePublisher, DynPublisher, ImmediatePublisher, Publisher, SendDynImmediatePublisher, SendDynPublisher,
22};
23pub use subscriber::{DynSubscriber, SendDynSubscriber, Subscriber};
24
25/// A broadcast channel implementation where multiple publishers can send messages to multiple subscribers
26///
27/// Any published message can be read by all subscribers.
28/// A publisher can choose how it sends its message.
29///
30/// - With [Pub::publish()] the publisher has to wait until there is space in the internal message queue.
31/// - With [Pub::publish_immediate()] the publisher doesn't await and instead lets the oldest message
32///   in the queue drop if necessary. This will cause any [Subscriber] that missed the message to receive
33///   an error to indicate that it has lagged.
34///
35/// ## Example
36///
37/// ```
38/// # use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
39/// # use hazard3_sync::pubsub::WaitResult;
40/// # use hazard3_sync::pubsub::PubSubChannel;
41/// # use futures_executor::block_on;
42/// # let test = async {
43/// // Create the channel. This can be static as well
44/// let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
45///
46/// // This is a generic subscriber with a direct reference to the channel
47/// let mut sub0 = channel.subscriber().unwrap();
48/// // This is a dynamic subscriber with a dynamic (trait object) reference to the channel
49/// let mut sub1 = channel.dyn_subscriber().unwrap();
50///
51/// let pub0 = channel.publisher().unwrap();
52///
53/// // Publish a message, but wait if the queue is full
54/// pub0.publish(42).await;
55///
56/// // Publish a message, but if the queue is full, just kick out the oldest message.
57/// // This may cause some subscribers to miss a message
58/// pub0.publish_immediate(43);
59///
60/// // Wait for a new message. If the subscriber missed a message, the WaitResult will be a Lag result
61/// assert_eq!(sub0.next_message().await, WaitResult::Message(42));
62/// assert_eq!(sub1.next_message().await, WaitResult::Message(42));
63///
64/// // Wait again, but this time ignore any Lag results
65/// assert_eq!(sub0.next_message_pure().await, 43);
66/// assert_eq!(sub1.next_message_pure().await, 43);
67///
68/// // There's also a polling interface
69/// assert_eq!(sub0.try_next_message(), None);
70/// assert_eq!(sub1.try_next_message(), None);
71/// # };
72/// #
73/// # block_on(test);
74/// ```
75///
76#[derive(Debug)]
77pub struct PubSubChannel<M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> {
78    inner: Mutex<M, RefCell<PubSubState<T, CAP, SUBS, PUBS>>>,
79}
80
81impl<M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize>
82    PubSubChannel<M, T, CAP, SUBS, PUBS>
83{
84    /// Create a new channel
85    pub const fn new() -> Self {
86        Self {
87            inner: Mutex::const_new(M::INIT, RefCell::new(PubSubState::new())),
88        }
89    }
90
91    /// Create a new subscriber. It will only receive messages that are published after its creation.
92    ///
93    /// If there are no subscriber slots left, an error will be returned.
94    pub fn subscriber(&self) -> Result<Subscriber<'_, M, T, CAP, SUBS, PUBS>, Error> {
95        self.inner.lock(|inner| {
96            let mut s = inner.borrow_mut();
97
98            if s.subscriber_count >= SUBS {
99                Err(Error::MaximumSubscribersReached)
100            } else {
101                s.subscriber_count += 1;
102                Ok(Subscriber(Sub::new(s.next_message_id, self)))
103            }
104        })
105    }
106
107    /// Create a new subscriber. It will only receive messages that are published after its creation.
108    ///
109    /// If there are no subscriber slots left, an error will be returned.
110    pub fn dyn_subscriber(&self) -> Result<DynSubscriber<'_, T>, Error> {
111        self.inner.lock(|inner| {
112            let mut s = inner.borrow_mut();
113
114            if s.subscriber_count >= SUBS {
115                Err(Error::MaximumSubscribersReached)
116            } else {
117                s.subscriber_count += 1;
118                Ok(DynSubscriber(Sub::new(s.next_message_id, self)))
119            }
120        })
121    }
122
123    /// Create a new publisher
124    ///
125    /// If there are no publisher slots left, an error will be returned.
126    pub fn publisher(&self) -> Result<Publisher<'_, M, T, CAP, SUBS, PUBS>, Error> {
127        self.inner.lock(|inner| {
128            let mut s = inner.borrow_mut();
129
130            if s.publisher_count >= PUBS {
131                Err(Error::MaximumPublishersReached)
132            } else {
133                s.publisher_count += 1;
134                Ok(Publisher(Pub::new(self)))
135            }
136        })
137    }
138
139    /// Create a new publisher
140    ///
141    /// If there are no publisher slots left, an error will be returned.
142    pub fn dyn_publisher(&self) -> Result<DynPublisher<'_, T>, Error> {
143        self.inner.lock(|inner| {
144            let mut s = inner.borrow_mut();
145
146            if s.publisher_count >= PUBS {
147                Err(Error::MaximumPublishersReached)
148            } else {
149                s.publisher_count += 1;
150                Ok(DynPublisher(Pub::new(self)))
151            }
152        })
153    }
154
155    /// Create a new publisher that can only send immediate messages.
156    /// This kind of publisher does not take up a publisher slot.
157    pub fn immediate_publisher(&self) -> ImmediatePublisher<'_, M, T, CAP, SUBS, PUBS> {
158        ImmediatePublisher(ImmediatePub::new(self))
159    }
160
161    /// Create a new publisher that can only send immediate messages.
162    /// This kind of publisher does not take up a publisher slot.
163    pub fn dyn_immediate_publisher(&self) -> DynImmediatePublisher<'_, T> {
164        DynImmediatePublisher(ImmediatePub::new(self))
165    }
166
167    /// Returns the maximum number of elements the channel can hold.
168    pub const fn capacity(&self) -> usize {
169        CAP
170    }
171
172    /// Returns the free capacity of the channel.
173    ///
174    /// This is equivalent to `capacity() - len()`
175    pub fn free_capacity(&self) -> usize {
176        CAP - self.len()
177    }
178
179    /// Clears all elements in the channel.
180    pub fn clear(&self) {
181        self.inner.lock(|inner| inner.borrow_mut().clear());
182    }
183
184    /// Returns the number of elements currently in the channel.
185    pub fn len(&self) -> usize {
186        self.inner.lock(|inner| inner.borrow().len())
187    }
188
189    /// Returns whether the channel is empty.
190    pub fn is_empty(&self) -> bool {
191        self.inner.lock(|inner| inner.borrow().is_empty())
192    }
193
194    /// Returns whether the channel is full.
195    pub fn is_full(&self) -> bool {
196        self.inner.lock(|inner| inner.borrow().is_full())
197    }
198}
199
200impl<M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> crate::pubsub::PubSubBehavior<T>
201    for PubSubChannel<M, T, CAP, SUBS, PUBS>
202{
203    fn publish_immediate(&self, message: T) {
204        self.inner.lock(|s| {
205            let mut s = s.borrow_mut();
206            s.publish_immediate(message)
207        })
208    }
209
210    fn capacity(&self) -> usize {
211        self.capacity()
212    }
213
214    fn is_full(&self) -> bool {
215        self.is_full()
216    }
217}
218
219impl<M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> SealedPubSubBehavior<T>
220    for PubSubChannel<M, T, CAP, SUBS, PUBS>
221{
222    fn get_message_with_context(&self, next_message_id: &mut u64, cx: Option<&mut Context<'_>>) -> Poll<WaitResult<T>> {
223        self.inner.lock(|s| {
224            let mut s = s.borrow_mut();
225
226            // Check if we can read a message
227            match s.get_message(*next_message_id) {
228                // Yes, so we are done polling
229                Some(WaitResult::Message(message)) => {
230                    *next_message_id += 1;
231                    Poll::Ready(WaitResult::Message(message))
232                }
233                // No, so we need to reregister our waker and sleep again
234                None => {
235                    if let Some(cx) = cx {
236                        s.subscriber_wakers.register(cx.waker());
237                    }
238                    Poll::Pending
239                }
240                // We missed a couple of messages. We must do our internal bookkeeping and return that we lagged
241                Some(WaitResult::Lagged(amount)) => {
242                    *next_message_id += amount;
243                    Poll::Ready(WaitResult::Lagged(amount))
244                }
245            }
246        })
247    }
248
249    fn available(&self, next_message_id: u64) -> u64 {
250        self.inner.lock(|s| s.borrow().next_message_id - next_message_id)
251    }
252
253    fn publish_with_context(&self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), T> {
254        self.inner.lock(|s| {
255            let mut s = s.borrow_mut();
256            // Try to publish the message
257            match s.try_publish(message) {
258                // We did it, we are ready
259                Ok(()) => Ok(()),
260                // The queue is full, so we need to reregister our waker and go to sleep
261                Err(message) => {
262                    if let Some(cx) = cx {
263                        s.publisher_wakers.register(cx.waker());
264                    }
265                    Err(message)
266                }
267            }
268        })
269    }
270
271    fn unregister_subscriber(&self, subscriber_next_message_id: u64) {
272        self.inner.lock(|s| {
273            let mut s = s.borrow_mut();
274            s.unregister_subscriber(subscriber_next_message_id)
275        })
276    }
277
278    fn unregister_publisher(&self) {
279        self.inner.lock(|s| {
280            let mut s = s.borrow_mut();
281            s.unregister_publisher()
282        })
283    }
284
285    fn free_capacity(&self) -> usize {
286        self.free_capacity()
287    }
288
289    fn clear(&self) {
290        self.clear();
291    }
292
293    fn len(&self) -> usize {
294        self.len()
295    }
296
297    fn is_empty(&self) -> bool {
298        self.is_empty()
299    }
300}
301
302/// Internal state for the PubSub channel
303#[derive(Debug)]
304struct PubSubState<T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> {
305    /// The queue contains the last messages that have been published and a countdown of how many subscribers are yet to read it
306    queue: Deque<(T, usize), CAP>,
307    /// Every message has an id.
308    /// Don't worry, we won't run out.
309    /// If a million messages were published every second, then the ID's would run out in about 584942 years.
310    next_message_id: u64,
311    /// Collection of wakers for Subscribers that are waiting.  
312    subscriber_wakers: MultiWakerRegistration<SUBS>,
313    /// Collection of wakers for Publishers that are waiting.  
314    publisher_wakers: MultiWakerRegistration<PUBS>,
315    /// The amount of subscribers that are active
316    subscriber_count: usize,
317    /// The amount of publishers that are active
318    publisher_count: usize,
319}
320
321impl<T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> PubSubState<T, CAP, SUBS, PUBS> {
322    /// Create a new internal channel state
323    const fn new() -> Self {
324        Self {
325            queue: Deque::new(),
326            next_message_id: 0,
327            subscriber_wakers: MultiWakerRegistration::new(),
328            publisher_wakers: MultiWakerRegistration::new(),
329            subscriber_count: 0,
330            publisher_count: 0,
331        }
332    }
333
334    fn try_publish(&mut self, message: T) -> Result<(), T> {
335        if self.subscriber_count == 0 {
336            // We don't need to publish anything because there is no one to receive it
337            return Ok(());
338        }
339
340        if self.queue.is_full() {
341            return Err(message);
342        }
343        // We just did a check for this
344        self.queue.push_back((message, self.subscriber_count)).ok().unwrap();
345
346        self.next_message_id += 1;
347
348        // Wake all of the subscribers
349        self.subscriber_wakers.wake();
350
351        Ok(())
352    }
353
354    fn publish_immediate(&mut self, message: T) {
355        // Make space in the queue if required
356        if self.queue.is_full() {
357            self.queue.pop_front();
358        }
359
360        // This will succeed because we made sure there is space
361        self.try_publish(message).ok().unwrap();
362    }
363
364    fn get_message(&mut self, message_id: u64) -> Option<WaitResult<T>> {
365        let start_id = self.next_message_id - self.queue.len() as u64;
366
367        if message_id < start_id {
368            return Some(WaitResult::Lagged(start_id - message_id));
369        }
370
371        let current_message_index = (message_id - start_id) as usize;
372
373        if current_message_index >= self.queue.len() {
374            return None;
375        }
376
377        // We've checked that the index is valid
378        let queue_item = self.queue.iter_mut().nth(current_message_index).unwrap();
379
380        // We're reading this item, so decrement the counter
381        queue_item.1 -= 1;
382
383        let message = if current_message_index == 0 && queue_item.1 == 0 {
384            let (message, _) = self.queue.pop_front().unwrap();
385            self.publisher_wakers.wake();
386            // Return pop'd message without clone
387            message
388        } else {
389            queue_item.0.clone()
390        };
391
392        Some(WaitResult::Message(message))
393    }
394
395    fn unregister_subscriber(&mut self, subscriber_next_message_id: u64) {
396        self.subscriber_count -= 1;
397
398        // All messages that haven't been read yet by this subscriber must have their counter decremented
399        let start_id = self.next_message_id - self.queue.len() as u64;
400        if subscriber_next_message_id >= start_id {
401            let current_message_index = (subscriber_next_message_id - start_id) as usize;
402            self.queue
403                .iter_mut()
404                .skip(current_message_index)
405                .for_each(|(_, counter)| *counter -= 1);
406
407            let mut wake_publishers = false;
408            while let Some((_, count)) = self.queue.front() {
409                if *count == 0 {
410                    self.queue.pop_front().unwrap();
411                    wake_publishers = true;
412                } else {
413                    break;
414                }
415            }
416
417            if wake_publishers {
418                self.publisher_wakers.wake();
419            }
420        }
421    }
422
423    fn unregister_publisher(&mut self) {
424        self.publisher_count -= 1;
425    }
426
427    fn clear(&mut self) {
428        if self.is_full() {
429            self.publisher_wakers.wake();
430        }
431        self.queue.clear();
432    }
433
434    fn len(&self) -> usize {
435        self.queue.len()
436    }
437
438    fn is_empty(&self) -> bool {
439        self.queue.is_empty()
440    }
441
442    fn is_full(&self) -> bool {
443        self.queue.is_full()
444    }
445}
446
447/// Error type for the [PubSubChannel]
448#[derive(Debug, PartialEq, Eq, Clone, Copy)]
449#[cfg_attr(feature = "defmt", derive(defmt::Format))]
450pub enum Error {
451    /// All subscriber slots are used. To add another subscriber, first another subscriber must be dropped or
452    /// the capacity of the channels must be increased.
453    MaximumSubscribersReached,
454    /// All publisher slots are used. To add another publisher, first another publisher must be dropped or
455    /// the capacity of the channels must be increased.
456    MaximumPublishersReached,
457}
458
459trait SealedPubSubBehavior<T> {
460    /// Try to get a message from the queue with the given message id.
461    ///
462    /// If the message is not yet present and a context is given, then its waker is registered in the subscriber wakers.
463    fn get_message_with_context(&self, next_message_id: &mut u64, cx: Option<&mut Context<'_>>) -> Poll<WaitResult<T>>;
464
465    /// Get the amount of messages that are between the given the next_message_id and the most recent message.
466    /// This is not necessarily the amount of messages a subscriber can still received as it may have lagged.
467    fn available(&self, next_message_id: u64) -> u64;
468
469    /// Try to publish a message to the queue.
470    ///
471    /// If the queue is full and a context is given, then its waker is registered in the publisher wakers.
472    fn publish_with_context(&self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), T>;
473
474    /// Returns the free capacity of the channel.
475    ///
476    /// This is equivalent to `capacity() - len()`
477    fn free_capacity(&self) -> usize;
478
479    /// Clears all elements in the channel.
480    fn clear(&self);
481
482    /// Returns the number of elements currently in the channel.
483    fn len(&self) -> usize;
484
485    /// Returns whether the channel is empty.
486    fn is_empty(&self) -> bool;
487
488    /// Let the channel know that a subscriber has dropped
489    fn unregister_subscriber(&self, subscriber_next_message_id: u64);
490
491    /// Let the channel know that a publisher has dropped
492    fn unregister_publisher(&self);
493}
494
495/// 'Middle level' behaviour of the pubsub channel.
496/// This trait is used so that Sub and Pub can be generic over the channel.
497#[allow(private_bounds)]
498pub trait PubSubBehavior<T>: SealedPubSubBehavior<T> {
499    /// Publish a message immediately
500    fn publish_immediate(&self, message: T);
501
502    /// Returns the maximum number of elements the channel can hold.
503    fn capacity(&self) -> usize;
504
505    /// Returns whether the channel is full.
506    fn is_full(&self) -> bool;
507}
508
509/// The result of the subscriber wait procedure
510#[derive(Debug, Clone, PartialEq, Eq)]
511#[cfg_attr(feature = "defmt", derive(defmt::Format))]
512pub enum WaitResult<T> {
513    /// The subscriber did not receive all messages and lagged by the given amount of messages.
514    /// (This is the amount of messages that were missed)
515    Lagged(u64),
516    /// A message was received
517    Message(T),
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523    use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
524
525    #[test]
526    fn send_dyn_are_send_sync() {
527        fn assert_send<T: Send>() {}
528        fn assert_sync<T: Sync>() {}
529
530        assert_send::<SendDynSubscriber<'_, u32>>();
531        assert_sync::<SendDynSubscriber<'_, u32>>();
532        assert_send::<SendDynPublisher<'_, u32>>();
533        assert_sync::<SendDynPublisher<'_, u32>>();
534        assert_send::<SendDynImmediatePublisher<'_, u32>>();
535        assert_sync::<SendDynImmediatePublisher<'_, u32>>();
536
537        let channel = PubSubChannel::<CriticalSectionRawMutex, u32, 4, 4, 4>::new();
538        let _sub: SendDynSubscriber<'_, u32> = channel.subscriber().unwrap().into();
539        let _pubb: SendDynPublisher<'_, u32> = channel.publisher().unwrap().into();
540        let _imm: SendDynImmediatePublisher<'_, u32> = channel.immediate_publisher().into();
541    }
542
543    #[futures_test::test]
544    async fn dyn_pub_sub_works() {
545        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
546
547        let mut sub0 = channel.dyn_subscriber().unwrap();
548        let mut sub1 = channel.dyn_subscriber().unwrap();
549        let pub0 = channel.dyn_publisher().unwrap();
550
551        pub0.publish(42).await;
552
553        assert_eq!(sub0.next_message().await, WaitResult::Message(42));
554        assert_eq!(sub1.next_message().await, WaitResult::Message(42));
555
556        assert_eq!(sub0.try_next_message(), None);
557        assert_eq!(sub1.try_next_message(), None);
558    }
559
560    #[futures_test::test]
561    async fn all_subscribers_receive() {
562        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
563
564        let mut sub0 = channel.subscriber().unwrap();
565        let mut sub1 = channel.subscriber().unwrap();
566        let pub0 = channel.publisher().unwrap();
567
568        pub0.publish(42).await;
569
570        assert_eq!(sub0.next_message().await, WaitResult::Message(42));
571        assert_eq!(sub1.next_message().await, WaitResult::Message(42));
572
573        assert_eq!(sub0.try_next_message(), None);
574        assert_eq!(sub1.try_next_message(), None);
575    }
576
577    #[futures_test::test]
578    async fn lag_when_queue_full_on_immediate_publish() {
579        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
580
581        let mut sub0 = channel.subscriber().unwrap();
582        let pub0 = channel.publisher().unwrap();
583
584        pub0.publish_immediate(42);
585        pub0.publish_immediate(43);
586        pub0.publish_immediate(44);
587        pub0.publish_immediate(45);
588        pub0.publish_immediate(46);
589        pub0.publish_immediate(47);
590
591        assert_eq!(sub0.try_next_message(), Some(WaitResult::Lagged(2)));
592        assert_eq!(sub0.next_message().await, WaitResult::Message(44));
593        assert_eq!(sub0.next_message().await, WaitResult::Message(45));
594        assert_eq!(sub0.next_message().await, WaitResult::Message(46));
595        assert_eq!(sub0.next_message().await, WaitResult::Message(47));
596        assert_eq!(sub0.try_next_message(), None);
597    }
598
599    #[test]
600    fn limited_subs_and_pubs() {
601        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
602
603        let sub0 = channel.subscriber();
604        let sub1 = channel.subscriber();
605        let sub2 = channel.subscriber();
606        let sub3 = channel.subscriber();
607        let sub4 = channel.subscriber();
608
609        assert!(sub0.is_ok());
610        assert!(sub1.is_ok());
611        assert!(sub2.is_ok());
612        assert!(sub3.is_ok());
613        assert_eq!(sub4.err().unwrap(), Error::MaximumSubscribersReached);
614
615        drop(sub0);
616
617        let sub5 = channel.subscriber();
618        assert!(sub5.is_ok());
619
620        // publishers
621
622        let pub0 = channel.publisher();
623        let pub1 = channel.publisher();
624        let pub2 = channel.publisher();
625        let pub3 = channel.publisher();
626        let pub4 = channel.publisher();
627
628        assert!(pub0.is_ok());
629        assert!(pub1.is_ok());
630        assert!(pub2.is_ok());
631        assert!(pub3.is_ok());
632        assert_eq!(pub4.err().unwrap(), Error::MaximumPublishersReached);
633
634        drop(pub0);
635
636        let pub5 = channel.publisher();
637        assert!(pub5.is_ok());
638    }
639
640    #[test]
641    fn publisher_wait_on_full_queue() {
642        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
643
644        let pub0 = channel.publisher().unwrap();
645
646        // There are no subscribers, so the queue will never be full
647        assert_eq!(pub0.try_publish(0), Ok(()));
648        assert_eq!(pub0.try_publish(0), Ok(()));
649        assert_eq!(pub0.try_publish(0), Ok(()));
650        assert_eq!(pub0.try_publish(0), Ok(()));
651        assert_eq!(pub0.try_publish(0), Ok(()));
652
653        let sub0 = channel.subscriber().unwrap();
654
655        assert_eq!(pub0.try_publish(0), Ok(()));
656        assert_eq!(pub0.try_publish(0), Ok(()));
657        assert_eq!(pub0.try_publish(0), Ok(()));
658        assert_eq!(pub0.try_publish(0), Ok(()));
659        assert!(pub0.is_full());
660        assert_eq!(pub0.try_publish(0), Err(0));
661
662        drop(sub0);
663    }
664
665    #[futures_test::test]
666    async fn correct_available() {
667        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
668
669        let sub0 = channel.subscriber().unwrap();
670        let mut sub1 = channel.subscriber().unwrap();
671        let pub0 = channel.publisher().unwrap();
672
673        assert_eq!(sub0.available(), 0);
674        assert_eq!(sub1.available(), 0);
675
676        pub0.publish(42).await;
677
678        assert_eq!(sub0.available(), 1);
679        assert_eq!(sub1.available(), 1);
680
681        sub1.next_message().await;
682
683        assert_eq!(sub1.available(), 0);
684
685        pub0.publish(42).await;
686
687        assert_eq!(sub0.available(), 2);
688        assert_eq!(sub1.available(), 1);
689    }
690
691    #[futures_test::test]
692    async fn correct_len() {
693        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
694
695        let mut sub0 = channel.subscriber().unwrap();
696        let mut sub1 = channel.subscriber().unwrap();
697        let pub0 = channel.publisher().unwrap();
698
699        assert!(sub0.is_empty());
700        assert!(sub1.is_empty());
701        assert!(pub0.is_empty());
702        assert_eq!(pub0.free_capacity(), 4);
703        assert_eq!(pub0.len(), 0);
704
705        pub0.publish(42).await;
706
707        assert_eq!(pub0.free_capacity(), 3);
708        assert_eq!(pub0.len(), 1);
709
710        pub0.publish(42).await;
711
712        assert_eq!(pub0.free_capacity(), 2);
713        assert_eq!(pub0.len(), 2);
714
715        sub0.next_message().await;
716        sub0.next_message().await;
717
718        assert_eq!(pub0.free_capacity(), 2);
719        assert_eq!(pub0.len(), 2);
720
721        sub1.next_message().await;
722        assert_eq!(pub0.free_capacity(), 3);
723        assert_eq!(pub0.len(), 1);
724
725        sub1.next_message().await;
726        assert_eq!(pub0.free_capacity(), 4);
727        assert_eq!(pub0.len(), 0);
728    }
729
730    #[futures_test::test]
731    async fn empty_channel_when_last_subscriber_is_dropped() {
732        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
733
734        let pub0 = channel.publisher().unwrap();
735        let mut sub0 = channel.subscriber().unwrap();
736        let mut sub1 = channel.subscriber().unwrap();
737
738        assert_eq!(4, pub0.free_capacity());
739
740        pub0.publish(1).await;
741        pub0.publish(2).await;
742
743        assert_eq!(2, channel.free_capacity());
744
745        assert_eq!(1, sub0.try_next_message_pure().unwrap());
746        assert_eq!(2, sub0.try_next_message_pure().unwrap());
747
748        assert_eq!(2, channel.free_capacity());
749
750        drop(sub0);
751
752        assert_eq!(2, channel.free_capacity());
753
754        assert_eq!(1, sub1.try_next_message_pure().unwrap());
755
756        assert_eq!(3, channel.free_capacity());
757
758        drop(sub1);
759
760        assert_eq!(4, channel.free_capacity());
761    }
762
763    struct CloneCallCounter(usize);
764
765    impl Clone for CloneCallCounter {
766        fn clone(&self) -> Self {
767            Self(self.0 + 1)
768        }
769    }
770
771    #[futures_test::test]
772    async fn skip_clone_for_last_message() {
773        let channel = PubSubChannel::<NoopRawMutex, CloneCallCounter, 1, 2, 1>::new();
774        let pub0 = channel.publisher().unwrap();
775        let mut sub0 = channel.subscriber().unwrap();
776        let mut sub1 = channel.subscriber().unwrap();
777
778        pub0.publish(CloneCallCounter(0)).await;
779
780        assert_eq!(1, sub0.try_next_message_pure().unwrap().0);
781        assert_eq!(0, sub1.try_next_message_pure().unwrap().0);
782    }
783
784    #[futures_test::test]
785    async fn publisher_sink() {
786        use futures_util::{SinkExt, StreamExt};
787
788        let channel = PubSubChannel::<NoopRawMutex, u32, 4, 4, 4>::new();
789
790        let mut sub = channel.subscriber().unwrap();
791
792        let publ = channel.publisher().unwrap();
793        let mut sink = publ.sink();
794
795        sink.send(0).await.unwrap();
796        assert_eq!(0, sub.try_next_message_pure().unwrap());
797
798        sink.send(1).await.unwrap();
799        assert_eq!(1, sub.try_next_message_pure().unwrap());
800
801        sink.send_all(&mut futures_util::stream::iter(0..4).map(Ok))
802            .await
803            .unwrap();
804        assert_eq!(0, sub.try_next_message_pure().unwrap());
805        assert_eq!(1, sub.try_next_message_pure().unwrap());
806        assert_eq!(2, sub.try_next_message_pure().unwrap());
807        assert_eq!(3, sub.try_next_message_pure().unwrap());
808    }
809}