Skip to main content

xrack_runtime/
model.rs

1use crate::{ChangeSignal, RowKey, RowLifetime};
2use std::{
3    cell::{Cell, RefCell},
4    cmp::Ordering as Comparison,
5    collections::BTreeMap,
6    fmt,
7    ops::Range,
8    rc::{Rc, Weak},
9    sync::atomic::{AtomicU64, Ordering},
10};
11
12static NEXT_MODEL: AtomicU64 = AtomicU64::new(1);
13
14struct Entry<T> {
15    id: u64,
16    value: T,
17}
18
19#[derive(Default)]
20struct RowSignals {
21    signals: BTreeMap<usize, ChangeSignal>,
22    next_prune: usize,
23}
24
25impl RowSignals {
26    fn track(&mut self, index: usize) {
27        if !self.signals.contains_key(&index) && self.signals.len() >= self.next_prune {
28            self.signals.retain(|_, signal| signal.has_observers());
29            self.next_prune = (self.signals.len() * 2).max(64);
30        }
31        self.signals.entry(index).or_default().track();
32    }
33}
34
35type ProjectionDiff<T> = dyn Fn(usize, &T, &T) -> bool;
36pub(crate) type RowObserver<T> = dyn Fn(RowKey, Option<&T>);
37
38struct RowProjection<T> {
39    signal: Weak<ChangeSignal>,
40    limit: usize,
41    changed: Box<ProjectionDiff<T>>,
42}
43
44struct ModelData<T> {
45    id: u64,
46    rows: RefCell<Vec<Entry<T>>>,
47    next_row: Cell<u64>,
48    revision: Cell<u64>,
49    edit_revision: Cell<u64>,
50    lifetimes: RefCell<BTreeMap<u64, Rc<()>>>,
51    count: ChangeSignal,
52    structure: ChangeSignal,
53    values: ChangeSignal,
54    row_signals: RefCell<RowSignals>,
55    projections: RefCell<Vec<RowProjection<T>>>,
56    row_observers: RefCell<Vec<Weak<RowObserver<T>>>>,
57}
58
59/// A shared UI-thread model with separately tracked row and length reads.
60/// Cloning the handle shares its data and subscriptions.
61pub struct VecModel<T>(Rc<ModelData<T>>);
62
63impl<T> fmt::Debug for VecModel<T> {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("VecModel")
66            .field("id", &self.0.id)
67            .finish_non_exhaustive()
68    }
69}
70
71impl<T> Clone for VecModel<T> {
72    fn clone(&self) -> Self {
73        Self(self.0.clone())
74    }
75}
76
77impl<T> From<Vec<T>> for VecModel<T> {
78    #[expect(
79        clippy::expect_used,
80        reason = "model IDs must stay unique even if the counter reaches its limit"
81    )]
82    fn from(rows: Vec<T>) -> Self {
83        let id = NEXT_MODEL
84            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
85            .expect("model identity exhausted");
86        let next_row = rows.len() as u64;
87        Self(Rc::new(ModelData {
88            id,
89            rows: RefCell::new(
90                rows.into_iter()
91                    .enumerate()
92                    .map(|(id, value)| Entry {
93                        id: id as u64,
94                        value,
95                    })
96                    .collect(),
97            ),
98            next_row: Cell::new(next_row),
99            revision: Cell::default(),
100            edit_revision: Cell::default(),
101            lifetimes: RefCell::default(),
102            count: ChangeSignal::default(),
103            structure: ChangeSignal::default(),
104            values: ChangeSignal::default(),
105            row_signals: RefCell::default(),
106            projections: RefCell::default(),
107            row_observers: RefCell::default(),
108        }))
109    }
110}
111
112impl<T> Default for VecModel<T> {
113    fn default() -> Self {
114        Self::from(Vec::new())
115    }
116}
117
118impl<T> PartialEq for VecModel<T> {
119    fn eq(&self, other: &Self) -> bool {
120        Rc::ptr_eq(&self.0, &other.0)
121    }
122}
123
124impl<T> Eq for VecModel<T> {}
125
126impl<T> VecModel<T> {
127    pub(crate) fn is_shared(&self) -> bool {
128        Rc::strong_count(&self.0) > 1
129    }
130
131    #[expect(
132        clippy::expect_used,
133        reason = "a new row must never reuse a row identity"
134    )]
135    fn entry(&self, value: T) -> Entry<T> {
136        let id = self.0.next_row.get();
137        self.0
138            .next_row
139            .set(id.checked_add(1).expect("model row identity exhausted"));
140        Entry { id, value }
141    }
142
143    /// A stable identity that survives edits, inserts, removes of other rows, and sorting.
144    pub fn row_key(&self, index: usize) -> Option<RowKey> {
145        self.0.structure.track();
146        self.0.rows.borrow().get(index).map(|entry| RowKey {
147            model: self.0.id,
148            row: entry.id,
149            scope: 0,
150        })
151    }
152
153    /// Find a record's current index by its stable identity.
154    pub fn row_index(&self, key: RowKey) -> Option<usize> {
155        self.0.structure.track();
156        self.row_index_untracked(key)
157    }
158
159    pub(crate) fn row_index_untracked(&self, key: RowKey) -> Option<usize> {
160        if key.model != self.0.id {
161            return None;
162        }
163        self.0
164            .rows
165            .borrow()
166            .iter()
167            .position(|entry| entry.id == key.row)
168    }
169
170    pub(crate) fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
171        self.0.structure.track();
172        for entry in &self.0.rows.borrow()[range] {
173            visit(RowKey {
174                model: self.0.id,
175                row: entry.id,
176                scope: 0,
177            });
178        }
179    }
180
181    pub(crate) fn visit_row_data(&self, count: usize, visit: impl FnMut(usize, RowKey, &T)) {
182        self.0.values.track();
183        self.visit_rows_untracked(count, visit);
184    }
185
186    /// Borrow the rows after the caller has established the appropriate dependencies.
187    pub(crate) fn visit_rows_untracked(
188        &self,
189        count: usize,
190        mut visit: impl FnMut(usize, RowKey, &T),
191    ) {
192        for (index, entry) in self.0.rows.borrow().iter().take(count).enumerate() {
193            visit(
194                index,
195                RowKey {
196                    model: self.0.id,
197                    row: entry.id,
198                    scope: 0,
199                },
200                &entry.value,
201            );
202        }
203    }
204
205    /// Locate a row after the caller has established the appropriate dependencies.
206    pub(crate) fn position_untracked(
207        &self,
208        range: std::ops::Range<usize>,
209        mut predicate: impl FnMut(&T) -> bool,
210    ) -> Option<usize> {
211        let start = range.start;
212        self.0
213            .rows
214            .borrow()
215            .get(range)?
216            .iter()
217            .position(|entry| predicate(&entry.value))
218            .map(|offset| start + offset)
219    }
220
221    /// Check an editor's field against the identified row without watching other fields.
222    #[doc(hidden)]
223    pub fn row_matches(&self, index: usize, key: RowKey, matches: impl FnOnce(&T) -> bool) -> bool {
224        key.model == self.0.id
225            && self
226                .0
227                .rows
228                .borrow()
229                .get(index)
230                .is_some_and(|entry| entry.id == key.row && matches(&entry.value))
231    }
232
233    pub(crate) fn project_row_untracked<R>(
234        &self,
235        index: usize,
236        project: impl FnOnce(&T) -> R,
237    ) -> Option<R> {
238        self.0
239            .rows
240            .borrow()
241            .get(index)
242            .map(|entry| project(&entry.value))
243    }
244
245    /// Subscribe to changes in the projected value of existing rows. The caller also tracks
246    /// structure changes and keeps the returned signal alive for as long as it uses the projection.
247    pub(crate) fn observe_projection<P: PartialEq>(
248        &self,
249        limit: usize,
250        project: impl Fn(&T) -> P + 'static,
251    ) -> Rc<ChangeSignal> {
252        self.observe_projection_changes(limit, move |_, before, after| {
253            project(before) != project(after)
254        })
255    }
256
257    pub(crate) fn observe_projection_changes(
258        &self,
259        limit: usize,
260        changed: impl Fn(usize, &T, &T) -> bool + 'static,
261    ) -> Rc<ChangeSignal> {
262        let signal = Rc::new(ChangeSignal::default());
263        let mut projections = self.0.projections.borrow_mut();
264        projections.retain(|projection| projection.signal.strong_count() != 0);
265        projections.push(RowProjection {
266            signal: Rc::downgrade(&signal),
267            limit,
268            changed: Box::new(changed),
269        });
270        signal
271    }
272
273    /// Observe row contents by stable key. Observers run while the model may be borrowed.
274    pub(crate) fn observe_rows(&self, observer: &Rc<RowObserver<T>>) {
275        let mut observers = self.0.row_observers.borrow_mut();
276        observers.retain(|observer| observer.strong_count() != 0);
277        observers.push(Rc::downgrade(observer));
278    }
279
280    fn row_changed(&self, id: u64, value: Option<&T>) {
281        let key = RowKey {
282            model: self.0.id,
283            row: id,
284            scope: 0,
285        };
286        self.0.row_observers.borrow_mut().retain(|observer| {
287            if let Some(observer) = observer.upgrade() {
288                observer(key, value);
289                true
290            } else {
291                false
292            }
293        });
294    }
295
296    pub(crate) fn row_lifetime(&self, key: RowKey) -> RowLifetime {
297        let mut lifetimes = self.0.lifetimes.borrow_mut();
298        RowLifetime(Some(Rc::downgrade(lifetimes.entry(key.row).or_default())))
299    }
300
301    pub(crate) fn structure_stamp(&self) -> (u64, u64) {
302        self.0.structure.track();
303        (self.0.id, self.0.revision.get())
304    }
305
306    /// Identify the exact model contents and order seen by an asynchronous edit.
307    #[doc(hidden)]
308    pub fn edit_stamp(&self) -> (u64, u64) {
309        (self.0.id, self.0.edit_revision.get())
310    }
311
312    pub(crate) fn contents_stamp(&self) -> (u64, u64) {
313        self.0.values.track();
314        self.edit_stamp()
315    }
316
317    pub fn len(&self) -> usize {
318        self.0.count.track();
319        self.0.rows.borrow().len()
320    }
321
322    /// Inspect a bounded page without recording reactive dependencies.
323    #[doc(hidden)]
324    pub fn inspect_rows<R>(
325        &self,
326        offset: usize,
327        limit: usize,
328        map: impl FnMut(&T) -> R,
329    ) -> (usize, Vec<R>) {
330        let rows = self.0.rows.borrow();
331        let items = rows
332            .iter()
333            .skip(offset)
334            .take(limit)
335            .map(|row| &row.value)
336            .map(map)
337            .collect();
338        (rows.len(), items)
339    }
340
341    pub fn is_empty(&self) -> bool {
342        self.len() == 0
343    }
344
345    pub fn push(&self, value: T) {
346        let index = {
347            let mut rows = self.0.rows.borrow_mut();
348            let index = rows.len();
349            let entry = self.entry(value);
350            self.row_changed(entry.id, Some(&entry.value));
351            rows.push(entry);
352            index
353        };
354        self.structure_changed(index, true);
355    }
356
357    /// Insert at a model index. An index beyond the end leaves the model unchanged.
358    pub fn insert(&self, index: usize, value: T) -> bool {
359        {
360            let mut rows = self.0.rows.borrow_mut();
361            if index > rows.len() {
362                return false;
363            }
364            let entry = self.entry(value);
365            self.row_changed(entry.id, Some(&entry.value));
366            rows.insert(index, entry);
367        }
368        self.structure_changed(index, true);
369        true
370    }
371
372    pub fn remove(&self, index: usize) -> Option<T> {
373        let removed = {
374            let mut rows = self.0.rows.borrow_mut();
375            if index >= rows.len() {
376                return None;
377            }
378            rows.remove(index)
379        };
380        self.row_changed(removed.id, None);
381        self.0.lifetimes.borrow_mut().remove(&removed.id);
382        self.structure_changed(index, true);
383        Some(removed.value)
384    }
385
386    /// Remove every row in a single structure update, keeping the model handle.
387    pub fn clear(&self) {
388        let removed = std::mem::take(&mut *self.0.rows.borrow_mut());
389        if removed.is_empty() {
390            return;
391        }
392        for entry in &removed {
393            self.row_changed(entry.id, None);
394        }
395        self.0.lifetimes.borrow_mut().clear();
396        self.structure_changed(0, true);
397    }
398
399    pub(crate) fn sorted_indices_untracked(
400        &self,
401        limit: usize,
402        compare: impl FnMut(&T, &T) -> Comparison,
403    ) -> Vec<usize> {
404        self.projected_indices_untracked(limit, None, |_| true, Some(compare))
405    }
406
407    pub(crate) fn projected_indices_untracked(
408        &self,
409        limit: usize,
410        base_order: Option<&[usize]>,
411        include: impl Fn(&T) -> bool,
412        compare: Option<impl FnMut(&T, &T) -> Comparison>,
413    ) -> Vec<usize> {
414        let rows = self.0.rows.borrow();
415        let mut order: Vec<_> = (0..rows.len().min(limit))
416            .map(|index| base_order.map_or(index, |order| order[index]))
417            .filter(|&index| include(&rows[index].value))
418            .collect();
419        if let Some(mut compare) = compare {
420            order.sort_by(|&a, &b| compare(&rows[a].value, &rows[b].value));
421        }
422        order
423    }
424
425    /// Move a row to its final index without changing its key or lifetime.
426    pub fn move_row(&self, from: usize, to: usize) -> bool {
427        if from == to || from.max(to) >= self.len() {
428            return false;
429        }
430        {
431            let mut rows = self.0.rows.borrow_mut();
432            if from < to {
433                rows[from..=to].rotate_left(1);
434            } else {
435                rows[to..=from].rotate_right(1);
436            }
437        }
438        self.structure_changed(from.min(to), false);
439        true
440    }
441
442    /// Stably reorder rows, retaining their keys and delegate lifetimes.
443    pub fn sort_by(&self, compare: impl FnMut(&T, &T) -> Comparison) -> bool {
444        let order = self.sorted_indices_untracked(usize::MAX, compare);
445        let Some(first_changed) = order.iter().enumerate().position(|(new, old)| new != *old)
446        else {
447            return false;
448        };
449        {
450            let mut rows = self.0.rows.borrow_mut();
451            let mut source: Vec<_> = rows.drain(first_changed..).map(Some).collect();
452            #[expect(
453                clippy::expect_used,
454                reason = "the sort permutation contains each existing row index exactly once"
455            )]
456            rows.extend(order.into_iter().skip(first_changed).map(|index| {
457                source[index - first_changed]
458                    .take()
459                    .expect("sort permutation contains each row once")
460            }));
461        }
462        self.structure_changed(first_changed, false);
463        true
464    }
465
466    fn structure_changed(&self, index: usize, count_changed: bool) {
467        self.0.revision.set(self.0.revision.get().wrapping_add(1));
468        // Notify readers before discarding signals for indices whose rows have shifted.
469        let shifted = self.0.row_signals.borrow_mut().signals.split_off(&index);
470        for signal in shifted.into_values() {
471            signal.notify();
472        }
473        if count_changed {
474            self.0.count.notify();
475        }
476        self.0.structure.notify();
477        self.values_changed();
478    }
479
480    fn values_changed(&self) {
481        self.0
482            .edit_revision
483            .set(self.0.edit_revision.get().wrapping_add(1));
484        self.0.values.notify();
485    }
486}
487
488impl<T> VecModel<T> {
489    pub(crate) fn project_row<R>(&self, index: usize, project: impl FnOnce(&T) -> R) -> Option<R> {
490        let rows = self.0.rows.borrow();
491        if let Some(entry) = rows.get(index) {
492            if ChangeSignal::is_tracking() {
493                self.0.row_signals.borrow_mut().track(index);
494            }
495            Some(project(&entry.value))
496        } else {
497            self.0.count.track();
498            None
499        }
500    }
501}
502
503impl<T: Clone> VecModel<T> {
504    pub fn row(&self, index: usize) -> Option<T> {
505        self.project_row(index, T::clone)
506    }
507
508    /// Resolve a DSL model index with the same dependency tracking as a row read.
509    #[doc(hidden)]
510    pub fn row_at(&self, index: i64) -> Option<T> {
511        self.row(usize::try_from(index).ok()?)
512    }
513
514    pub fn snapshot(&self) -> Vec<T> {
515        self.0.values.track();
516        self.snapshot_untracked()
517    }
518
519    /// Copy rows that the caller has already sampled from the live model.
520    #[doc(hidden)]
521    pub fn snapshot_untracked(&self) -> Vec<T> {
522        self.0
523            .rows
524            .borrow()
525            .iter()
526            .map(|entry| entry.value.clone())
527            .collect()
528    }
529
530    /// Transfer an owned model's rows at a by-value boundary. A shared model
531    /// still needs a tracked read because its other owners can edit it.
532    #[doc(hidden)]
533    pub fn into_snapshot(self) -> Vec<T> {
534        match Rc::try_unwrap(self.0) {
535            Ok(data) => data
536                .rows
537                .into_inner()
538                .into_iter()
539                .map(|entry| entry.value)
540                .collect(),
541            Err(data) => Self(data).snapshot(),
542        }
543    }
544}
545
546/// A typed mutation of an existing model.
547#[doc(hidden)]
548pub enum ModelEdit<T> {
549    Append(T),
550    Insert(i64, T),
551    Set(i64, T),
552    Remove(i64),
553    Move(i64, i64),
554    Clear,
555}
556
557impl<T> ModelEdit<T> {
558    pub fn try_map<U, E>(self, map: impl FnOnce(T) -> Result<U, E>) -> Result<ModelEdit<U>, E> {
559        use ModelEdit::*;
560        Ok(match self {
561            Append(value) => Append(map(value)?),
562            Insert(index, value) => Insert(index, map(value)?),
563            Set(index, value) => Set(index, map(value)?),
564            Remove(index) => Remove(index),
565            Move(from, to) => Move(from, to),
566            Clear => Clear,
567        })
568    }
569}
570
571impl<T: PartialEq> ModelEdit<T> {
572    pub fn apply(self, model: &VecModel<T>) {
573        let index = |index| usize::try_from(index).ok();
574        match self {
575            Self::Append(value) => model.push(value),
576            Self::Insert(at, value) => {
577                if let Some(at) = index(at) {
578                    model.insert(at, value);
579                }
580            }
581            Self::Set(at, value) => {
582                if let Some(at) = index(at) {
583                    model.set_row(at, value);
584                }
585            }
586            Self::Remove(at) => {
587                if let Some(at) = index(at) {
588                    model.remove(at);
589                }
590            }
591            Self::Move(from, to) => {
592                if let (Some(from), Some(to)) = (index(from), index(to)) {
593                    model.move_row(from, to);
594                }
595            }
596            Self::Clear => model.clear(),
597        }
598    }
599}
600
601impl<T: PartialEq> VecModel<T> {
602    /// Commit a value against the row and value observed by an editor.
603    pub fn set_row_if_current(&self, index: usize, key: RowKey, expected: &T, value: T) -> bool {
604        self.update_row_if_key(index, key, |current| (current == expected).then_some(value))
605    }
606
607    /// Update an identified record from its latest value. Returning None declines the edit.
608    pub fn update_row_if_key(
609        &self,
610        index: usize,
611        key: RowKey,
612        update: impl FnOnce(&T) -> Option<T>,
613    ) -> bool {
614        let next = {
615            let rows = self.0.rows.borrow();
616            let Some(entry) = rows
617                .get(index)
618                .filter(|entry| key.model == self.0.id && entry.id == key.row)
619            else {
620                return false;
621            };
622            update(&entry.value)
623        };
624        next.is_some_and(|value| self.set_row(index, value))
625    }
626
627    /// Replace one row. Returns false for an invalid index or equal value.
628    pub fn set_row(&self, index: usize, value: T) -> bool {
629        let mut value = value;
630        let changed = {
631            let mut rows = self.0.rows.borrow_mut();
632            let Some(current) = rows.get_mut(index) else {
633                return false;
634            };
635            self.swap_row(index, current, &mut value)
636        };
637        if changed {
638            self.values_changed();
639        }
640        changed
641    }
642
643    pub(crate) fn replace_rows_if_current(
644        &self,
645        stamp: (u64, u64),
646        mut values: Vec<(usize, T)>,
647    ) -> bool {
648        if self.edit_stamp() != stamp {
649            return false;
650        }
651        let mut rows = self.0.rows.borrow_mut();
652        if values.iter().any(|(index, _)| *index >= rows.len()) {
653            return false;
654        }
655        let mut changed = false;
656        for (index, value) in &mut values {
657            changed |= self.swap_row(*index, &mut rows[*index], value);
658        }
659        drop(rows);
660        if changed {
661            self.values_changed();
662        }
663        changed
664    }
665
666    fn swap_row(&self, index: usize, entry: &mut Entry<T>, next: &mut T) -> bool {
667        if &entry.value == next {
668            return false;
669        }
670        self.0.projections.borrow_mut().retain(|projection| {
671            let Some(signal) = projection.signal.upgrade() else {
672                return false;
673            };
674            if index < projection.limit && (projection.changed)(index, &entry.value, next) {
675                signal.notify();
676            }
677            true
678        });
679        std::mem::swap(&mut entry.value, next);
680        self.row_changed(entry.id, Some(&entry.value));
681        if let Some(signal) = self.0.row_signals.borrow().signals.get(&index) {
682            signal.notify();
683        }
684        true
685    }
686
687    /// Compare the current values, independently of handle identity.
688    pub fn values_eq(&self, other: &Self) -> bool {
689        self.compare_values(other, |model| model.0.values.track())
690    }
691
692    /// Compare expression operands, tracking only models that can outlive
693    /// the comparison and be changed by another owner.
694    #[doc(hidden)]
695    pub fn values_eq_owned(self, other: Self) -> bool {
696        self.compare_values(&other, |model| {
697            if model.is_shared() {
698                model.0.values.track();
699            }
700        })
701    }
702
703    fn compare_values(&self, other: &Self, track: impl Fn(&Self)) -> bool {
704        if self == other {
705            return true;
706        }
707        track(self);
708        track(other);
709        self.0.rows.borrow().iter().map(|row| &row.value).eq(other
710            .0
711            .rows
712            .borrow()
713            .iter()
714            .map(|row| &row.value))
715    }
716}
717
718#[cfg(test)]
719mod tests {
720    use super::*;
721    use crate::Property;
722    use std::cell::Cell;
723
724    #[test]
725    fn clear_notifies_count_and_expires_rows_without_replacing_the_model() {
726        let model = VecModel::from(vec!["first", "second"]);
727        let count = Property::default();
728        let alias = model.clone();
729        let first = model.row_key(0).unwrap();
730        let lifetime = model.row_lifetime(first);
731        let (identity, _) = model.structure_stamp();
732        assert_eq!(count.get(|| alias.len()), 2);
733        ModelEdit::Clear.apply(&model);
734        assert_eq!(count.get(|| alias.len()), 0);
735        assert_eq!(model.structure_stamp().0, identity);
736        let empty = model.edit_stamp();
737        ModelEdit::Clear.apply(&model);
738        assert_eq!(model.edit_stamp(), empty);
739        ModelEdit::Append("again").apply(&alias);
740        assert_eq!(count.get(|| model.len()), 1);
741        assert_ne!(model.row_key(0), Some(first));
742        assert!(!lifetime.is_live(first, identity, 1));
743    }
744
745    #[test]
746    fn moving_rows_keeps_keys_and_invalidates_shifted_index_reads() {
747        let model = VecModel::from(vec!['a', 'b', 'c', 'd']);
748        let key = model.row_key(1).unwrap();
749        let lifetime = model.row_lifetime(key);
750        let second = Property::default();
751        let last = Property::default();
752        assert_eq!(second.get(|| model.row(1)), Some('b'));
753        assert_eq!(last.get(|| model.row(3)), Some('d'));
754        let before = model.contents_stamp();
755        assert!(!model.move_row(1, 1));
756        assert!(!model.move_row(1, 4));
757        assert_eq!(before, model.contents_stamp());
758        assert!(model.move_row(1, 3));
759        assert_eq!(model.snapshot(), ['a', 'c', 'd', 'b']);
760        assert_eq!(model.row_key(3), Some(key));
761        assert!(lifetime.is_live(key, model.structure_stamp().0, 4));
762        assert_eq!(second.get(|| model.row(1)), Some('c'));
763        assert_eq!(last.get(|| model.row(3)), Some('b'));
764        assert!(model.move_row(3, 1));
765        assert_eq!(model.row_key(1), Some(key));
766    }
767
768    #[test]
769    fn sorting_retains_stable_keys_and_invalidates_only_affected_reads() {
770        let model = VecModel::from(vec![(0, 'a'), (2, 'b'), (1, 'c'), (2, 'd')]);
771        let keys: Vec<_> = (0..4).map(|index| model.row_key(index).unwrap()).collect();
772        let lifetime = model.row_lifetime(keys[2]);
773        let len = Property::default();
774        let first = Property::default();
775        let second = Property::default();
776        let count_reads = Cell::new(0);
777        let prefix_reads = Cell::new(0);
778        let count = || {
779            len.get(|| {
780                count_reads.set(count_reads.get() + 1);
781                model.len()
782            })
783        };
784        let prefix = || {
785            first.get(|| {
786                prefix_reads.set(prefix_reads.get() + 1);
787                model.row(0)
788            })
789        };
790        let row = || second.get(|| model.row(1));
791        assert_eq!(
792            (count(), prefix(), row()),
793            (4, Some((0, 'a')), Some((2, 'b')))
794        );
795        assert!(model.sort_by(|a, b| a.0.cmp(&b.0)));
796        assert_eq!(
797            (count(), prefix(), row()),
798            (4, Some((0, 'a')), Some((1, 'c')))
799        );
800        assert_eq!((count_reads.get(), prefix_reads.get()), (1, 1));
801        assert_eq!(model.snapshot(), [(0, 'a'), (1, 'c'), (2, 'b'), (2, 'd')]);
802        assert_eq!(model.row_key(1), Some(keys[2]));
803        assert_eq!(model.row_key(2), Some(keys[1]));
804        assert_eq!(model.row_key(3), Some(keys[3]));
805        assert!(lifetime.is_live(keys[2], model.structure_stamp().0, 4));
806        assert!(!model.sort_by(|a, b| a.0.cmp(&b.0)));
807    }
808
809    #[test]
810    fn watched_model_rows_survive_pruning_and_detect_shifts() {
811        use crate::property::watch_reads;
812
813        let model = VecModel::from((0..128).collect::<Vec<_>>());
814        watch_reads(|reads| {
815            for index in 0..100 {
816                assert_eq!(model.row(index), Some(index));
817            }
818            assert!(model.set_row(120, 0));
819            assert!(!reads.changed());
820            assert!(model.set_row(0, 120));
821            assert!(reads.changed());
822        });
823        watch_reads(|reads| {
824            assert_eq!(model.row(1), Some(1));
825            assert_eq!(model.remove(0), Some(120));
826            assert!(reads.changed());
827        });
828    }
829
830    #[test]
831    fn consuming_snapshot_tracks_only_models_with_a_live_owner() {
832        let temporary = Property::default();
833        assert_eq!(
834            temporary.get(|| VecModel::from(vec![1]).into_snapshot()),
835            [1]
836        );
837        assert!(!temporary.is_dirty());
838
839        let shared = VecModel::from(vec![2]);
840        let snapshot = Property::default();
841        let read = || snapshot.get(|| shared.clone().into_snapshot());
842        assert_eq!(read(), [2]);
843        assert!(!snapshot.is_dirty());
844        assert!(shared.set_row(0, 3));
845        assert!(snapshot.is_dirty());
846        assert_eq!(read(), [3]);
847    }
848
849    #[test]
850    fn model_tracks_rows_length_and_snapshots_independently() {
851        let model = VecModel::from(vec![10, 20, 30]);
852        let count = Property::default();
853        let second = Property::default();
854        let missing = Property::default();
855        let snapshot = Property::default();
856        let reads = Cell::new(0);
857        let len = || {
858            count.get(|| {
859                reads.set(reads.get() + 1);
860                model.len()
861            })
862        };
863        let row = || second.get(|| model.row(1));
864        let tail = || missing.get(|| model.row(3));
865        let values = || snapshot.get(|| model.snapshot());
866
867        assert_eq!((len(), row(), tail()), (3, Some(20), None));
868        assert_eq!(values(), [10, 20, 30]);
869        assert!(model.set_row(0, 11));
870        assert_eq!((len(), row()), (3, Some(20)));
871        assert_eq!(reads.get(), 1);
872        assert_eq!(values(), [11, 20, 30]);
873        assert!(!model.set_row(0, 11));
874        assert!(!model.set_row(9, 11));
875        model.push(40);
876        assert_eq!((len(), row(), tail()), (4, Some(20), Some(40)));
877        assert!(model.insert(0, 5));
878        assert_eq!((len(), row(), tail()), (5, Some(11), Some(30)));
879        assert_eq!(model.remove(0), Some(5));
880        assert_eq!((len(), row(), tail()), (4, Some(20), Some(40)));
881    }
882}