Skip to main content

aeth_event/
pubsub.rs

1use crate::core::Handler;
2use futures::lock::Mutex;
3use indexed_bitmap::IndexedBitmap;
4use std::cell::RefCell;
5use std::rc::{Rc, Weak};
6
7struct Registry<E>
8where
9    E: Clone + 'static,
10{
11    id: Rc<RefCell<usize>>,
12    handler: Weak<RefCell<Handler<E>>>,
13}
14
15struct Inner<E>
16where
17    E: Clone + 'static,
18{
19    waiter: Mutex<()>,
20    bitmap: RefCell<IndexedBitmap>,
21    regs: RefCell<Vec<Option<Registry<E>>>>,
22}
23
24impl<E> Inner<E>
25where
26    E: Clone + 'static,
27{
28    fn new() -> Self {
29        Self {
30            waiter: Mutex::new(()),
31            bitmap: RefCell::new(IndexedBitmap::new()),
32            regs: RefCell::new(Vec::new()),
33        }
34    }
35
36    fn deref_handler(r: &Option<Registry<E>>) -> Option<Rc<RefCell<Handler<E>>>> {
37        r.as_ref()?.handler.upgrade()
38    }
39
40    fn index_handler(&self, i: usize) -> Option<Rc<RefCell<Handler<E>>>> {
41        debug_assert!(i < self.regs.borrow().len());
42        Self::deref_handler(&self.regs.borrow()[i])
43    }
44
45    async fn publish_locked(&self, e: E) -> Option<()> {
46        let (min_id, max_id) = {
47            let bitmap = self.bitmap.borrow();
48            (bitmap.lowest_one()?, bitmap.highest_one()?)
49        };
50        let mut i = min_id;
51        while i <= max_id {
52            match self.index_handler(i) {
53                Some(rc) => {
54                    let mut handler = rc.borrow_mut();
55                    let handler_ref: &mut Handler<E> = &mut handler;
56                    let ev = e.clone();
57                    match handler_ref {
58                        Handler::Sync(f) => f(ev),
59                        Handler::Async(f) => f.call_mut_boxed(ev).await,
60                    };
61                    i += 1;
62                }
63                None => {
64                    i = self.bitmap.borrow().next_one(i)?;
65                }
66            }
67        }
68        Some(())
69    }
70
71    fn register_locked(self: &Rc<Self>, h: Handler<E>) -> Ledge<E> {
72        let src = Rc::downgrade(&self);
73        let handler = Rc::new(RefCell::new(h));
74        let mut bitmap = self.bitmap.borrow_mut();
75        let slot = bitmap.lowest_zero();
76        let regs = self.regs.borrow();
77        if slot < regs.len() {
78            assert!(Self::deref_handler(&regs[slot]).is_none());
79        }
80        std::mem::drop(regs);
81        bitmap.bitset(slot, true);
82        let id = Rc::new(RefCell::new(slot));
83        let mut regs = self.regs.borrow_mut();
84        if regs.len() <= slot {
85            regs.resize_with(slot + 1, || None);
86        }
87        regs[slot] = Some(Registry {
88            id: id.clone(),
89            handler: Rc::downgrade(&handler),
90        });
91        Ledge {
92            inner: src,
93            handler: Some(handler),
94            id: Some(id.clone()),
95        }
96    }
97
98    fn compact_locked(&self) {
99        // XXX: Wow, what is this mess! Shouldn't we
100        // just move the tail registry to fill the
101        // cavity? Well, the point here is, let
102        // cavity be i, our notification cursor be
103        // j, and the tail be k, so that i < j < k.
104        // If we move tail regs[k] to the the cavity
105        // regs[i], then we will not notifying regs[k]
106        // since it's behind the cursor j!
107        //
108        // In this way, we will have to split the
109        // destruction of registry into two phases:
110        // In the first phase, the Legde owner drops
111        // and leaves a cavity in regs[i]. In the
112        // second phase, when there's no event in
113        // notification or when the current event
114        // notification is done, we fill the cavities
115        // introduced in the first phase back.
116        let mut bitmap = self.bitmap.borrow_mut();
117        let mut regs = self.regs.borrow_mut();
118        loop {
119            let i = bitmap.lowest_zero();
120            let j = bitmap.highest_one().unwrap_or(0);
121            if i >= j {
122                break;
123            }
124            assert!(j < regs.len());
125            assert!(self.index_handler(i).is_none());
126            assert_eq!(bitmap.bitget(i), false);
127            assert_eq!(bitmap.bitget(j), true);
128            regs[i] = None;
129            let mut mid: Option<Registry<E>> = None;
130            std::mem::swap(&mut regs[j], &mut mid);
131            let mid_ref = mid.as_mut().unwrap();
132            assert!(mid_ref.handler.upgrade().is_some());
133            *mid_ref.id.borrow_mut() = i;
134            std::mem::swap(&mut regs[i], &mut mid);
135            bitmap.bitset(i, true);
136            bitmap.bitset(j, false);
137        }
138        let bitmap_size = bitmap.highest_one().map(|x| x + 1).unwrap_or(0);
139        if bitmap_size >= regs.len() {
140            return;
141        }
142        regs.truncate(bitmap_size);
143        if regs.capacity() >= regs.len() * 2 {
144            regs.shrink_to_fit();
145            bitmap.shrink_to(regs.capacity());
146        }
147    }
148
149    fn evict(&self, id: usize) -> Option<()> {
150        self.bitmap.borrow_mut().bitset(id, false);
151        let _lock = self.waiter.try_lock()?;
152        self.compact_locked();
153        Some(())
154    }
155
156    fn has_subscriber(&self) -> bool {
157        self.bitmap.borrow().lowest_one().is_some()
158    }
159}
160
161/// Event subscription handle.
162///
163/// This object is a ledge for whether the owner is
164/// still interested in this event, and how will the
165/// owner process the event. When the subscriber is
166/// dropped, the handling function will no longer be
167/// called, unless it's being notified.
168pub struct Ledge<E>
169where
170    E: Clone + 'static,
171{
172    inner: Weak<Inner<E>>,
173    handler: Option<Rc<RefCell<Handler<E>>>>,
174    id: Option<Rc<RefCell<usize>>>,
175}
176
177impl<E> Ledge<E>
178where
179    E: Clone + 'static,
180{
181    fn drop_option(&mut self) -> Option<()> {
182        std::mem::drop(self.handler.take());
183        let pub_inner = self.inner.upgrade()?;
184        pub_inner.evict(*self.id.as_ref()?.borrow())
185    }
186}
187
188impl<E> Drop for Ledge<E>
189where
190    E: Clone + 'static,
191{
192    fn drop(&mut self) {
193        self.drop_option();
194    }
195}
196
197impl<E> Default for Ledge<E>
198where
199    E: Clone + 'static,
200{
201    fn default() -> Self {
202        Self {
203            inner: Weak::new(),
204            handler: None,
205            id: None,
206        }
207    }
208}
209
210/// Event publisher handle.
211///
212/// Event publisher is the place for notifying the
213/// underlying publishers when the specific
214/// event occurs.
215///
216/// The caller is free to clone the event publisher,
217/// so that they can be easily distributed.
218#[derive(Clone)]
219pub struct Pub<E>
220where
221    E: Clone + 'static,
222{
223    inner: Rc<Inner<E>>,
224}
225
226impl<E> Pub<E>
227where
228    E: Clone + 'static,
229{
230    pub async fn publish(&self, e: E) {
231        let _lock = self.inner.waiter.lock().await;
232        self.inner.publish_locked(e).await;
233        self.inner.compact_locked();
234    }
235
236    pub async fn take_publish(self, e: E) {
237        self.publish(e).await
238    }
239
240    pub fn has_subscriber(&self) -> bool {
241        self.inner.has_subscriber()
242    }
243}
244
245/// Event subscriber handle.
246///
247/// Event subscriber is the place for registering
248/// the event handlers.
249///
250/// The caller is free to clone the event subscriber,
251/// so that they can be easily distributed.
252#[derive(Clone)]
253pub struct Sub<E>
254where
255    E: Clone + 'static,
256{
257    inner: Weak<Inner<E>>,
258}
259
260impl<E> Sub<E>
261where
262    E: Clone + 'static,
263{
264    #[must_use = "Unregister when Ledge is dropped."]
265    pub async fn try_subscribe(&self, h: Handler<E>) -> Option<Ledge<E>> {
266        let inner = self.inner.upgrade()?;
267        let _lock = inner.waiter.lock().await;
268        Some(inner.register_locked(h))
269    }
270
271    #[must_use = "Unregister when Ledge is dropped."]
272    pub async fn subscribe(&self, h: Handler<E>) -> Ledge<E> {
273        self.try_subscribe(h).await.unwrap_or_default()
274    }
275}
276
277/// Create a publisher and subscriber for the
278/// specified event.
279///
280/// The publisher and subscriber are separate objects
281/// so that they are more dedicated to their roles.
282pub fn new_pubsub<E>() -> (Pub<E>, Sub<E>)
283where
284    E: Clone + 'static,
285{
286    let inner = Rc::new(Inner::new());
287    let inner_weak = Rc::downgrade(&inner);
288    (Pub { inner }, Sub { inner: inner_weak })
289}
290
291#[cfg(test)]
292mod test {
293    use crate::core::Handler;
294    use crate::pubsub::*;
295    use crate::testutil::TestFixture;
296    use anyhow::Result;
297
298    async fn async_test_normal() -> Result<()> {
299        #[derive(Clone)]
300        struct EventSome;
301
302        let (pub_some, sub_some) = new_pubsub::<EventSome>();
303
304        let v1 = Rc::new(RefCell::new(0));
305        let mv1 = v1.clone();
306        let _ledge1 = sub_some
307            .subscribe(Handler::new_sync(move |_| {
308                *mv1.borrow_mut() = 2;
309            }))
310            .await;
311
312        let v2 = Rc::new(RefCell::new(0));
313        let mv2 = v2.clone();
314        let _legde2 = sub_some
315            .subscribe(Handler::new_async(async move |_| {
316                *mv2.borrow_mut() = 3;
317            }))
318            .await;
319
320        // The publisher waits for all handlers to execute, thus
321        // we observe the mutated values after awaiting.
322        pub_some.publish(EventSome).await;
323        assert_eq!(*v1.borrow(), 2);
324        assert_eq!(*v2.borrow(), 3);
325        Ok(())
326    }
327
328    #[test]
329    fn test_normal() {
330        let mut fixture = TestFixture::new();
331
332        fixture
333            .execute(async { async_test_normal().await.unwrap() })
334            .assert_done();
335    }
336}