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
use crate::HandlerId;
use nohash_hasher::IntMap;
use parking_lot::Mutex;
use smallvec::SmallVec;
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;

mod private {
    /// Internal type unreachable externally
    // This struct is intentionally made `!Sized` with `[()]` such that we have no overlap with
    // `Sized` arguments in specialized versions of `call_simple` implementations below
    #[derive(Debug)]
    pub struct Private([()]);
}

struct Inner<F: Send + Sync + Clone + 'static> {
    handlers: IntMap<usize, F>,
    next_index: usize,
}

/// Data structure that holds `Fn()` event handlers
pub struct Bag<
    F: Send + Sync + Clone + 'static,
    A1: ?Sized = private::Private,
    A2: ?Sized = private::Private,
    A3: ?Sized = private::Private,
    A4: ?Sized = private::Private,
    A5: ?Sized = private::Private,
> {
    inner: Arc<Mutex<Inner<F>>>,
    a1: PhantomData<A1>,
    a2: PhantomData<A2>,
    a3: PhantomData<A3>,
    a4: PhantomData<A4>,
    a5: PhantomData<A5>,
}

impl<F, A1, A2, A3, A4, A5> fmt::Debug for Bag<F, A1, A2, A3, A4, A5>
where
    F: Send + Sync + Clone + 'static,
    A1: ?Sized,
    A2: ?Sized,
    A3: ?Sized,
    A4: ?Sized,
    A5: ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Bag").finish()
    }
}

impl<F, A1, A2, A3, A4, A5> Clone for Bag<F, A1, A2, A3, A4, A5>
where
    F: Send + Sync + Clone + 'static,
    A1: ?Sized,
    A2: ?Sized,
    A3: ?Sized,
    A4: ?Sized,
    A5: ?Sized,
{
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            a1: PhantomData::default(),
            a2: PhantomData::default(),
            a3: PhantomData::default(),
            a4: PhantomData::default(),
            a5: PhantomData::default(),
        }
    }
}

impl<F, A1, A2, A3, A4, A5> Default for Bag<F, A1, A2, A3, A4, A5>
where
    F: Send + Sync + Clone + 'static,
    A1: ?Sized,
    A2: ?Sized,
    A3: ?Sized,
    A4: ?Sized,
    A5: ?Sized,
{
    fn default() -> Self {
        Self {
            inner: Arc::new(Mutex::new(Inner {
                handlers: IntMap::default(),
                next_index: 0,
            })),
            a1: PhantomData::default(),
            a2: PhantomData::default(),
            a3: PhantomData::default(),
            a4: PhantomData::default(),
            a5: PhantomData::default(),
        }
    }
}

impl<F, A1, A2, A3, A4, A5> Bag<F, A1, A2, A3, A4, A5>
where
    F: Send + Sync + Clone + 'static,
    A1: ?Sized,
    A2: ?Sized,
    A3: ?Sized,
    A4: ?Sized,
    A5: ?Sized,
{
    /// Add new event handler to a bag
    pub fn add(&self, callback: F) -> HandlerId {
        let index;

        {
            let mut inner = self.inner.lock();

            index = loop {
                let index = inner.next_index;
                inner.next_index += 1;

                if !inner.handlers.contains_key(&index) {
                    inner.handlers.insert(index, callback);
                    break index;
                }
            }
        }

        HandlerId::new({
            let weak_inner = Arc::downgrade(&self.inner);

            move || {
                if let Some(inner) = weak_inner.upgrade() {
                    inner.lock().handlers.remove(&index);
                }
            }
        })
    }

    /// Call applicator with each handler and keep handlers in the bag
    pub fn call<A>(&self, applicator: A)
    where
        A: Fn(&F),
    {
        // We collect handlers first in order to avoid holding lock while calling handlers
        let handlers = self
            .inner
            .lock()
            .handlers
            .values()
            .cloned()
            .collect::<SmallVec<[F; 2]>>();
        for handler in handlers.iter() {
            applicator(handler);
        }
    }
}

impl<F: Fn() + Send + Sync + ?Sized + 'static> Bag<Arc<F>> {
    /// Call each handler without arguments and keep handlers in the bag
    pub fn call_simple(&self) {
        self.call(|handler| handler())
    }
}

impl<A1, F> Bag<Arc<F>, A1>
where
    A1: Sized,
    F: Fn(&A1) + Send + Sync + ?Sized + 'static,
{
    /// Call each handler without arguments and keep handlers in the bag
    pub fn call_simple(&self, a1: &A1) {
        self.call(|handler| handler(a1))
    }
}

impl<A1, A2, F> Bag<Arc<F>, A1, A2>
where
    A1: Sized,
    A2: Sized,
    F: Fn(&A1, &A2) + Send + Sync + ?Sized + 'static,
{
    /// Call each handler without arguments and keep handlers in the bag
    pub fn call_simple(&self, a1: &A1, a2: &A2) {
        self.call(|handler| handler(a1, a2))
    }
}

impl<A1, A2, A3, F> Bag<Arc<F>, A1, A2, A3>
where
    A1: Sized,
    A2: Sized,
    A3: Sized,
    F: Fn(&A1, &A2, &A3) + Send + Sync + ?Sized + 'static,
{
    /// Call each handler without arguments and keep handlers in the bag
    pub fn call_simple(&self, a1: &A1, a2: &A2, a3: &A3) {
        self.call(|handler| handler(a1, a2, a3))
    }
}

impl<A1, A2, A3, A4, F> Bag<Arc<F>, A1, A2, A3, A4>
where
    A1: Sized,
    A2: Sized,
    A3: Sized,
    A4: Sized,
    F: Fn(&A1, &A2, &A3, &A4) + Send + Sync + ?Sized + 'static,
{
    /// Call each handler without arguments and keep handlers in the bag
    pub fn call_simple(&self, a1: &A1, a2: &A2, a3: &A3, a4: &A4) {
        self.call(|handler| handler(a1, a2, a3, a4))
    }
}

impl<A1, A2, A3, A4, A5, F> Bag<Arc<F>, A1, A2, A3, A4, A5>
where
    A1: Sized,
    A2: Sized,
    A3: Sized,
    A4: Sized,
    A5: Sized,
    F: Fn(&A1, &A2, &A3, &A4, &A5) + Send + Sync + ?Sized + 'static,
{
    /// Call each handler without arguments and keep handlers in the bag
    pub fn call_simple(&self, a1: &A1, a2: &A2, a3: &A3, a4: &A4, a5: &A5) {
        self.call(|handler| handler(a1, a2, a3, a4, a5))
    }
}