nami 0.11.1

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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Reactive collections with watcher support.
//!
//! This module provides a trait-based approach for creating observable collections
//! that can notify watchers when their contents change. It supports both reactive
//! collections that emit change notifications and static collections that provide
//! one-time snapshots.
//!
//! # Core Components
//!
//! - [`Collection`]: A trait defining the interface for observable collections
//! - [`List<T>`]: A reactive list implementation using `Rc<RefCell<Vec<T>>>`
//! - [`AnyCollection<T>`]: A type-erased wrapper for storing different collection types
//!
//! # Collection Types
//!
//! The module provides `Collection` implementations for:
//! - `List<T>`: Fully reactive with ongoing change notifications
//! - `Vec<T>`: Static collection with one-time watcher notifications
//! - `[T; N]`: Static array with one-time watcher notifications
//!
//! # Usage Example
//!
//! ```rust
//! use nami::collection::{Collection, List};
//!
//! // Create a reactive list
//! let mut list = List::new();
//! list.push(1);
//! list.push(2);
//!
//! // Watch for changes in a specific range
//! let _guard = list.watch(0..2, |ctx| {
//!     println!("Items changed: {:?}", ctx.into_value());
//! });
//!
//! // Modifications will trigger the watcher
//! list.push(3);
//! ```
//!
//! # Range-based Watching
//!
//! All collections support range-based watching using standard Rust range syntax:
//! - `collection.watch(.., watcher)` - Watch entire collection
//! - `collection.watch(1..5, watcher)` - Watch indices 1 through 4
//! - `collection.watch(2.., watcher)` - Watch from index 2 to end
//! - `collection.watch(..3, watcher)` - Watch from start to index 2
//!
//! # Type Erasure
//!
//! The `AnyCollection` wrapper allows storing different collection types
//! in the same container while preserving the ability to observe them:
//!
//! ```rust
//! use nami::collection::{AnyCollection, List};
//!
//! let list = List::from(vec![1, 2, 3]);
//! let any_collection = AnyCollection::new(list);
//!
//! // Still supports watching despite type erasure
//! let _guard = any_collection.watch(.., |ctx| {
//!     // Handle change notifications
//! });
//! ```

use core::{
    cell::{Cell, RefCell},
    ops::{Bound, RangeBounds},
};
pub use nami_core::collection::*;

use alloc::{rc::Rc, vec::Vec};
use nami_core::{
    SignalIdentity,
    observe::Origin,
    watcher::{Context, Metadata},
};

use crate::{
    Signal,
    watcher::{WatcherManager, WatcherManagerGuard},
};

/// Adapts a signal of vector snapshots into a reactive collection.
///
/// Collection consumers reconcile snapshots by item identity, so membership
/// changes update only inserted, removed, moved, or replaced items instead of
/// rebuilding the containing view subtree.
#[derive(Debug, Clone)]
pub struct SignalCollection<S> {
    signal: S,
}

impl<S> SignalCollection<S> {
    /// Creates a collection backed by vector snapshots from `signal`.
    pub const fn new(signal: S) -> Self {
        Self { signal }
    }
}

/// A reactive list that can be observed for changes.
///
/// Notifications use `Rc<[T]>` snapshots so that cloning a `Context` across
/// multiple watchers is O(1) (reference-count bump) instead of O(n).
#[derive(Debug)]
pub struct List<T> {
    vec: Rc<RefCell<Vec<T>>>,
    watchers: WatcherManager<Rc<[T]>>,
}

impl<T: 'static> From<Vec<T>> for List<T> {
    #[track_caller]
    fn from(value: Vec<T>) -> Self {
        Self::from_vec(value)
    }
}

impl<T: 'static> List<T> {
    /// Creates a new empty reactive list.
    #[must_use]
    #[track_caller]
    pub fn new() -> Self {
        Self::from_vec(Vec::new())
    }

    /// Builds a list around `value`, attributing the node to the caller.
    #[track_caller]
    fn from_vec(value: Vec<T>) -> Self {
        let vec = Rc::new(RefCell::new(value));
        let origin = Origin::capture::<Self>(SignalIdentity::from_rc(&vec));
        Self {
            vec,
            watchers: WatcherManager::with_origin(origin),
        }
    }

    /// Takes an `Rc<[T]>` snapshot of the current contents and notifies all
    /// watchers.  The snapshot is shared (O(1) clone) across watchers so each
    /// notification cycle only pays for one allocation.
    fn notify(&self)
    where
        T: Clone,
    {
        self.notify_with_metadata(Metadata::new());
    }

    fn notify_with_metadata(&self, metadata: Metadata)
    where
        T: Clone,
    {
        if self.watchers.is_empty() {
            return;
        }
        let snapshot: Rc<[T]> = Rc::from(self.vec.borrow().as_slice());
        self.watchers.notify(&Context::new(snapshot, metadata));
    }

    /// Adds an element to the end of the list.
    pub fn push(&self, value: T)
    where
        T: Clone,
    {
        self.vec.borrow_mut().push(value);
        self.notify();
    }

    /// Sorts the list in place.
    pub fn sort(&self)
    where
        T: Ord + Clone,
    {
        self.vec.borrow_mut().sort();
        self.notify();
    }

    /// Removes and returns the last element of the list.
    #[must_use]
    pub fn pop(&self) -> Option<T>
    where
        T: Clone,
    {
        let result = self.vec.borrow_mut().pop();
        if result.is_some() {
            self.notify();
        }
        result
    }

    /// Inserts an element at the specified index.
    pub fn insert(&self, index: usize, value: T)
    where
        T: Clone,
    {
        self.vec.borrow_mut().insert(index, value);
        self.notify();
    }

    /// Removes and returns the element at the specified index.
    #[must_use]
    pub fn remove(&self, index: usize) -> T
    where
        T: Clone,
    {
        let result = self.vec.borrow_mut().remove(index);
        self.notify();
        result
    }

    /// Clears all elements from the list.
    pub fn clear(&self)
    where
        T: Clone,
    {
        let was_empty = self.vec.borrow().is_empty();
        self.vec.borrow_mut().clear();
        if !was_empty {
            self.notify();
        }
    }

    /// Atomically replaces the complete list and returns the previous contents.
    ///
    /// Watchers observe only the final replacement snapshot, regardless of how
    /// many items differ between the old and new collections.
    #[must_use]
    pub fn replace(&self, value: Vec<T>) -> Vec<T>
    where
        T: Clone,
    {
        let previous = core::mem::replace(&mut *self.vec.borrow_mut(), value);
        self.notify();
        previous
    }

    /// Atomically replaces the complete list and propagates watcher metadata.
    #[must_use]
    pub fn replace_with_metadata(&self, value: Vec<T>, metadata: Metadata) -> Vec<T>
    where
        T: Clone,
    {
        let previous = core::mem::replace(&mut *self.vec.borrow_mut(), value);
        self.notify_with_metadata(metadata);
        previous
    }

    /// Takes a snapshot of the current list contents.
    #[must_use]
    pub fn snapshot(&self) -> Vec<T>
    where
        T: Clone,
    {
        self.vec.borrow().clone()
    }

    /// Returns an iterator over the list's items.
    ///
    /// Warning: This will clone the entire list, ensuring that modifications during iteration do not affect the iterator.
    #[must_use]
    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter
    where
        T: Clone,
    {
        self.snapshot().into_iter()
    }
}

/// Iterator implementation for `List<T>`
/// Tip: This method will attempt to avoid cloning the internal Vec if possible. However, if there are multiple references to the List, it will clone the Vec to ensure safety.
impl<T: Clone + 'static> IntoIterator for List<T> {
    type Item = T;
    type IntoIter = alloc::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        // if we can unwrap the Rc, we can avoid cloning
        match Rc::try_unwrap(self.vec) {
            Ok(vec) => vec.into_inner().into_iter(),
            Err(rc) => rc.borrow().clone().into_iter(),
        }
    }
}

/// Iterator implementation for references to `List<T>`
/// Warning: This will clone the entire list, ensuring that modifications during iteration do not affect the iterator.
impl<T: Clone + 'static> IntoIterator for &List<T> {
    type Item = T;
    type IntoIter = alloc::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.snapshot().into_iter()
    }
}

impl<T> Clone for List<T> {
    fn clone(&self) -> Self {
        Self {
            vec: self.vec.clone(),
            watchers: self.watchers.clone(),
        }
    }
}

impl<T: 'static> Default for List<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Resolve concrete `(start, end)` offsets from captured `Bound` values and
/// the current snapshot length, clamping to valid indices.
fn resolve_range(start_bound: Bound<usize>, end_bound: Bound<usize>, len: usize) -> (usize, usize) {
    let mut start = match start_bound {
        Bound::Included(n) => n,
        Bound::Excluded(n) => n.saturating_add(1),
        Bound::Unbounded => 0,
    };
    let mut end = match end_bound {
        Bound::Included(n) => n.saturating_add(1),
        Bound::Excluded(n) => n,
        Bound::Unbounded => len,
    };
    start = start.min(len);
    end = end.min(len);
    if start > end {
        start = end;
    }
    (start, end)
}

fn notify_signal_collection<T>(
    watcher: &dyn for<'a> Fn(Context<&'a [T]>),
    context: Context<Vec<T>>,
    start_bound: Bound<usize>,
    end_bound: Bound<usize>,
) {
    let metadata = context.metadata().clone();
    let snapshot = context.into_value();
    let (start, end) = resolve_range(start_bound, end_bound, snapshot.len());
    watcher(Context::new(&snapshot[start..end], metadata));
}

impl<S, T> Collection for SignalCollection<S>
where
    S: Signal<Output = Vec<T>> + Clone,
    T: Clone + 'static,
{
    type Item = T;
    type Guard = S::Guard;

    fn get(&self, index: usize) -> Option<Self::Item> {
        self.signal.get().as_slice().get(index).cloned()
    }

    fn len(&self) -> usize {
        self.signal.get().len()
    }

    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Item]>) + 'static,
    ) -> Self::Guard {
        let start_bound = range.start_bound().cloned();
        let end_bound = range.end_bound().cloned();
        let watcher = Rc::new(watcher);
        let pending = Rc::new(RefCell::new(None));
        let subscribed = Rc::new(Cell::new(false));

        let guard = self.signal.watch({
            let watcher = Rc::clone(&watcher);
            let pending = Rc::clone(&pending);
            let subscribed = Rc::clone(&subscribed);
            move |context| {
                if subscribed.get() {
                    notify_signal_collection(watcher.as_ref(), context, start_bound, end_bound);
                } else {
                    *pending.borrow_mut() = Some(context);
                }
            }
        });

        let initial = pending
            .borrow_mut()
            .take()
            .unwrap_or_else(|| Context::from(self.signal.get()));
        subscribed.set(true);
        notify_signal_collection(watcher.as_ref(), initial, start_bound, end_bound);

        guard
    }
}

impl<T: Clone + 'static> Collection for List<T> {
    type Item = T;
    type Guard = WatcherManagerGuard<Rc<[T]>>;

    fn get(&self, index: usize) -> Option<Self::Item> {
        self.vec.borrow().as_slice().get(index).cloned()
    }
    fn len(&self) -> usize {
        self.vec.borrow().len()
    }
    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Item]>) + 'static,
    ) -> Self::Guard {
        // Convert range bounds to concrete values for capture
        let start_bound = match range.start_bound() {
            Bound::Included(&n) => Bound::Included(n),
            Bound::Excluded(&n) => Bound::Excluded(n),
            Bound::Unbounded => Bound::Unbounded,
        };
        let end_bound = match range.end_bound() {
            Bound::Included(&n) => Bound::Included(n),
            Bound::Excluded(&n) => Bound::Excluded(n),
            Bound::Unbounded => Bound::Unbounded,
        };

        // Call watcher immediately with current data
        {
            let snapshot: Rc<[T]> = Rc::from(self.vec.borrow().as_slice());
            let (start, end) = resolve_range(start_bound, end_bound, snapshot.len());
            watcher(Context::from(&snapshot[start..end]));
        }

        // Subsequent notifications: slice the Rc<[T]> snapshot carried inside
        // the Context.  Cloning an Rc is O(1), so this avoids the previous
        // O(n) re-borrow + range clone per watcher.
        self.watchers.register_as_guard(move |ctx| {
            let snapshot: Rc<[T]> = ctx.value().clone(); // O(1) ref-count bump
            let metadata = ctx.metadata().clone();
            let (start, end) = resolve_range(start_bound, end_bound, snapshot.len());
            watcher(Context::new(&snapshot[start..end], metadata));
        })
    }
}

impl<T: 'static> FromIterator<T> for List<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self::from(iter.into_iter().collect::<Vec<_>>())
    }
}

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

    #[test]
    fn test_collection_trait_basic_operations() {
        let list = List::from(vec![1, 2, 3]);

        assert_eq!(Collection::len(&list), 3);
        assert!(!Collection::is_empty(&list));
        assert_eq!(Collection::get(&list, 0), Some(1));
        assert_eq!(Collection::get(&list, 1), Some(2));
        assert_eq!(Collection::get(&list, 2), Some(3));
        assert_eq!(Collection::get(&list, 3), None);
    }

    #[test]
    fn replace_notifies_only_the_final_snapshot() {
        let list = List::from(vec![1, 2]);
        let observed = Rc::new(RefCell::new(Vec::<Vec<i32>>::new()));
        let observed_for_watcher = Rc::clone(&observed);
        let _guard = list.watch(.., move |context| {
            observed_for_watcher
                .borrow_mut()
                .push(context.into_value().to_vec());
        });

        let previous = list.replace(vec![3, 4, 5]);

        assert_eq!(previous, vec![1, 2]);
        assert_eq!(*observed.borrow(), vec![vec![1, 2], vec![3, 4, 5]]);
    }

    #[test]
    fn signal_collection_emits_initial_and_updated_snapshots() {
        let values = crate::binding(vec![1, 2]);
        let collection = SignalCollection::new(values.clone());
        let observed = Rc::new(RefCell::new(Vec::<Vec<i32>>::new()));
        let observed_for_watcher = Rc::clone(&observed);
        let _guard = collection.watch(.., move |context| {
            observed_for_watcher
                .borrow_mut()
                .push(context.into_value().to_vec());
        });

        values.set(vec![2, 3, 4]);

        assert_eq!(*observed.borrow(), vec![vec![1, 2], vec![2, 3, 4]]);
    }

    #[test]
    fn test_list_new_and_default() {
        let list1: List<i32> = List::new();
        let list2: List<i32> = List::default();

        assert_eq!(Collection::len(&list1), 0);
        assert!(Collection::is_empty(&list1));
        assert_eq!(Collection::len(&list2), 0);
        assert!(Collection::is_empty(&list2));
    }

    #[test]
    fn test_list_from_vec() {
        let vec = vec![1, 2, 3, 4, 5];
        let list = List::from(vec);

        assert_eq!(Collection::len(&list), 5);
        for i in 0..5 {
            assert_eq!(Collection::get(&list, i), Some(i + 1));
        }
    }

    #[test]
    fn test_list_push_and_pop() {
        let list = List::new();

        list.push(1);
        list.push(2);
        list.push(3);

        assert_eq!(Collection::len(&list), 3);
        assert_eq!(Collection::get(&list, 0), Some(1));
        assert_eq!(Collection::get(&list, 1), Some(2));
        assert_eq!(Collection::get(&list, 2), Some(3));

        assert_eq!(list.pop(), Some(3));
        assert_eq!(Collection::len(&list), 2);
        assert_eq!(list.pop(), Some(2));
        assert_eq!(list.pop(), Some(1));
        assert_eq!(list.pop(), None);
        assert!(Collection::is_empty(&list));
    }

    #[test]
    fn test_list_insert_and_remove() {
        let list = List::from(vec![1, 3, 5]);

        list.insert(1, 2);
        list.insert(3, 4);

        assert_eq!(Collection::len(&list), 5);
        assert_eq!(Collection::get(&list, 0), Some(1));
        assert_eq!(Collection::get(&list, 1), Some(2));
        assert_eq!(Collection::get(&list, 2), Some(3));
        assert_eq!(Collection::get(&list, 3), Some(4));
        assert_eq!(Collection::get(&list, 4), Some(5));

        assert_eq!(list.remove(1), 2);
        assert_eq!(list.remove(2), 4);
        assert_eq!(Collection::len(&list), 3);
        assert_eq!(Collection::get(&list, 0), Some(1));
        assert_eq!(Collection::get(&list, 1), Some(3));
        assert_eq!(Collection::get(&list, 2), Some(5));
    }

    #[test]
    fn test_list_clear() {
        let list = List::from(vec![1, 2, 3, 4, 5]);
        assert_eq!(Collection::len(&list), 5);

        list.clear();
        assert_eq!(Collection::len(&list), 0);
        assert!(Collection::is_empty(&list));

        // Clearing an empty list should not panic
        list.clear();
        assert!(Collection::is_empty(&list));
    }

    #[test]
    fn test_list_clone() {
        let list1 = List::from(vec![1, 2, 3]);
        let list2 = Clone::clone(&list1);

        assert_eq!(Collection::len(&list1), Collection::len(&list2));
        for i in 0..3 {
            assert_eq!(Collection::get(&list1, i), Collection::get(&list2, i));
        }

        // Modifications to one should affect the other (shared ownership)
        list1.push(4);
        assert_eq!(Collection::len(&list2), 4);
        assert_eq!(Collection::get(&list2, 3), Some(4));
    }

    #[test]
    fn test_list_watcher_notifications() {
        let list = List::new();
        let notification_count = Rc::new(RefCell::new(0));

        let count = notification_count.clone();
        let _guard = Collection::watch(&list, .., move |_ctx| {
            *count.borrow_mut() += 1;
        });

        // Initial snapshot should fire once with empty data.
        assert_eq!(*notification_count.borrow(), 1);
        {
            let mut count_mut = notification_count.borrow_mut();
            *count_mut = 0;
        }

        // Push operations should trigger notifications
        list.push(1);
        assert_eq!(*notification_count.borrow(), 1);

        list.push(2);
        assert_eq!(*notification_count.borrow(), 2);

        let _ = list.pop();
        assert_eq!(*notification_count.borrow(), 3);
    }

    #[test]
    fn test_list_watcher_range() {
        let list = List::from(vec![1, 2, 3, 4, 5]);
        let notification_count = Rc::new(RefCell::new(0));

        let count = notification_count.clone();
        let _guard = Collection::watch(&list, 1..4, move |ctx| {
            *count.borrow_mut() += 1;
            assert_eq!(ctx.into_value(), vec![2, 3, 4]);
        });

        list.push(6);
        assert_eq!(*notification_count.borrow(), 2);
    }

    #[test]
    fn test_vec_collection_implementation() {
        let vec = vec![1, 2, 3, 4, 5];

        assert_eq!(Collection::len(&vec), 5);
        assert!(!Collection::is_empty(&vec));
        assert_eq!(Collection::get(&vec, 2), Some(3));
        assert_eq!(Collection::get(&vec, 10), None);

        // Vec is static - watch should be a no-op and not call the watcher
        let called = Rc::new(Cell::new(false));
        let c = called.clone();
        Collection::watch(&vec, 1..3, move |_ctx| {
            c.set(true);
        });

        assert!(!called.get()); // Watcher should not be called for static Vec
    }

    #[test]
    fn test_array_collection_implementation() {
        let arr = [1, 2, 3, 4, 5];

        assert_eq!(Collection::len(&arr), 5);
        assert!(!Collection::is_empty(&arr));
        assert_eq!(Collection::get(&arr, 2), Some(3));
        assert_eq!(Collection::get(&arr, 10), None);

        // Arrays are static - watch should be a no-op and not call the watcher
        let called = Rc::new(Cell::new(false));
        let c = called.clone();
        Collection::watch(&arr, 0..2, move |_ctx| {
            c.set(true);
        });

        assert!(!called.get()); // Watcher should not be called for static array
    }

    #[test]
    fn test_empty_array_collection() {
        let arr: [i32; 0] = [];

        assert_eq!(Collection::len(&arr), 0);
        assert!(Collection::is_empty(&arr));
        assert_eq!(Collection::get(&arr, 0), None);

        // Empty arrays are static - watch should be a no-op
        let called = Rc::new(Cell::new(false));
        let c = called.clone();
        Collection::watch(&arr, .., move |_ctx| {
            c.set(true);
        });

        assert!(!called.get()); // Watcher should not be called for static empty array
    }

    #[test]
    fn test_any_collection_basic_operations() {
        let list = List::from(vec![1, 2, 3]);
        let any_collection = AnyCollection::new(list);

        assert_eq!(any_collection.len(), 3);
        assert!(!any_collection.is_empty());
        assert_eq!(any_collection.get(0), Some(1));
        assert_eq!(any_collection.get(1), Some(2));
        assert_eq!(any_collection.get(2), Some(3));
        assert_eq!(any_collection.get(3), None);
    }

    #[test]
    fn test_any_collection_from_vec() {
        let vec = vec![10, 20, 30];
        let any_collection = AnyCollection::new(vec);

        assert_eq!(any_collection.len(), 3);
        assert_eq!(any_collection.get(0), Some(10));
        assert_eq!(any_collection.get(1), Some(20));
        assert_eq!(any_collection.get(2), Some(30));
    }

    #[test]
    fn test_any_collection_from_array() {
        let arr = [100, 200, 300];
        let any_collection = AnyCollection::new(arr);

        assert_eq!(any_collection.len(), 3);
        assert_eq!(any_collection.get(0), Some(100));
        assert_eq!(any_collection.get(1), Some(200));
        assert_eq!(any_collection.get(2), Some(300));
    }

    #[test]
    fn test_any_collection_watcher() {
        let list = List::from(vec![1, 2, 3, 4, 5]);
        let any_collection = AnyCollection::new(list);

        let called = Rc::new(RefCell::new(false));
        let c = called.clone();
        let _guard = any_collection.watch(1..3, move |ctx| {
            *c.borrow_mut() = true;
            assert_eq!(ctx.into_value(), vec![2, 3]);
        });

        assert!(*called.borrow());
    }

    #[test]
    fn test_range_bounds_inclusive() {
        let list = List::from(vec![0, 1, 2, 3, 4]);
        let called = Rc::new(RefCell::new(false));

        let c = called.clone();
        let _guard = Collection::watch(&list, 1..=3, move |ctx| {
            *c.borrow_mut() = true;
            assert_eq!(ctx.into_value(), vec![1, 2, 3]);
        });

        assert!(*called.borrow());
    }

    #[test]
    fn test_range_bounds_from() {
        let list = List::from(vec![0, 1, 2, 3, 4]);
        let called = Rc::new(RefCell::new(false));

        let c = called.clone();
        let _guard = Collection::watch(&list, 2.., move |ctx| {
            *c.borrow_mut() = true;
            assert_eq!(ctx.into_value(), vec![2, 3, 4]);
        });

        assert!(*called.borrow());
    }

    #[test]
    fn test_range_bounds_to() {
        let list = List::from(vec![0, 1, 2, 3, 4]);
        let called = Rc::new(RefCell::new(false));

        let c = called.clone();
        let _guard = Collection::watch(&list, ..3, move |ctx| {
            *c.borrow_mut() = true;
            assert_eq!(ctx.into_value(), vec![0, 1, 2]);
        });

        assert!(*called.borrow());
    }

    #[test]
    fn test_range_bounds_full() {
        let list = List::from(vec![0, 1, 2, 3, 4]);
        let called = Rc::new(RefCell::new(false));

        let c = called.clone();
        let _guard = Collection::watch(&list, .., move |ctx| {
            *c.borrow_mut() = true;
            assert_eq!(ctx.into_value(), vec![0, 1, 2, 3, 4]);
        });

        assert!(*called.borrow());
    }

    #[test]
    fn test_out_of_bounds_range() {
        let list = List::from(vec![1, 2, 3]);
        let called = Rc::new(Cell::new(None::<bool>));

        let c = called.clone();
        let _guard = Collection::watch(&list, 10..20, move |ctx| {
            let is_empty = ctx.map(<[i32]>::is_empty).into_value();
            c.set(Some(is_empty));
        });

        // Out-of-bounds range should yield an empty snapshot
        assert_eq!(called.get(), Some(true));
    }

    #[test]
    fn test_empty_range() {
        let list = List::from(vec![1, 2, 3]);
        let called = Rc::new(Cell::new(None::<bool>));

        let c = called.clone();
        let _guard = Collection::watch(&list, 2..2, move |ctx| {
            let is_empty = ctx.map(<[i32]>::is_empty).into_value();
            c.set(Some(is_empty));
        });

        // Empty range should snapshot as an empty slice
        assert_eq!(called.get(), Some(true));
    }

    #[test]
    fn test_watcher_guard_cleanup() {
        let list = List::new();
        let notification_count = Rc::new(RefCell::new(0));

        {
            let count = notification_count.clone();
            let _guard = Collection::watch(&list, .., move |_ctx| {
                *count.borrow_mut() += 1;
            });

            // Initial snapshot
            assert_eq!(*notification_count.borrow(), 1);
            {
                let mut count_mut = notification_count.borrow_mut();
                *count_mut = 0;
            }

            list.push(1);
            assert_eq!(*notification_count.borrow(), 1);
        } // Guard is dropped here

        // After guard is dropped, no more notifications should occur
        list.push(2);
        assert_eq!(*notification_count.borrow(), 1);
    }
}