1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#![deny(missing_docs)]

//! Broadcast synchronization sending out to all subscribed receivers.

extern crate crossbeam_channel;
extern crate failure;

mod error;

use crossbeam_channel::{unbounded, Receiver, Sender};
use std::sync::{Arc, RwLock};

pub use error::{Error, ErrorKind};

/// A manager for subscriptions.
/// The manager is bound to a broadcaster and can be used to subscribe to
/// it's broadcast messages. It can be cloned and sent to other threads
/// which also want to subscribe to the broadcast.
#[derive(Clone)]
pub struct SubscriptionManager<T: Clone> {
    sender: Sender<Sender<T>>,
}

/// A broadcaster which sends out broadcasts to all of it's subscribers.
#[derive(Clone)]
pub struct Broadcaster<T: Clone> {
    senders: Arc<RwLock<Vec<Sender<T>>>>,
    inbox: (Sender<Sender<T>>, Receiver<Sender<T>>),
}

impl<T: Clone> Broadcaster<T> {
    /// Create a new broadcaster.
    pub fn new() -> Self {
        Broadcaster {
            senders: Arc::new(RwLock::new(Vec::new())),
            inbox: unbounded(),
        }
    }

    /// Process all pending subscriptions.
    pub fn process_pending_subscriptions(&mut self) {
        self.process_pending_subscriptions_with(&mut |_| {})
    }

    /// Process all pending subscriptions.
    /// This method calls a function on each sender before adding it.
    pub fn process_pending_subscriptions_with<F: FnMut(&mut Sender<T>)>(
        &mut self,
        f: &mut F,
    ) {
        let mut senders = self.senders.write().unwrap();
        while let Ok(mut s) = self.inbox.1.try_recv() {
            f(&mut s);
            senders.push(s);
        }
    }

    /// Broadcast a message to all subscribers.
    pub fn broadcast(&mut self, item: T) {
        self.process_pending_subscriptions();
        let mut senders = self.senders.write().unwrap();
        senders.retain(|sender| sender.send(item.clone()).is_ok());
    }

    /// Get a subscription manager which can be cloned or sent.
    pub fn subscription_manager(&self) -> SubscriptionManager<T> {
        SubscriptionManager {
            sender: self.inbox.0.clone(),
        }
    }
}

impl<T: Clone> SubscriptionRegistration<T> for SubscriptionManager<T> {
    fn subscribe_with<F: FnMut(&mut Sender<T>)>(
        &self,
        f: &mut F,
    ) -> Result<Receiver<T>, Error> {
        self.sender.subscribe_with(f)
    }
}

impl<T: Clone> SubscriptionRegistration<T> for Sender<Sender<T>> {
    fn subscribe_with<F: FnMut(&mut Sender<T>)>(
        &self,
        f: &mut F,
    ) -> Result<Receiver<T>, Error> {
        let (mut sender, receiver) = unbounded();
        self.send(sender.clone()).map_err(|_| {
            Error::from(ErrorKind::BroadcasterNoLongerExists)
        })?;
        f(&mut sender);
        Ok(receiver)
    }
}

impl<T: Clone> SubscriptionRegistration<T> for Broadcaster<T> {
    fn subscribe_with<F: FnMut(&mut Sender<T>)>(
        &self,
        f: &mut F,
    ) -> Result<Receiver<T>, Error> {
        self.inbox.0.subscribe_with(f)
    }
}

/// A trait for subscribing to a broadcaster.
pub trait SubscriptionRegistration<T: Clone> {
    /// Subscribe to a broadcaster and return the receiver.
    /// If the associated broadcaster got dropped in the meantime, an
    /// error gets returned.
    fn subscribe(&self) -> Result<Receiver<T>, Error> {
        self.subscribe_with(&mut |_| {})
    }

    /// Subscribe to a broadcaster and return the receiver.
    /// Calls a function on the newly created sender.
    /// If the associated broadcaster got dropped in the meantime, an
    /// error gets returned.
    fn subscribe_with<F: FnMut(&mut Sender<T>)>(
        &self,
        f: &mut F,
    ) -> Result<Receiver<T>, Error>;
}