signals2 0.3.3

A thread-safe signal/slot library inspired by boost::signals2
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright Christian Daley 2021
// Copyright Frank Mori Hess 2007-2008.
// Distributed under the Boost Software License, Version 1.0. 
// See http://www.boost.org/LICENSE_1_0.txt

use std::sync::{Arc, Weak, atomic::{AtomicBool, AtomicUsize, Ordering}};

use crate::{Signal, ConnectHandle};
use crate::combiner::Combiner;

/// Represents a position to connect a slot to in a group of slots.
pub enum Position {
    /// A position at the front of a group. A slot connected at `Position::Front` be executed 
    /// *before* all other slots in the group that were present before it was conncted.
    Front,
    /// A position at the back of a group. A slot connected at `Position::Back` be executed 
    /// *after* all other slots in the group that were present before it was conncted.
    Back
}

/// Represents a group to connect a slot to in a signal.
#[derive(Ord, PartialOrd, Eq, PartialEq)]
pub enum Group<G>
where
    G: Ord + Send + Sync
{
    /// The unnamed "front" group. Slots in the "front" group are executed before
    /// slots from named groups and the unnamed "back" group.
    Front,
    /// A named group. Slots in named groups are executed after all slots in the
    /// unnamed "front" group. Individual named groups are executed according the ordering defined by the
    /// [Ord] trait.
    Named(G),
    /// The unnamed "back" group. Slots in the "back" group are executed after
    /// slots from the unnamed "front" group and slots from named groups.
    Back
}

macro_rules! impl_connect {
    ($name:ident; $($args:ident)*; $($params:ident)*) => {

        /// Connect trait for signals with slots that accept the corresponding number of arguments. 
        pub trait $name<R, C, G, $($args),*>
        where 
            ($($args,)*): Clone + 'static,
            R: 'static,
            C: Combiner<R> + 'static,
            G: Ord + Send + Sync
        {
            /// Connects the slot function `f` to the given [Group] at the given [Position]
            fn connect_group_position<F>(&self, f: F, group: Group<G>, pos: Position) -> Connection
            where 
                F: Fn($($args,)*) -> R + Send + Sync + 'static;

            /// Connects the extended slot function `f` to the given [Group] at the given [Position]
            fn connect_group_position_extended<F>(&self, f: F, group: Group<G>, pos: Position) -> Connection
            where 
                F: Fn(Connection, $($args,)*) -> R + Send + Sync + 'static;

            /// Connects the slot function `f` to the given [Group] at [Position::Back]. Equivalent to calling
            /// `connect_group_position(f, group, Position::Back)`.
            fn connect_group<F>(&self, f: F, group: Group<G>) -> Connection
            where 
                F: Fn($($args,)*) -> R + Send + Sync + 'static
            {
                self.connect_group_position(f, group, Position::Back)
            }

            /// Connects the slot function `f` to [Group::Back] at the given position. Equivalent to calling
            /// `connect_group_position(f, Group::Back, pos)`.
            fn connect_position<F>(&self, f: F, pos: Position) -> Connection
            where 
                F: Fn($($args,)*) -> R + Send + Sync + 'static
            {
                self.connect_group_position(f, Group::Back, pos)
            }

            /// Connects the slot function `f` to [Group::Back] at [Position::Back]. Equivalent to calling
            /// `connect_group_position(f, Group::Back, Position::Back)`.
            fn connect<F>(&self, f: F) -> Connection
            where 
                F: Fn($($args,)*) -> R + Send + Sync + 'static
            {
                self.connect_group_position(f, Group::Back, Position::Back)
            }

            /// Connects the extended slot function `f` to the given [Group] at [Position::Back]. Equivalent to calling
            /// `connect_group_position_extended(f, group, Position::Back)`.
            fn connect_group_extended<F>(&self, f: F, group: Group<G>) -> Connection
            where 
                F: Fn(Connection, $($args,)*) -> R + Send + Sync + 'static
            {
                self.connect_group_position_extended(f, group, Position::Back)
            }

            /// Connects the extended slot function `f` to [Group::Back] at the given position. Equivalent to calling
            /// `connect_group_position_extended(f, Group::Back, pos)`.
            fn connect_position_extended<F>(&self, f: F, pos: Position) -> Connection
            where 
                F: Fn(Connection, $($args,)*) -> R + Send + Sync + 'static
            {
                self.connect_group_position_extended(f, Group::Back, pos)
            }

             /// Connects the extended slot function `f` to [Group::Back] at [Position::Back]. Equivalent to calling
            /// `connect_group_position_extended(f, Group::Back, Position::Back)`.
            fn connect_extended<F>(&self, f: F) -> Connection
            where 
                F: Fn(Connection, $($args,)*) -> R + Send + Sync + 'static
            {
                self.connect_group_position_extended(f, Group::Back, Position::Back)
            }
        }

        impl<R, C, G, $($args,)*> $name<R, C, G, $($args,)*> for Signal<($($args,)*), R, C, G> 
        where
            ($($args,)*): Clone + 'static,
            R: 'static,
            C: Combiner<R> + 'static,
            G: Ord + Send + Sync + 'static,
        {
            fn connect_group_position<F>(&self, f: F, group: Group<G>, pos: Position) -> Connection
            where
                F: Fn($($args,)*) -> R + Send + Sync + 'static
            {
                let weak_core = Arc::downgrade(&self.core);

                let cleanup = move || {
                    if let Some(core) = weak_core.upgrade() {
                        let mut lock = core.write().unwrap();
                        let mut core_clone = (**lock).clone();
                        core_clone.cleanup();
                        *lock = Arc::new(core_clone);
                    }
                };

                let make_conn = move |connected, blocker_count| {
                    Connection::new(connected, blocker_count, Arc::new(cleanup))
                };

                let mut lock = self.core.write().unwrap();
                let mut core_clone = (**lock).clone();

                let wrapped_f = move |($($params,)*)| f($($params,)*);
                let conn = core_clone.connect(wrapped_f, group, pos, make_conn);

                *lock = Arc::new(core_clone);
                conn
            }

            fn connect_group_position_extended<F>(&self, f: F, group: Group<G>, pos: Position) -> Connection
            where
                F: Fn(Connection, $($args,)*) -> R + Send + Sync + 'static
            {
                let weak_core = Arc::downgrade(&self.core);

                let cleanup = move || {
                    if let Some(core) = weak_core.upgrade() {
                        let mut lock = core.write().unwrap();
                        let mut core_clone = (**lock).clone();
                        core_clone.cleanup();
                        *lock = Arc::new(core_clone);
                    }
                };

                let make_conn = move |connected, blocker_count| {
                    Connection::new(connected, blocker_count, Arc::new(cleanup))
                };

                let mut lock = self.core.write().unwrap();
                let mut core_clone = (**lock).clone();

                let wrapped_f = move |conn, ($($params,)*)| f(conn, $($params,)*);
                let conn = core_clone.connect_extended(wrapped_f, group, pos, make_conn);

                *lock = Arc::new(core_clone);
                conn
            }
        }

        // Implement Connect traits for COnnectHandle
        impl<R, C, G, $($args,)*> $name<R, C, G, $($args,)*> for ConnectHandle<($($args,)*), R, C, G> 
        where
            ($($args,)*): Clone + 'static,
            R: 'static,
            C: Combiner<R> + 'static,
            G: Ord + Send + Sync + 'static,
        {
            fn connect_group_position<F>(&self, f: F, group: Group<G>, pos: Position) -> Connection
            where
                F: Fn($($args,)*) -> R + Send + Sync + 'static
            {
                self.weak_sig
                    .upgrade()
                    .map(|sig| sig.connect_group_position(f, group, pos))
                    .unwrap_or(Connection::empty())
            }

            fn connect_group_position_extended<F>(&self, f: F, group: Group<G>, pos: Position) -> Connection
            where
                F: Fn(Connection, $($args,)*) -> R + Send + Sync + 'static
            {
                self.weak_sig
                    .upgrade()
                    .map(|sig| sig.connect_group_position_extended(f, group, pos))
                    .unwrap_or(Connection::empty())
            }
        }
    };
}

impl_connect!(Connect0;;);
impl_connect!(Connect1; T0; a);
impl_connect!(Connect2; T0 T1; a b);
impl_connect!(Connect3; T0 T1 T2; a b c);
impl_connect!(Connect4; T0 T1 T2 T3; a b c d);
impl_connect!(Connect5; T0 T1 T2 T3 T4; a b c d e);
impl_connect!(Connect6; T0 T1 T2 T3 T4 T5; a b c d e f);
impl_connect!(Connect7; T0 T1 T2 T3 T4 T5 T6; a b c d e f g);
impl_connect!(Connect8; T0 T1 T2 T3 T4 T5 T6 T7; a b c d e f g h);
impl_connect!(Connect9; T0 T1 T2 T3 T4 T5 T6 T7 T8; a b c d e f g h i);
impl_connect!(Connect10; T0 T1 T2 T3 T4 T5 T6 T7 T8 T9; a b c d e f g h i j);
impl_connect!(Connect11; T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10; a b c d e f g h i j k);
impl_connect!(Connect12; T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11; a b c d e f g h i j k l);

/// The implementation used by both [Connection] and [ScopedConnection].
/// Takes a const bool parameter indicating whether it is a scoped connection or not.
#[derive(Clone)]
pub struct ConnectionImpl<const SCOPED: bool>
{
    weak_connected: Weak<AtomicBool>,
    weak_blocker_count: Weak<AtomicUsize>,
    cleanup: Arc<dyn Fn() -> () + Send + Sync>
}

impl<const SCOPED: bool> ConnectionImpl<SCOPED> {
    fn new(weak_connected: Weak<AtomicBool>, weak_blocker_count: Weak<AtomicUsize>, cleanup: Arc<dyn Fn() -> () + Send + Sync>) -> Self {
        Self {
            weak_connected,
            weak_blocker_count,
            cleanup
        }
    }

    fn empty() -> Self {
        Self {
            weak_connected: Weak::new(),
            weak_blocker_count: Weak::new(),
            cleanup: Arc::new(|| ())
        }
    }

    /// Returns true if the underlying slot is still connected, false otherwise. Will return false 
    /// if the underlying signal no longer exists.
    pub fn connected(&self) -> bool {
        self.weak_connected
            .upgrade()
            .map(|connected| connected.load(Ordering::SeqCst))
            .unwrap_or(false)
    }

    /// Disconnects the underlying slot. Further, repeated calls to `disconnect` will do nothing.
    /// When a connection is disconnected its underlying slot is permanently removed from the the signal's slot list.
    /// Once disconnected, there is no way to re-connect a slot.
    pub fn disconnect(&self) {
        if let Some(connected) = self.weak_connected.upgrade() {
            connected.store(false, Ordering::SeqCst);
            (self.cleanup)();
        }
    }

    /// Returns true if the underlying slot is blocked, false otherwise. Will return true if either the
    /// underyling slot or underlying signal no longer exists.
    pub fn blocked(&self) -> bool {        
        self.weak_blocker_count
            .upgrade()
            .map(|blocker_count| blocker_count.load(Ordering::SeqCst) != 0usize)
            .unwrap_or(true)
    }

    /// Returns the number of [SharedConnectionBlocks](SharedConnectionBlock) currently blocking the slot. 
    /// Will return `usize::Max` if either the underyling slot or underlying signal no longer exists.
    pub fn blocker_count(&self) -> usize {
        self.weak_blocker_count
            .upgrade()
            .map(|blocker_count| blocker_count.load(Ordering::SeqCst))
            .unwrap_or(usize::MAX)
    }

    #[must_use="shared connection blocks are automatically unblocked when dropped"]
    /// Gets a [SharedConnectionBlock] that can be used to temporarily block the underlying slot.
    pub fn shared_block(&self, initially_blocking: bool) -> SharedConnectionBlock {
        SharedConnectionBlock::new(self.weak_blocker_count.clone(), initially_blocking)
    }
}

impl<const SCOPED: bool> Drop for ConnectionImpl<SCOPED> {
    /// Disconnects the connection if and only if the connection is scoped.
    fn drop(&mut self) {
        if SCOPED {
            self.disconnect();
        }
    }
}

impl ConnectionImpl<false> {
    /// Consumes the connection and returns a [ScopedConnection].
    #[must_use="ScopedConnection automatically disconnects when dropped"]
    pub fn scoped(self) -> ScopedConnection {
        ScopedConnection::new(self.weak_connected.clone(), self.weak_blocker_count.clone(), self.cleanup.clone())
    }
}

/// A connection manages one slot for one particular signal. Connections carry no type information about their
/// underlying signal. Connections are created when new slots are connected to a signal.
/// 
/// Note that when a connection is dropped it *will not* automatically disconnect its underlying slot.
/// See [ScopedConnection] for a connection that automatically disconnects when dropped.
///
/// See [ConnectionImpl] for details on the various functions implemented by connections.
/// # Examples 
/// ```
/// use signals2::*;
/// 
/// let sig: Signal<(), i32> = Signal::new();
/// let conn = sig.connect(|| 4);
/// assert_eq!(sig.emit(), Some(4));
/// conn.disconnect(); // disconnect the slot
/// assert_eq!(sig.emit(), None);
/// ```
pub type Connection = ConnectionImpl<false>;


/// Scoped connections are identical to regular connections, except that they will automcatically
/// disconnect themselves when dropped.
///
/// See [ConnectionImpl] for details on the various functions implemented by scoped connections.
/// ```
/// use signals2::*;
/// 
/// let sig: Signal<(), i32> = Signal::new();
/// {
///    let _conn = sig.connect(|| 4).scoped(); // create a scoped connection
///    assert_eq!(sig.emit(), Some(4));
/// }
/// 
/// assert_eq!(sig.emit(), None);
/// ```
pub type ScopedConnection = ConnectionImpl<true>;

/// A shared connection block can be used to temporarily block a slot from executing. There can be an
/// arbitrary number of shared connection blocks for any particular slot. If any of the shared connection blocks
/// are blocking the slot, that slot will not be executed when the signal is emitted.
/// # Examples 
/// ```
/// use signals2::*;
/// 
/// let sig: Signal<(), i32> = Signal::new();
/// let conn = sig.connect(|| 4);
/// assert_eq!(sig.emit(), Some(4));
///
/// let blocker1 = conn.shared_block(true); // blocking
/// let blocker2 = blocker1.clone(); // also blocking, since blocker1 is blocking
///
/// assert_eq!(conn.blocker_count(), 2);
/// assert_eq!(sig.emit(), None); // slot is blocked and will not execute
/// 
/// blocker1.unblock();
/// assert_eq!(conn.blocker_count(), 1);
/// assert_eq!(sig.emit(), None); // slot is still blocked
///
/// blocker2.unblock();
/// assert_eq!(conn.blocker_count(), 0);
/// assert_eq!(sig.emit(), Some(4)); // no more active blockers
/// ```
///  Shared connection blocks automatically unblock themselved when dropped.
/// ```
/// use signals2::*;
/// 
/// let sig: Signal<(), i32> = Signal::new();
/// let conn = sig.connect(|| 4);
/// assert_eq!(sig.emit(), Some(4));
/// {
///    let _blocker = conn.shared_block(true);
///    assert_eq!(conn.blocker_count(), 1);
///    assert_eq!(sig.emit(), None);
/// }
///
/// assert_eq!(conn.blocker_count(), 0);
/// assert_eq!(sig.emit(), Some(4)); // blocker was dropped
/// ```
pub struct SharedConnectionBlock {
    weak_blocker_count: Weak<AtomicUsize>,
    blocking: AtomicBool
}

impl SharedConnectionBlock {
    fn new(weak_blocker_count: Weak<AtomicUsize>, initially_blocking: bool) -> Self {
        let shared_block = Self {
            weak_blocker_count,
            blocking: AtomicBool::new(false)
        };

        if initially_blocking {
            shared_block.block_impl(true);
        }

        shared_block
    }

    /// Causes the `SharedConnectionBlock` to begin blocking, if it isn't already.
    pub fn block(&self) {
        if !self.blocking() {
            self.block_impl(true);
        }
    }

    /// Causes the `SharedConnectionBlock` to stop blocking, if it isn't already.
    pub fn unblock(&self) {
        if self.blocking() {
            self.block_impl(false);
        }
    }

    /// Returns true if the `SharedConnectionBlock` is currently blocking, false otherwise.
    /// If this function returns `true` it is guaranteed that the given slot will not be executed when
    /// the signal is emitted. However, if this function returns `false` it is not guaranteed that the given
    /// slot will be executed when the signal is emitted because there could be other existing blockers for
    /// the slot.
    pub fn blocking(&self) -> bool {
        self.blocking.load(Ordering::SeqCst)
    }

    fn block_impl(&self, block: bool) {
        if let Some(blocker_count) = self.weak_blocker_count.upgrade() {
            if block {
                blocker_count.fetch_add(1, Ordering::SeqCst);
            } else {
                blocker_count.fetch_sub(1, Ordering::SeqCst);
            }
        }

        self.blocking.store(block, Ordering::SeqCst);
    }
}

impl Clone for SharedConnectionBlock {
    /// Creates a copy of the given `SharedConnectionBlock` with the same blocking state.
    fn clone(&self) -> Self {
        SharedConnectionBlock::new(self.weak_blocker_count.clone(), self.blocking())
    }
}

impl Drop for SharedConnectionBlock {
    /// Unblocks the underlying signal, if it sitll exists.
    fn drop(&mut self) {
        self.unblock();
    }
}