nami-core 0.5.0

A powerful, lightweight reactive framework.
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! # Watcher Management
//!
//! This module provides the infrastructure for managing reactive value watchers,
//! including metadata handling and notification systems.
//!
//! # When watcher would be called?
//!
//! > Watchers are called when the value may have changed.
//!
//! This means that even if the new value is equal to the old value, watchers may will still be called.
//!
//! # Why not only when value actually changed?
//!
//! Since we does not require `Eq` or `PartialEq` bounds on the watched values, so we cannot determine
//! whether the value actually changed or not.
//!
//! # So if upstream user calls `notify`, my watcher will always be called?
//!
//! The answer is: Maybe yes, maybe no.
//!
//! We preserve the freedom to discard notifications in certain scenarios, as a performance optimization.
//!
//! Also, you can use `nami::SignalExt::distinct` to create a distinct signal that only notifies when the value changes manually.

use alloc::{boxed::Box, collections::VecDeque, rc::Rc, vec::Vec};
use core::{
    any::{Any, TypeId, type_name},
    cell::RefCell,
    fmt::Debug,
    num::NonZeroUsize,
};

use crate::observe::{self, Origin};

/// A type-erased container for metadata that can be associated with computation results.
///
/// `Metadata` allows attaching arbitrary typed information to computation results
/// and passing it through the computation pipeline.
///
/// It holds at most a handful of entries (typically none, sometimes an
/// animation), so it is a boxed slice searched linearly: an empty `Metadata`
/// does not allocate, and cloning an empty one is free.
#[derive(Debug, Default, Clone)]
pub struct Metadata(Box<[(TypeId, Rc<dyn Any>)]>);

/// Type alias for a reference-counted watcher function.
pub type Watcher<T> = Rc<dyn Fn(Context<T>) + 'static>;

/// Context passed to watchers containing the value and associated metadata.
#[derive(Debug, Clone)]
pub struct Context<T> {
    /// The current value being watched.
    value: T,
    /// Associated metadata for this value change.
    metadata: Metadata,
}

impl<T> Context<T> {
    /// Creates a new context with the given value and metadata.
    pub const fn new(value: T, metadata: Metadata) -> Self {
        Self { value, metadata }
    }

    /// Adds additional metadata to this context.
    #[must_use]
    pub fn with<V: Clone + 'static>(mut self, value: V) -> Self {
        self.metadata = self.metadata.with(value);
        self
    }

    /// Consumes the context and returns the inner value.
    pub fn into_value(self) -> T {
        self.value
    }

    /// Consumes the context and returns the value and the metadata.
    ///
    /// Useful to re-wrap a borrow of the value with the same metadata, without
    /// cloning it: `Context::new(&value[..], metadata)`.
    pub fn into_parts(self) -> (T, Metadata) {
        (self.value, self.metadata)
    }

    /// Returns a reference to the inner value.
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns a mutable reference to the inner value.
    pub const fn value_mut(&mut self) -> &mut T {
        &mut self.value
    }

    /// Returns a reference to the metadata.
    pub const fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Returns a mutable reference to the metadata.
    pub const fn metadata_mut(&mut self) -> &mut Metadata {
        &mut self.metadata
    }

    /// Maps the inner value to a new value.
    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Context<U> {
        Context::new(f(self.value), self.metadata)
    }

    /// Returns a new context with a reference to the inner value.
    pub fn as_ref(&self) -> Context<&T> {
        Context::new(&self.value, self.metadata.clone())
    }

    /// Returns a new context with a mutable reference to the inner value.
    pub fn as_mut(&mut self) -> Context<&mut T> {
        Context::new(&mut self.value, self.metadata.clone())
    }

    /// Returns a new context with a reference to the dereferenced inner value.
    pub fn as_deref(&self) -> Context<&T::Target>
    where
        T: core::ops::Deref,
    {
        Context::new(&*self.value, self.metadata.clone())
    }

    /// Returns a new context with a mutable reference to the dereferenced inner value.
    pub fn as_deref_mut(&mut self) -> Context<&mut T::Target>
    where
        T: core::ops::DerefMut,
    {
        Context::new(&mut *self.value, self.metadata.clone())
    }
}

impl<T> From<T> for Context<T> {
    fn from(value: T) -> Self {
        Self::new(value, Metadata::new())
    }
}

/// A guard that ensures proper cleanup of watchers when dropped.
#[must_use]
pub trait WatcherGuard: 'static {}

impl<T: 'static> WatcherGuard for Option<T> {}

impl<T: WatcherGuard, E: WatcherGuard> WatcherGuard for Result<T, E> {}

impl WatcherGuard for () {}

impl<T1: WatcherGuard, T2: WatcherGuard> WatcherGuard for (T1, T2) {}

/// A utility struct that runs a cleanup function when dropped.
#[derive(Debug)]
pub struct OnDrop<F>(Option<F>)
where
    F: FnOnce();

impl<F> OnDrop<F>
where
    F: FnOnce() + 'static,
{
    /// Creates a new `OnDrop` that will call the function when dropped.
    pub const fn new(f: F) -> Self {
        Self(Some(f))
    }

    /// Attaches a cleanup function to a guard.
    ///
    /// `drop` (not `let _ =`) moves `guard` into the closure: a `move`
    /// closure whose body only does `let _ = guard` captures nothing,
    /// because disjoint closure captures (edition 2021) see no use of
    /// `guard` — it would stay owned by the caller and die when `attach`
    /// returns.
    #[allow(clippy::needless_pass_by_value)]
    pub fn attach(guard: impl WatcherGuard, f: F) -> impl WatcherGuard {
        OnDrop::new(move || {
            drop(guard);
            f();
        })
    }
}

impl<F> Drop for OnDrop<F>
where
    F: FnOnce(),
{
    fn drop(&mut self) {
        let Some(callback) = self.0.take() else {
            panic!("OnDrop::drop called with missing callback");
        };
        callback();
    }
}

/// Type alias for a boxed watcher guard.
pub type BoxWatcherGuard = Box<dyn WatcherGuard>;

impl<T: WatcherGuard + ?Sized> WatcherGuard for Box<T> {}
impl<T: WatcherGuard + ?Sized> WatcherGuard for Rc<T> {}

impl<F: FnOnce() + 'static> WatcherGuard for OnDrop<F> {}

impl Metadata {
    /// Creates a new, empty metadata container.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets a value of type `T` from the metadata.
    ///
    /// # Panics
    ///
    /// Panics if no value of type `T` is present in the metadata.
    #[must_use]
    pub fn get<T: 'static + Clone>(&self) -> T {
        self.try_get()
            .unwrap_or_else(|| panic!("Metadata::get missing value for requested type"))
    }

    /// Attempts to get a value of type `T` from the metadata.
    ///
    /// Returns `None` if no value of the requested type is present.
    #[must_use]
    pub fn try_get<T: 'static + Clone>(&self) -> Option<T> {
        let id = TypeId::of::<T>();
        self.0
            .iter()
            .find(|(key, _)| *key == id)
            .and_then(|(_, value)| value.downcast_ref::<T>())
            .cloned()
    }

    /// Adds a value to the metadata and returns the updated metadata.
    ///
    /// A value of the same type that is already present is replaced.
    /// This method is chainable for fluent API usage.
    #[must_use]
    pub fn with<T: 'static + Clone>(self, value: T) -> Self {
        // Values are cheap to clone (an `Animation` is a few words), but the
        // type must be erased; `Rc` keeps retrieval a refcount bump.
        self.with_erased(TypeId::of::<T>(), Rc::new(value))
    }

    /// Merges `other` into `self`, returning the union: a value already
    /// present under the same type is replaced by `other`'s.
    ///
    /// Deferred notifications (such as a batched `List` change) compose
    /// their metadata this way, so the single notification they finally
    /// send carries what the individual ones would have.
    #[must_use]
    pub fn merge(self, other: Self) -> Self {
        if self.is_empty() {
            return other;
        }
        other
            .0
            .into_iter()
            .fold(self, |merged, (id, value)| merged.with_erased(id, value))
    }

    /// Stores the erased `value` under `id`, replacing a value already
    /// present under it.
    fn with_erased(mut self, id: TypeId, value: Rc<dyn Any>) -> Self {
        if let Some(slot) = self.0.iter_mut().find(|(key, _)| *key == id) {
            slot.1 = value;
            return self;
        }
        let mut entries = Vec::from(self.0);
        entries.push((id, value));
        self.0 = entries.into_boxed_slice();
        self
    }

    /// Checks if the metadata container is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// A unique identifier for registered watchers.
pub type WatcherId = NonZeroUsize;

/// The registered callbacks of a [`WatcherRegistry`], in registration order.
///
/// Shared copy-on-write: a notification holds one of these while it runs, so
/// registering or cancelling during a notification rebuilds the list for the
/// next round instead of changing the one being delivered.
type Entries<W> = Rc<Vec<(WatcherId, Rc<W>)>>;

/// A copy-on-write list of callbacks, the storage behind every watcher list
/// in nami.
///
/// `W` is the callback type, usually a `dyn Fn(..)`. [`WatcherManager`] is the
/// registry for `Fn(Context<T>)` watchers; collections use it with their own
/// callback signature.
///
/// Notifying takes a refcount on the current list instead of collecting it,
/// so the notify path does not allocate. Watchers registered or cancelled
/// during a notification do not affect that notification, and a notification
/// raised by a watcher while one is in progress is queued and delivered
/// afterwards (see [`Self::notify_with`]), so every watcher sees changes in
/// the order they happened.
pub struct WatcherRegistry<W: ?Sized> {
    inner: Rc<RefCell<RegistryInner<W>>>,
}

impl<W: ?Sized> Debug for WatcherRegistry<W> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(type_name::<Self>())
    }
}

impl<W: ?Sized> Clone for WatcherRegistry<W> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<W: ?Sized> Default for WatcherRegistry<W> {
    fn default() -> Self {
        Self::with_origin_unobserved(Origin::unattributed())
    }
}

impl<W: ?Sized + 'static> WatcherRegistry<W> {
    /// Creates an empty registry with no provenance.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a registry attributed to a state-owning signal node.
    ///
    /// State owners should use this rather than [`Self::new`] so development
    /// tooling can attribute subscriptions and notifications to the node and to
    /// the source location that created it. [`Origin`] is zero-sized unless the
    /// `observability` feature is enabled.
    #[must_use]
    pub fn with_origin(origin: Origin) -> Self {
        observe::on_create(origin);
        Self::with_origin_unobserved(origin)
    }

    /// Checks if the registry has any registered watchers.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.borrow().entries.is_empty()
    }

    /// Number of currently registered watchers.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.borrow().entries.len()
    }

    /// Adds `watcher` and returns its identifier.
    pub fn insert(&self, watcher: Rc<W>) -> WatcherId {
        let (id, origin, subscribers) = {
            let mut inner = self.inner.borrow_mut();
            let id = inner.assign();
            Rc::make_mut(&mut inner.entries).push((id, watcher));
            (id, inner.origin, inner.entries.len())
        };
        observe::on_subscribe(origin, subscribers);
        id
    }

    /// Adds `watcher` and returns a guard that removes it when dropped.
    pub fn insert_as_guard(&self, watcher: Rc<W>) -> RegistryGuard<W> {
        let id = self.insert(watcher);
        RegistryGuard {
            registry: self.clone(),
            id,
        }
    }

    /// Cancels a previously registered watcher by its identifier.
    ///
    /// The removed watcher is dropped after the borrow on `inner` is
    /// released, because dropping its closure may re-enter this registry
    /// through a guard it owns.
    pub fn cancel(&self, id: WatcherId) {
        let (removed, origin, subscribers) = {
            let mut inner = self.inner.borrow_mut();
            // Ids are assigned in increasing order and entries are only ever
            // appended, so the list stays sorted by id.
            let removed = match inner.entries.binary_search_by_key(&id, |(id, _)| *id) {
                Ok(position) => Some(Rc::make_mut(&mut inner.entries).remove(position)),
                Err(_) => None,
            };
            (removed, inner.origin, inner.entries.len())
        };
        observe::on_unsubscribe(origin, subscribers);
        drop(removed);
    }

    /// Calls `call` once per registered watcher with a clone of `value`; the
    /// last watcher receives `value` itself, so a single watcher costs no
    /// clone at all.
    ///
    /// The watcher list is the one registered when the call starts: watchers
    /// added or cancelled by a callback take effect from the next delivery.
    ///
    /// # Reentrancy
    ///
    /// A `notify_with` call that arrives while the same registry is already
    /// delivering — a watcher notifying the signal it watches — does not
    /// run a nested round. Its delivery is queued, and the outermost
    /// `notify_with` drains the queue after its own round finishes: every
    /// watcher sees the running round's value before the queued one.
    /// Queued deliveries run in the order they arrived, each to the
    /// watchers that were registered when it was raised and are still
    /// registered when it runs: a watcher added meanwhile has already read
    /// the state the queued notification describes, and one cancelled
    /// meanwhile must not be called at all. A delivery queued while
    /// draining joins the same loop, so reentrant notification never
    /// recurses at any depth.
    ///
    /// The queue owns a deferred delivery until its turn, which is why
    /// `value` and `call` must be `'static`; it allocates only when a
    /// notification is actually deferred.
    pub fn notify_with<A: Clone + 'static>(&self, value: A, mut call: impl FnMut(&W, A) + 'static) {
        let (entries, origin) = {
            let mut inner = self.inner.borrow_mut();
            // The snapshot comes first: a mutable borrow of `inner.queue`
            // would keep all of `inner` borrowed through `DerefMut`.
            let entries = Rc::clone(&inner.entries);
            let origin = inner.origin;
            if let Some(queue) = &mut inner.queue {
                // A round is in progress: queue this delivery behind it
                // instead of nesting a second round inside the first. The
                // recipients are the watchers registered right now, so the
                // current entries list rides along (a refcount, not a copy).
                queue.push_back((
                    entries,
                    Box::new(move |watcher| call(watcher, value.clone())),
                ));
                return;
            }
            inner.queue = Some(VecDeque::new());
            (entries, origin)
        };
        // Takes `queue` back to `None` on any exit — a panicking watcher
        // included — and drops what is still queued with it, so the registry
        // is never stuck in "delivering".
        let _scope = DeliveryScope(&self.inner);

        let Some(((_, last), rest)) = entries.split_last() else {
            return;
        };
        observe::on_notify(origin, entries.len());
        for (_, watcher) in rest {
            call(watcher, value.clone());
        }
        call(last, value);

        // Deliver what watchers queued, oldest first; deliveries queued
        // while draining join the same loop. A queued delivery goes to the
        // watchers registered when it was raised that are still registered
        // — both lists are sorted by id, so membership is a binary search.
        loop {
            let queued = {
                let mut inner = self.inner.borrow_mut();
                // `queue` stays `Some` until `_scope` drops.
                let Some(queue) = inner.queue.as_mut() else {
                    break;
                };
                queue.pop_front()
            };
            let Some((raised, mut delivery)) = queued else {
                break;
            };
            let (current, origin) = {
                let inner = self.inner.borrow();
                (Rc::clone(&inner.entries), inner.origin)
            };
            let still_registered =
                |id: &WatcherId| current.binary_search_by_key(id, |(id, _)| *id).is_ok();
            let recipients = raised.iter().filter(|(id, _)| still_registered(id)).count();
            if recipients == 0 {
                continue;
            }
            observe::on_notify(origin, recipients);
            for (_, watcher) in raised.iter().filter(|(id, _)| still_registered(id)) {
                delivery(watcher);
            }
        }
    }
}

impl<W: ?Sized> WatcherRegistry<W> {
    /// Builds the registry without reporting its creation to observers.
    fn with_origin_unobserved(origin: Origin) -> Self {
        Self {
            inner: Rc::new(RefCell::new(RegistryInner {
                next: WatcherId::MIN,
                entries: Rc::new(Vec::new()),
                origin,
                queue: None,
            })),
        }
    }
}

/// A guard that removes a watcher from its [`WatcherRegistry`] when dropped.
#[must_use]
pub struct RegistryGuard<W: ?Sized + 'static> {
    registry: WatcherRegistry<W>,
    id: WatcherId,
}

impl<W: ?Sized> Debug for RegistryGuard<W> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RegistryGuard")
            .field("registry", &self.registry)
            .field("id", &self.id)
            .finish()
    }
}

impl<W: ?Sized + 'static> WatcherGuard for RegistryGuard<W> {}

impl<W: ?Sized + 'static> Drop for RegistryGuard<W> {
    fn drop(&mut self) {
        self.registry.cancel(self.id);
    }
}

/// Manages the `Fn(Context<T>)` watchers of a signal.
pub type WatcherManager<T> = WatcherRegistry<dyn Fn(Context<T>)>;

/// A guard that ensures a watcher is unregistered from its
/// [`WatcherManager`] when dropped.
pub type WatcherManagerGuard<T> = RegistryGuard<dyn Fn(Context<T>)>;

impl<T: 'static> WatcherRegistry<dyn Fn(Context<T>)> {
    /// Registers a new watcher and returns its unique identifier.
    pub fn register(&self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
        self.insert(Rc::new(watcher))
    }

    /// Registers a watcher and returns a guard that will unregister it when dropped.
    pub fn register_as_guard(
        &self,
        watcher: impl Fn(Context<T>) + 'static,
    ) -> WatcherManagerGuard<T> {
        self.insert_as_guard(Rc::new(watcher))
    }

    /// Notifies all registered watchers with a clone of `ctx`.
    ///
    /// Prefer [`Self::notify_owned`] when the context is not needed
    /// afterwards: it saves one clone.
    pub fn notify(&self, ctx: &Context<T>)
    where
        T: Clone,
    {
        if self.is_empty() {
            return;
        }
        self.notify_owned(ctx.clone());
    }

    /// Notifies all registered watchers, moving `ctx` into the last one.
    pub fn notify_owned(&self, ctx: Context<T>)
    where
        T: Clone,
    {
        self.notify_with(ctx, |watcher, ctx| watcher(ctx));
    }
}

/// A notification that arrived while its registry was already delivering.
/// Owns the value and the caller's `call`, cloning the value for each
/// watcher it is invoked for.
type QueuedDelivery<W> = Box<dyn FnMut(&W)>;

/// Internal state of a [`WatcherRegistry`].
struct RegistryInner<W: ?Sized> {
    next: WatcherId,
    entries: Entries<W>,
    origin: Origin,
    /// `Some` while a `notify_*` call is delivering: notifications that
    /// arrive then are appended here and drained once the round in progress
    /// finishes, oldest first. Each entry keeps the watcher list that was
    /// registered when the notification was raised (a refcount, not a
    /// copy). The `VecDeque` allocates on its first push, so a registry
    /// that is never notified re-entrantly allocates nothing.
    queue: Option<VecDeque<(Entries<W>, QueuedDelivery<W>)>>,
}

/// Ends a registry's "delivering" state on drop. A watcher that panics
/// unwinds through this guard, so the registry is never left stuck; the
/// still-queued deliveries are dropped along with the state.
struct DeliveryScope<'a, W: ?Sized>(&'a RefCell<RegistryInner<W>>);

impl<W: ?Sized> Drop for DeliveryScope<'_, W> {
    fn drop(&mut self) {
        // A queued delivery can own a guard on this registry; drop them
        // only after the borrow is released.
        let queue = self.0.borrow_mut().queue.take();
        drop(queue);
    }
}

impl<W: ?Sized> Drop for RegistryInner<W> {
    fn drop(&mut self) {
        observe::on_drop(self.origin);
    }
}

impl<W: ?Sized> RegistryInner<W> {
    /// Assigns a new unique identifier for a watcher.
    const fn assign(&mut self) -> WatcherId {
        let id = self.next;
        self.next = match self.next.checked_add(1) {
            Some(id) => id,
            None => panic!("`id` grows beyond `usize::MAX`"),
        };
        id
    }
}

#[cfg(test)]
mod tests {
    use alloc::{rc::Rc, vec, vec::Vec};
    use core::cell::{Cell, RefCell};

    use super::{Context, OnDrop, WatcherGuard, WatcherManager};

    /// A watcher whose closure owns a `WatcherManagerGuard` on the same
    /// manager re-enters `cancel` from the guard's `Drop` when the watcher is
    /// dropped, so removal must not run that destructor while `inner` is
    /// still borrowed.
    #[test]
    fn cancel_drops_removed_watcher_after_releasing_borrow() {
        let manager = WatcherManager::<i32>::new();
        let nested = manager.register_as_guard(|_| ());
        let owner = manager.register(move |_: Context<i32>| {
            let _owns_nested_guard = &nested;
        });
        manager.cancel(owner);
        assert!(manager.is_empty());
    }

    /// A `move` closure that only did `let _ = guard` would capture nothing
    /// under edition 2021's disjoint captures, so `attach` returned a guard
    /// whose payload had already died. `attach` must hold `guard` until the
    /// returned `OnDrop` itself drops (water-rs/hydrolysis#228).
    #[test]
    fn attach_holds_the_guard_until_the_result_drops() {
        struct Probe(Rc<Cell<bool>>);
        impl WatcherGuard for Probe {}
        impl Drop for Probe {
            fn drop(&mut self) {
                self.0.set(true);
            }
        }

        let dropped = Rc::new(Cell::new(false));
        let attached = OnDrop::attach(Probe(Rc::clone(&dropped)), || ());
        assert!(!dropped.get(), "attach dropped the guard early");
        drop(attached);
        assert!(dropped.get());
    }

    /// A notification raised while a round is delivering is queued and
    /// drained after it, so every watcher sees the changes in the order
    /// they were made (water-rs/nami#51).
    #[test]
    fn reentrant_notify_is_queued_until_the_round_finishes() {
        let manager = WatcherManager::<i32>::new();
        let seen_first = Rc::new(RefCell::new(Vec::new()));
        let seen_second = Rc::new(RefCell::new(Vec::new()));
        let fired = Rc::new(Cell::new(false));

        manager.register({
            let manager = manager.clone();
            let seen = Rc::clone(&seen_first);
            let fired = Rc::clone(&fired);
            move |context: Context<i32>| {
                let value = context.into_value();
                seen.borrow_mut().push(value);
                if value == 1 && !fired.replace(true) {
                    manager.notify_owned(Context::from(2));
                }
            }
        });
        manager.register({
            let seen = Rc::clone(&seen_second);
            move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
        });

        manager.notify_owned(Context::from(1));

        assert_eq!(*seen_first.borrow(), vec![1, 2]);
        assert_eq!(*seen_second.borrow(), vec![1, 2]);
    }

    /// A watcher registered while a round is delivering — but after a
    /// notification was raised — misses the queued delivery too: by the
    /// time it registered it could already read the state that notification
    /// describes.
    #[test]
    fn a_watcher_registered_mid_round_misses_queued_deliveries() {
        let manager = WatcherManager::<i32>::new();
        let seen_late = Rc::new(RefCell::new(Vec::new()));
        let done = Rc::new(Cell::new(false));

        manager.register({
            let manager = manager.clone();
            let seen_late = Rc::clone(&seen_late);
            let done = Rc::clone(&done);
            move |_context: Context<i32>| {
                if done.replace(true) {
                    return;
                }
                // Raised before the late watcher registers: it must not see
                // this delivery.
                manager.notify_owned(Context::from(2));
                manager.register({
                    let seen_late = Rc::clone(&seen_late);
                    move |context: Context<i32>| {
                        seen_late.borrow_mut().push(context.into_value());
                    }
                });
            }
        });

        manager.notify_owned(Context::from(1));
        assert!(
            seen_late.borrow().is_empty(),
            "the late watcher must miss the delivery raised before it registered"
        );

        manager.notify_owned(Context::from(3));
        assert_eq!(
            *seen_late.borrow(),
            vec![3],
            "the late watcher takes effect from the next notification"
        );
    }

    /// A watcher cancelled by an earlier watcher after a notification was
    /// raised but before its queued delivery runs does not receive it.
    #[test]
    fn a_watcher_cancelled_mid_round_misses_queued_deliveries() {
        let manager = WatcherManager::<i32>::new();
        let done = Rc::new(Cell::new(false));
        let cancelled_id = Rc::new(RefCell::new(None));
        let seen_cancelled = Rc::new(RefCell::new(Vec::new()));
        let seen_later = Rc::new(RefCell::new(Vec::new()));

        manager.register({
            let manager = manager.clone();
            let done = Rc::clone(&done);
            let cancelled_id = Rc::clone(&cancelled_id);
            move |context: Context<i32>| {
                if *context.value() == 1 && !done.replace(true) {
                    // Raised while the cancelled watcher is still
                    // registered; cancelled before the delivery runs.
                    manager.notify_owned(Context::from(2));
                    if let Some(id) = cancelled_id.borrow_mut().take() {
                        manager.cancel(id);
                    }
                }
            }
        });
        let second = manager.register({
            let seen = Rc::clone(&seen_cancelled);
            move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
        });
        *cancelled_id.borrow_mut() = Some(second);
        manager.register({
            let seen = Rc::clone(&seen_later);
            move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
        });

        manager.notify_owned(Context::from(1));

        assert_eq!(
            *seen_cancelled.borrow(),
            vec![1],
            "round 1's snapshot still reached it; the queued delivery did not"
        );
        assert_eq!(*seen_later.borrow(), vec![1, 2]);
    }
}