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
use indexmap::IndexMap;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::{cell::RefCell, rc::Rc};
use uuid::Uuid;

// ------ SubManager ------

type Subscriptions<Ms> = HashMap<TypeId, IndexMap<Uuid, Subscription<Ms>>>;

#[derive(Default)]
pub struct SubManager<Ms> {
    subs: Rc<RefCell<Subscriptions<Ms>>>,
}

impl<Ms: 'static> SubManager<Ms> {
    pub fn new() -> Self {
        Self {
            subs: Rc::new(RefCell::new(HashMap::new())),
        }
    }

    pub fn subscribe<SubMs: 'static + Clone>(
        &mut self,
        handler: impl FnOnce(SubMs) -> Option<Ms> + Clone + 'static,
    ) {
        self.subscribe_with_priority(handler, 0);
    }

    pub(crate) fn subscribe_with_priority<SubMs: 'static + Clone>(
        &mut self,
        handler: impl FnOnce(SubMs) -> Option<Ms> + Clone + 'static,
        priority: i8,
    ) {
        let sub = Subscription::new_with_priority(handler, priority);
        let (type_id, id) = (sub.type_id, sub.id);

        let mut subs = self.subs.borrow_mut();
        subs.entry(type_id)
            .or_insert_with(IndexMap::new)
            .insert(id, sub);

        subs.entry(type_id).and_modify(|subs_group| {
            subs_group.sort_by(|_, sub_a, _, sub_b| Ord::cmp(&sub_b.priority, &sub_a.priority))
        });
    }

    pub fn subscribe_with_handle<SubMs: 'static + Clone>(
        &mut self,
        handler: impl FnOnce(SubMs) -> Option<Ms> + Clone + 'static,
    ) -> SubHandle {
        let sub = Subscription::new(handler);
        let (type_id, id) = (sub.type_id, sub.id);

        let mut subs = self.subs.borrow_mut();
        subs.entry(type_id)
            .or_insert_with(IndexMap::new)
            .insert(id, sub);

        subs.entry(type_id).and_modify(|subs_group| {
            subs_group.sort_by(|_, sub_a, _, sub_b| Ord::cmp(&sub_b.priority, &sub_a.priority))
        });

        let subs = Rc::clone(&self.subs);
        SubHandle {
            unsubscriber: Box::new(move || {
                subs.borrow_mut()
                    .get_mut(&type_id)
                    .expect("get subscriptions by `type_id`")
                    .remove(&id)
                    .expect("remove subscription");
            }),
        }
    }

    pub fn notify(&self, notification: &Notification) -> Vec<Ms> {
        self.subs
            .borrow()
            .get(&notification.type_id)
            .map(|subscriptions| {
                subscriptions
                    .values()
                    .filter_map(|subscription| (&subscription.handler)(&notification.message))
                    .collect()
            })
            .unwrap_or_default()
    }
}

// ------ SubHandle ------

pub struct SubHandle {
    unsubscriber: Box<dyn Fn()>,
}

impl fmt::Debug for SubHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubHandle")
            .field("unsubscriber", &"Box<dyn Fn()>")
            .finish()
    }
}

impl Drop for SubHandle {
    fn drop(&mut self) {
        (self.unsubscriber)();
    }
}

// ------ Subscription ------

struct Subscription<Ms> {
    type_id: TypeId,
    id: Uuid,
    handler: Box<dyn Fn(&Box<dyn Any>) -> Option<Ms>>,
    priority: i8,
}

impl<Ms: 'static> Subscription<Ms> {
    #[allow(clippy::shadow_unrelated)]
    pub fn new<SubMs: 'static + Clone>(
        handler: impl FnOnce(SubMs) -> Option<Ms> + Clone + 'static,
    ) -> Self {
        Self::new_with_priority(handler, 0)
    }

    #[allow(clippy::shadow_unrelated)]
    pub(crate) fn new_with_priority<SubMs: 'static + Clone>(
        handler: impl FnOnce(SubMs) -> Option<Ms> + Clone + 'static,
        priority: i8,
    ) -> Self {
        // Convert `FnOnce + Clone` to `Fn`.
        let handler = move |sub_msg: SubMs| handler.clone()(sub_msg);

        // Convert `Fn(SubMs)` to `Fn(&Box<dyn Any>)` where `Any` is `SubMs`.
        let handler = move |sub_msg: &Box<dyn Any>| {
            let sub_msg = sub_msg
                .downcast_ref::<SubMs>()
                .expect("downcast to `SubMs`");
            handler(sub_msg.clone())
        };

        Self {
            type_id: TypeId::of::<SubMs>(),
            id: Uuid::new_v4(),
            handler: Box::new(handler),
            priority,
        }
    }
}

// ------ Notification ------

pub struct Notification {
    type_id: TypeId,
    message: Box<dyn Any>,
}

impl Notification {
    pub fn new<SubMs: 'static + Any + Clone>(message: SubMs) -> Self {
        Self {
            type_id: TypeId::of::<SubMs>(),
            message: Box::new(message),
        }
    }
}