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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! An event pubsub utility.
//!
//! Publishers can have multiple subscribers, and subscribers can filter the events
//! they accept.
//!
//! # Example
//!
//! ```
//! # use riddle_common::eventpub::*;
//! #[derive(Clone, Eq, PartialEq, Debug)]
//! enum Message {
//!     Test
//! }
//!
//! fn main() {
//!     // Make a new pub and sub
//!     let publisher: EventPub<Message> = EventPub::new();
//!     let subscriber: EventSub<Message> = EventSub::new();
//!     publisher.attach(&subscriber);
//!
//!     // Send a message through the pub
//!     publisher.dispatch(Message::Test);
//!
//!     // Take the messages from the sub
//!     let messages = subscriber.collect();
//!     assert_eq!(vec![Message::Test], messages);
//! }
//! ```

use std::sync::{Arc, Mutex, RwLock, Weak};

/////////////////////////////////////////////////////////////////////////////
// struct EventQueue
/////////////////////////////////////////////////////////////////////////////

struct EventQueue<T> {
    queue: Mutex<Vec<T>>,
    filter: Box<dyn Fn(&T) -> bool + Sync + Send>,
}

impl<T> EventQueue<T> {
    fn new() -> Self {
        Self::new_with_filter(|_| true)
    }

    fn new_with_filter<F>(filter: F) -> Self
    where
        F: Fn(&T) -> bool + Send + Sync + 'static,
    {
        Self {
            queue: Mutex::new(vec![]),
            filter: Box::new(filter),
        }
    }

    fn deliver(&self, event: T) {
        if (*self.filter)(&event) {
            let mut queue = self.queue.lock().unwrap();
            queue.push(event);
        }
    }

    fn collect(&self) -> Vec<T> {
        let mut queue = self.queue.lock().unwrap();
        let mut res = vec![];
        res.append(&mut queue);
        res
    }
}

/////////////////////////////////////////////////////////////////////////////
// struct EventPub
/////////////////////////////////////////////////////////////////////////////

/// Event publisher which can have multiple subscribers.
///
/// # Example
///
/// ```
/// # use riddle_common::eventpub::*;
/// #[derive(Clone)]
/// enum Message {
///     Test(u32)
/// }
///
/// fn main() {
///     let publisher: EventPub<Message> = EventPub::new();
///
///     // Attach any subscribers
///     // ...
///
///     publisher.dispatch(Message::Test(42));
///     publisher.dispatch(Message::Test(13));
/// }
/// ```
pub struct EventPub<T> {
    subs: RwLock<Vec<Weak<EventQueue<T>>>>,
}

impl<T: Clone> EventPub<T> {
    /// Create a new event publisher.
    ///
    /// The new publisher will have no subscribers, so any message dispatched to it in
    /// this state will be silently dropped.
    pub fn new() -> Self {
        Self {
            subs: RwLock::new(vec![]),
        }
    }

    /// Attach a subscriber to the publisher.
    ///
    /// Any events dispatched after this call will be registered with the subscriber.
    /// The subscriber won't receive any events dispatched before it has been attached.
    ///
    /// The subscriber is detached by dropping the attached [`EventSub`].
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_common::eventpub::*;
    /// # #[derive(Clone)] enum Message { Test(u32) }
    /// # fn main() {
    /// let publisher: EventPub<Message> = EventPub::new();
    /// let subscriber: EventSub<Message> = EventSub::new();
    ///
    /// publisher.attach(&subscriber);
    /// assert_eq!(1, publisher.subscription_count());
    ///
    /// drop(subscriber);
    /// assert_eq!(0, publisher.subscription_count());
    /// # }
    /// ```
    pub fn attach(&self, sub: &EventSub<T>) {
        let mut subs = self.subs.write().unwrap();
        subs.push(Arc::downgrade(&sub.events));
    }

    /// Send an event to all currently registered subscribers.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_common::eventpub::*;
    /// # #[derive(Clone, PartialEq, Eq, Debug)] enum Message { Test(u32) }
    /// # fn main() {
    /// let sub_a: EventSub<Message> = EventSub::new();
    /// let sub_b: EventSub<Message> = EventSub::new();
    /// let publisher: EventPub<Message> = EventPub::new();
    /// publisher.attach(&sub_a);
    /// publisher.attach(&sub_b);
    ///
    /// publisher.dispatch(Message::Test(0));
    ///
    /// assert_eq!(vec![Message::Test(0)], sub_a.collect());
    /// assert_eq!(vec![Message::Test(0)], sub_b.collect());
    /// # }
    /// ```
    pub fn dispatch(&self, event: T) {
        let mut dirty = false;

        for sub in self.subs.read().unwrap().iter() {
            match Weak::upgrade(sub) {
                Some(strong_sub) => strong_sub.deliver(event.clone()),
                None => dirty = true,
            }
        }

        if dirty {
            self.clean()
        }
    }

    /// The current count of attached subscribers.
    pub fn subscription_count(&self) -> u32 {
        self.clean();
        self.subs.read().unwrap().len() as u32
    }

    fn clean(&self) {
        let mut subs = self.subs.write().unwrap();
        subs.retain(|w| Weak::upgrade(w).is_some())
    }
}

impl<T: Clone> Default for EventPub<T> {
    fn default() -> Self {
        Self::new()
    }
}

/////////////////////////////////////////////////////////////////////////////
// struct EventSub
/////////////////////////////////////////////////////////////////////////////

/// An event subscriber which can filter incoming messages.
///
/// # Example
///
/// ```
/// # use riddle_common::eventpub::*;
/// #[derive(Clone)]
/// enum Message {
///     Test(u32)
/// }
///
/// fn main() {
///     let subscriber: EventSub<Message> = EventSub::new();
///
///     // Attach to publisher
///     // ...
///
///     // At a later point consume events
///     let events: Vec<Message> = subscriber.collect();
/// }
/// ```
pub struct EventSub<T> {
    events: Arc<EventQueue<T>>,
}

impl<T> EventSub<T> {
    /// Create a new EventSub which accepts all events
    pub fn new() -> Self {
        Self {
            events: EventQueue::new().into(),
        }
    }

    /// Create a new EventSub which applies a filter on incoming events
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_common::eventpub::*;
    /// # #[derive(Clone, PartialEq, Eq, Debug)] enum Message { Test(u32) }
    /// # fn main() {
    /// // Subscriber only accepts even numbered messages
    /// let subscriber: EventSub<Message> = EventSub::new_with_filter(|Message::Test(v)| {
    ///     v % 2 == 0
    /// });
    ///
    /// let publisher: EventPub<Message> = EventPub::new();
    /// publisher.attach(&subscriber);
    ///
    /// publisher.dispatch(Message::Test(0));
    /// publisher.dispatch(Message::Test(1));
    /// publisher.dispatch(Message::Test(2));
    ///
    /// assert_eq!(vec![Message::Test(0), Message::Test(2)], subscriber.collect());
    /// # }
    /// ```
    pub fn new_with_filter<F>(filter: F) -> Self
    where
        F: Fn(&T) -> bool + Send + Sync + 'static,
    {
        Self {
            events: EventQueue::new_with_filter(filter).into(),
        }
    }

    /// Return all received events and clear the subscribers buffer.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_common::eventpub::*;
    /// # #[derive(Clone, PartialEq, Eq, Debug)] enum Message { Test(u32) }
    /// # fn main() {
    /// let subscriber: EventSub<Message> = EventSub::new();
    /// let publisher: EventPub<Message> = EventPub::new();
    /// publisher.attach(&subscriber);
    ///
    /// publisher.dispatch(Message::Test(0));
    ///
    /// // First collect consumes all pending events
    /// assert_eq!(1, subscriber.collect().len());
    /// // Leaving none for the second collect
    /// assert_eq!(0, subscriber.collect().len());
    /// # }
    /// ```
    pub fn collect(&self) -> Vec<T> {
        self.events.collect()
    }
}

impl<T: Clone> Default for EventSub<T> {
    fn default() -> Self {
        Self::new()
    }
}