nosy 0.3.0

Change notification / observation / broadcast channels, with filtering and coalescing. no_std compatible.
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use alloc::sync::Weak;
use alloc::vec::Vec;
use core::fmt;
use core::marker::PhantomData;
use core::sync::atomic::{AtomicBool, Ordering::Relaxed};

#[cfg(doc)]
use alloc::sync::Arc;

use crate::maybe_sync::RwLock;
use crate::{IntoListener, Listen, Listener};

#[cfg(doc)]
use crate::{FromListener, Source, sync};

// -------------------------------------------------------------------------------------------------

#[cfg_attr(not(feature = "std-sync"), allow(rustdoc::broken_intra_doc_links))]
/// Delivers messages to a dynamic set of [`Listener`]s.
///
/// The `Notifier` is usually owned by some entity which emits messages when it changes.
/// [`Listener`]s may be added using the [`Listen`] implementation, and are removed when
/// they report themselves as dead (usually by means of checking a weak reference).
///
/// We recommend that you use the type aliases [`sync::Notifier`][crate::sync::Notifier]
/// or [`unsync::Notifier`][crate::unsync::Notifier], to avoid writing the type parameter
/// `L` outside of special cases.
///
/// # Generic parameters
///
/// * `M` is the type of the messages to be broadcast.
/// * `L` is the type of [`Listener`] accepted,
///   usually a trait object type such as [`sync::DynListener`],
///   or something else which implements [`FromListener`] (though this is not mandatory).
///
/// # Example
///
/// You may use a [`Notifier`] to construct a data structure which reports when specific elements of
/// it have changed, allowing clients to stay in sync with those changes.
///
/// ```
/// use std::collections::{HashMap, hash_map::Entry};
/// use std::hash::Hash;
/// use nosy::Listen as _;
///
/// #[derive(Default)]
/// struct NotifyingMap<K, V> {
///     map: HashMap<K, V>,
///     notifier: nosy::unsync::Notifier<K>,
/// }
///
/// impl<K: Eq + Hash + Copy, V: PartialEq> NotifyingMap<K, V> {
///     fn insert(&mut self, key: K, value: V) {
///         match self.map.entry(key) {
///             Entry::Occupied(mut oe) if *oe.get() == value => {
///                 // Values are equal; don’t change or report a change.
///                 return;
///             }
///             entry => {
///                 entry.insert_entry(value);
///             }   
///         }
///         self.notifier.notify(&key);
///     }
/// }
///
/// impl<K, V> nosy::Listen for NotifyingMap<K, V> {
///     type Msg = K;
///     type Listener = nosy::unsync::DynListener<K>;
///     fn listen_raw(&self, listener: Self::Listener) {
///         self.notifier.listen_raw(listener);
///     }
/// }
///
/// // Example/test of using the map
/// {
///     let log = nosy::Log::new();
///     let mut map = NotifyingMap::default();
///     map.listen(log.listener());
///     
///     map.insert(1, 2);
///     map.insert(3, 4);
///     map.insert(1, 10);
///     map.insert(3, 4);
///     
///     assert_eq!(log.drain(), vec![1, 3, 1]);
/// }
/// ```
pub struct Notifier<M, L> {
    state: RwLock<State<M, L>>,
}

enum State<M, L> {
    Open(RawNotifier<M, L>),
    /// The notifier is unable to send any more messages and does not accept listeners.
    Closed,
}

/// [`Notifier`] but without interior mutability.
///
/// Compared to [`Notifier`],
/// this type requires `&mut` access to add listeners, and therefore does not implement [`Listen`].
/// In exchange, it is always `Send + Sync` if the listener type is, even without thread
/// synchronization features enabled.
///
/// We recommend that you use the type aliases [`sync::RawNotifier`][crate::sync::RawNotifier]
/// or [`unsync::RawNotifier`][crate::unsync::RawNotifier], to avoid writing the type parameter
/// `L` outside of special cases.
///
/// # Generic parameters
///
/// * `M` is the type of the messages to be broadcast.
/// * `L` is the type of [`Listener`] accepted,
///   usually a trait object type such as [`sync::DynListener`],
///   or something else which implements [`FromListener`] (though this is not mandatory).
//---
// Design note: `State` and `close()` is not a part of `RawNotifier` because they would require
// `&mut self` to perform the closure, so there’s no benefit to making them internal.
pub struct RawNotifier<M, L> {
    listeners: Vec<NotifierEntry<L>>,
    _phantom: PhantomData<fn(&M)>,
}

pub(crate) struct NotifierEntry<L> {
    listener: L,
    /// True iff every call to `listener.receive()` has returned true.
    was_alive: AtomicBool,
}

// -------------------------------------------------------------------------------------------------
// Impls for `Notifier` and `RawNotifier` are interleaved because they are so similar.

impl<M, L> Notifier<M, L> {
    /// Constructs a new [`Notifier`] with no listeners.
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: RwLock::new(State::Open(RawNotifier::new())),
        }
    }

    /// Signals that no further messages will be delivered, by dropping all current and future
    /// listeners.
    ///
    /// After calling this, [`Notifier::notify()`] will panic if called.
    ///
    /// This method should be used when a `Notifier` has shared ownership and the remaining owners
    /// (e.g. a [`Source`]) cannot be used to send further messages.
    /// It is not necessary when the `Notifier` itself is dropped.
    pub fn close(&self) {
        *self.state.write() = State::Closed;
    }
}
impl<M, L> RawNotifier<M, L> {
    /// Constructs a new [`RawNotifier`] with no listeners.
    #[must_use]
    pub fn new() -> Self {
        Self {
            listeners: Vec::new(),
            _phantom: PhantomData,
        }
    }

    fn count_approximate(&self) -> usize {
        self.listeners.len()
    }
}

impl<M, L: Listener<M>> Notifier<M, L> {
    /// Returns a [`Listener`] which forwards messages to the listeners registered with
    /// this `Notifier`, provided that it is owned by an [`Arc`].
    ///
    /// This may be used together with [`Listener::filter()`] to forward notifications
    /// of changes in dependencies. Using this operation means that the dependent does not
    /// need to fan out listener registrations to all of its current dependencies.
    ///
    /// ```
    /// use std::sync::Arc;
    #[cfg_attr(
        feature = "std-sync",
        doc = " use nosy::{Listen, sync::Notifier, Log};"
    )]
    #[cfg_attr(
        not(feature = "std-sync"),
        doc = " use nosy::{Listen, unsync::Notifier, Log};"
    )]
    ///
    /// let notifier_1 = Notifier::new();
    /// let notifier_2 = Arc::new(Notifier::new());
    /// let mut log = Log::new();
    /// notifier_1.listen(Notifier::forwarder(Arc::downgrade(&notifier_2)));
    /// notifier_2.listen(log.listener());
    /// # assert_eq!(notifier_1.count(), 1);
    /// # assert_eq!(notifier_2.count(), 1);
    ///
    /// notifier_1.notify(&"a");
    /// assert_eq!(log.drain(), vec!["a"]);
    /// drop(notifier_2);
    /// notifier_1.notify(&"a");
    /// assert!(log.drain().is_empty());
    ///
    /// # assert_eq!(notifier_1.count(), 0);
    /// ```
    #[must_use]
    pub fn forwarder(this: Weak<Self>) -> NotifierForwarder<M, L> {
        NotifierForwarder(this)
    }

    /// Deliver a message to all [`Listener`]s.
    ///
    /// # Panics
    ///
    /// Panics if [`Notifier::close()`] was previously called.
    pub fn notify(&self, message: &M) {
        self.notify_many(core::slice::from_ref(message))
    }

    /// Deliver multiple messages to all [`Listener`]s.
    ///
    /// # Panics
    ///
    /// Panics if [`Notifier::close()`] was previously called.
    pub fn notify_many(&self, messages: &[M]) {
        match &*self.state.read() {
            State::Open(raw) => raw.notify_many(messages),
            State::Closed => panic!("cannot send messages after Notifier::close()"),
        }
    }

    /// Creates a [`Buffer`] which batches messages sent through it.
    /// This may be used as a more convenient interface to [`Notifier::notify_many()`],
    /// at the cost of delaying messages until the buffer is dropped.
    ///
    /// The buffer does not use any heap allocations and will collect up to `CAPACITY` messages
    /// per batch.
    ///
    /// # Example
    ///
    /// ```
    /// use nosy::{Listen as _, unsync::Notifier, Log};
    ///
    /// let notifier: Notifier<&str> = Notifier::new();
    /// let log: Log<&str> = Log::new();
    /// notifier.listen(log.listener());
    ///
    /// let mut buffer = notifier.buffer::<2>();
    ///
    /// // The buffer fills up and sends after two messages.
    /// buffer.push("hello");
    /// assert!(log.drain().is_empty());
    /// buffer.push("and");
    /// assert_eq!(log.drain(), vec!["hello", "and"]);
    ///
    /// // The buffer also sends when it is dropped.
    /// buffer.push("goodbye");
    /// drop(buffer);
    /// assert_eq!(log.drain(), vec!["goodbye"]);
    /// ```
    pub fn buffer<const CAPACITY: usize>(&self) -> Buffer<'_, M, L, CAPACITY> {
        Buffer::new(self)
    }

    /// Computes the exact count of listeners, including asking all current listeners
    /// if they are alive.
    ///
    /// This operation is intended for testing and diagnostic purposes.
    pub fn count(&self) -> usize {
        let mut state = self.state.write();
        state.drop_dead_listeners();
        state.count_approximate()
    }
}
impl<M, L: Listener<M>> RawNotifier<M, L> {
    /// Deliver a message to all [`Listener`]s.
    pub fn notify(&self, message: &M) {
        self.notify_many(core::slice::from_ref(message))
    }

    /// Deliver multiple messages to all [`Listener`]s.
    ///
    /// # Panics
    ///
    /// Panics if [`Notifier::close()`] was previously called.
    pub fn notify_many(&self, messages: &[M]) {
        for NotifierEntry {
            listener,
            was_alive,
        } in self.listeners.iter()
        {
            // Don't load was_alive before sending, because we assume the common case is that
            // a listener implements receive() cheaply when it is dead.
            let alive = listener.receive(messages);

            was_alive.fetch_and(alive, Relaxed);
        }
    }

    /// Creates a [`Buffer`] which batches messages sent through it.
    /// This may be used as a more convenient interface to [`RawNotifier::notify_many()`],
    /// at the cost of delaying messages until the buffer is dropped.
    ///
    /// The buffer does not use any heap allocations and will collect up to `CAPACITY` messages
    /// per batch.
    ///
    /// # Example
    ///
    /// ```
    /// use nosy::{Listen as _, unsync::RawNotifier, Log};
    ///
    /// let mut notifier: RawNotifier<&str> = RawNotifier::new();
    /// let log: Log<&str> = Log::new();
    /// notifier.listen(log.listener());
    ///
    /// let mut buffer = notifier.buffer::<2>();
    ///
    /// // The buffer fills up and sends after two messages.
    /// buffer.push("hello");
    /// assert!(log.drain().is_empty());
    /// buffer.push("and");
    /// assert_eq!(log.drain(), vec!["hello", "and"]);
    ///
    /// // The buffer also sends when it is dropped.
    /// buffer.push("goodbye");
    /// drop(buffer);
    /// assert_eq!(log.drain(), vec!["goodbye"]);
    /// ```
    pub fn buffer<const CAPACITY: usize>(&mut self) -> RawBuffer<'_, M, L, CAPACITY> {
        RawBuffer::new(self)
    }

    /// Add a listener which will receive future messages.
    pub fn listen<L2: IntoListener<L, M>>(&mut self, listener: L2) {
        if !listener.receive(&[]) {
            // skip adding it if it's already dead
            return;
        }

        self.drop_dead_if_full();

        self.listeners.push(NotifierEntry {
            listener: listener.into_listener(),
            was_alive: AtomicBool::new(true),
        });
    }

    /// Identical to [`Self::listen()`] except that it doesn't call `IntoListener::into_listener()`.
    fn listen_raw(&mut self, listener: L) {
        if !listener.receive(&[]) {
            // skip adding it if it's already dead
            return;
        }

        self.drop_dead_if_full();

        self.listeners.push(NotifierEntry {
            listener,
            was_alive: AtomicBool::new(true),
        });
    }

    // TODO: Add Buffer for RawNotifier

    /// Discard all dead listeners.
    ///
    /// This is done automatically as new listeners are added.
    /// Doing this explicitly may be useful to control the timing of deallocation or
    /// to get a more accurate count of alive listeners.
    //---
    // TODO: add doctest?
    #[mutants::skip] // there are many ways to subtly break this
    fn drop_dead_listeners(&mut self) {
        let listeners = &mut self.listeners;
        let mut i = 0;
        while i < listeners.len() {
            let entry = &listeners[i];
            // We must ask the listener, not just consult was_alive, in order to avoid
            // leaking memory if listen() is called repeatedly without any notify().
            // TODO: But we can skip it if the last operation was notify().
            if entry.was_alive.load(Relaxed) && entry.listener.receive(&[]) {
                i += 1;
            } else {
                listeners.swap_remove(i);
            }
        }
    }

    fn drop_dead_if_full(&mut self) {
        let full = self.listeners.len() >= self.listeners.capacity();
        if full {
            self.drop_dead_listeners();
        }
    }

    /// Computes the exact count of listeners, including asking all current listeners
    /// if they are alive.
    ///
    /// This operation is intended for testing and diagnostic purposes.
    #[must_use]
    pub fn count(&self) -> usize {
        self.listeners
            .iter()
            .filter(|entry| entry.was_alive.load(Relaxed) && entry.listener.receive(&[]))
            .count()
    }
}

impl<M, L: Listener<M>> Listen for Notifier<M, L> {
    type Msg = M;
    type Listener = L;

    fn listen_raw(&self, listener: L) {
        match *self.state.write() {
            State::Open(ref mut raw_notifier) => raw_notifier.listen_raw(listener),
            State::Closed => {}
        }
    }

    // By adding this implementation instead of taking the default, we can defer
    // `FromListener::from_listener()` until we've done the early exit test.
    fn listen<L2: IntoListener<Self::Listener, Self::Msg>>(&self, listener: L2) {
        match *self.state.write() {
            State::Open(ref mut raw_notifier) => raw_notifier.listen(listener),
            State::Closed => {}
        }
    }
}

impl<M, L: Listener<M>> Default for Notifier<M, L> {
    fn default() -> Self {
        Self::new()
    }
}
impl<M, L: Listener<M>> Default for RawNotifier<M, L> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M, L> fmt::Debug for Notifier<M, L> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.state.try_read().as_deref() {
            // not using fmt.debug_tuple() so this is never printed on multiple lines
            Ok(State::Open(raw_notifier)) => {
                write!(fmt, "Notifier({})", raw_notifier.count_approximate())
            }
            Ok(State::Closed) => write!(fmt, "Notifier(closed)"),
            Err(_) => write!(fmt, "Notifier(?)"),
        }
    }
}
impl<M, L> fmt::Debug for RawNotifier<M, L> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        // not using fmt.debug_tuple() so this is never printed on multiple lines
        write!(fmt, "RawNotifier({})", self.count_approximate())
    }
}

impl<M, L> State<M, L> {
    fn count_approximate(&self) -> usize {
        match self {
            State::Open(listeners) => listeners.count_approximate(),
            State::Closed => 0,
        }
    }
}

impl<M, L: Listener<M>> State<M, L> {
    /// Discard all dead listeners.
    fn drop_dead_listeners(&mut self) {
        match self {
            State::Closed => {}
            State::Open(raw_notifier) => raw_notifier.drop_dead_listeners(),
        }
    }
}

// -------------------------------------------------------------------------------------------------

/// Buffers messages that are to be sent through a [`Notifier`], for efficiency.
///
/// Messages may be added to the buffer, and when the buffer contains
/// `CAPACITY` messages or when it is dropped,
/// they are all sent through [`Notifier::notify_many()`] at once.
/// This is intended to increase performance by invoking each listener once per batch
/// instead of once per message.
///
/// Create a [`Buffer`] by calling [`Notifier::buffer()`].
///
/// # Generic parameters
///
/// * `'notifier` is the lifetime of the borrow of the [`Notifier`]
///   which this sends messages to.
/// * `M` is the type of message accepted by the [`Notifier`].
/// * `L` is the type of [`Listener`] accepted by the [`Notifier`].
/// * `CAPACITY` is the maximum number of messages in one batch.
///   The buffer memory is allocated in-line in the [`Buffer`] value, so
///   `CAPACITY` should be chosen with consideration for stack memory usage.
#[derive(Debug)]
pub struct Buffer<'notifier, M, L, const CAPACITY: usize>
where
    L: Listener<M>,
{
    pub(crate) buffer: arrayvec::ArrayVec<M, CAPACITY>,
    pub(crate) notifier: &'notifier Notifier<M, L>,
}
/// Buffers messages that are to be sent through a [`RawNotifier`], for efficiency.
///
/// Messages may be added to the buffer, and when the buffer contains
/// `CAPACITY` messages or when it is dropped,
/// they are all sent through [`RawNotifier::notify_many()`] at once.
/// This is intended to increase performance by invoking each listener once per batch
/// instead of once per message.
///
/// Create a [`Buffer`] by calling [`RawNotifier::buffer()`].
///
/// # Generic parameters
///
/// * `'notifier` is the lifetime of the borrow of the [`Notifier`]
///   which this sends messages to.
/// * `M` is the type of message accepted by the [`Notifier`].
/// * `L` is the type of [`Listener`] accepted by the [`Notifier`].
/// * `CAPACITY` is the maximum number of messages in one batch.
///   The buffer memory is allocated in-line in the [`Buffer`] value, so
///   `CAPACITY` should be chosen with consideration for stack memory usage.
#[derive(Debug)]
pub struct RawBuffer<'notifier, M, L, const CAPACITY: usize>
where
    L: Listener<M>,
{
    pub(crate) buffer: arrayvec::ArrayVec<M, CAPACITY>,
    pub(crate) notifier: &'notifier mut RawNotifier<M, L>,
}

impl<'notifier, M, L, const CAPACITY: usize> Buffer<'notifier, M, L, CAPACITY>
where
    L: Listener<M>,
{
    pub(crate) fn new(notifier: &'notifier Notifier<M, L>) -> Self {
        Self {
            buffer: arrayvec::ArrayVec::new(),
            notifier,
        }
    }

    /// Store a message in this buffer, to be delivered later as if by [`Notifier::notify()`].
    ///
    /// If the buffer becomes full when this message is added, then the messages in the buffer will
    /// be delivered before `push()` returns.
    /// Otherwise, they will be delivered when the [`Buffer`] is dropped.
    pub fn push(&mut self, message: M) {
        // We don't need to check for fullness before pushing, because we always flush immediately
        // if full.
        self.buffer.push(message);
        if self.buffer.is_full() {
            self.flush();
        }
    }

    #[cold]
    pub(crate) fn flush(&mut self) {
        self.notifier.notify_many(&self.buffer);
        self.buffer.clear();
    }
}
impl<'notifier, M, L, const CAPACITY: usize> RawBuffer<'notifier, M, L, CAPACITY>
where
    L: Listener<M>,
{
    pub(crate) fn new(notifier: &'notifier mut RawNotifier<M, L>) -> Self {
        Self {
            buffer: arrayvec::ArrayVec::new(),
            notifier,
        }
    }

    /// Store a message in this buffer, to be delivered later as if by [`RawNotifier::notify()`].
    ///
    /// If the buffer becomes full when this message is added, then the messages in the buffer will
    /// be delivered before `push()` returns.
    /// Otherwise, they will be delivered when the [`Buffer`] is dropped.
    pub fn push(&mut self, message: M) {
        // We don't need to check for fullness before pushing, because we always flush immediately
        // if full.
        self.buffer.push(message);
        if self.buffer.is_full() {
            self.flush();
        }
    }

    #[cold]
    pub(crate) fn flush(&mut self) {
        self.notifier.notify_many(&self.buffer);
        self.buffer.clear();
    }
}

impl<M, L, const CAPACITY: usize> Drop for Buffer<'_, M, L, CAPACITY>
where
    L: Listener<M>,
{
    fn drop(&mut self) {
        if !self.buffer.is_empty() {
            self.flush();
        }
    }
}
impl<M, L, const CAPACITY: usize> Drop for RawBuffer<'_, M, L, CAPACITY>
where
    L: Listener<M>,
{
    fn drop(&mut self) {
        if !self.buffer.is_empty() {
            self.flush();
        }
    }
}

// -------------------------------------------------------------------------------------------------

/// A [`Listener`] which forwards messages through a [`Notifier`] to its listeners.
/// Constructed by [`Notifier::forwarder()`].
///
/// # Generic parameters
///
/// * `M` is the type of the messages to be broadcast.
/// * `L` is the type of [`Listener`] accepted by the [`Notifier`].
pub struct NotifierForwarder<M, L>(pub(super) Weak<Notifier<M, L>>);

impl<M, L> fmt::Debug for NotifierForwarder<M, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NotifierForwarder")
            .field("alive(shallow)", &(self.0.strong_count() > 0))
            .finish_non_exhaustive()
    }
}

impl<M, L> fmt::Pointer for NotifierForwarder<M, L> {
    /// Produces the address of the `Notifier` this forwards to.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.as_ptr().fmt(f)
    }
}

impl<M, L: Listener<M>> Listener<M> for NotifierForwarder<M, L> {
    fn receive(&self, messages: &[M]) -> bool {
        if let Some(notifier) = self.0.upgrade() {
            notifier.notify_many(messages);
            true
        } else {
            false
        }
    }
}

impl<L: Listener<M>, M> crate::FromListener<NotifierForwarder<M, L>, M>
    for NotifierForwarder<M, L>
{
    /// No-op conversion returning the listener unchanged.
    fn from_listener(listener: NotifierForwarder<M, L>) -> Self {
        listener
    }
}

impl<M, L> Clone for NotifierForwarder<M, L> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}