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    fn from(rows: Vec<T>) -> Self {
79        let id = NEXT_MODEL
80            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
81            .expect("model identity exhausted");
82        let next_row = rows.len() as u64;
83        Self(Rc::new(ModelData {
84            id,
85            rows: RefCell::new(
86                rows.into_iter()
87                    .enumerate()
88                    .map(|(id, value)| Entry {
89                        id: id as u64,
90                        value,
91                    })
92                    .collect(),
93            ),
94            next_row: Cell::new(next_row),
95            revision: Cell::default(),
96            edit_revision: Cell::default(),
97            lifetimes: RefCell::default(),
98            count: ChangeSignal::default(),
99            structure: ChangeSignal::default(),
100            values: ChangeSignal::default(),
101            row_signals: RefCell::default(),
102            projections: RefCell::default(),
103            row_observers: RefCell::default(),
104        }))
105    }
106}
107
108impl<T> Default for VecModel<T> {
109    fn default() -> Self {
110        Self::from(Vec::new())
111    }
112}
113
114impl<T> PartialEq for VecModel<T> {
115    fn eq(&self, other: &Self) -> bool {
116        Rc::ptr_eq(&self.0, &other.0)
117    }
118}
119
120impl<T> Eq for VecModel<T> {}
121
122impl<T> VecModel<T> {
123    pub(crate) fn is_shared(&self) -> bool {
124        Rc::strong_count(&self.0) > 1
125    }
126
127    fn entry(&self, value: T) -> Entry<T> {
128        let id = self.0.next_row.get();
129        self.0
130            .next_row
131            .set(id.checked_add(1).expect("model row identity exhausted"));
132        Entry { id, value }
133    }
134
135    /// A stable identity that survives edits, inserts, removes of other rows, and sorting.
136    pub fn row_key(&self, index: usize) -> Option<RowKey> {
137        self.0.structure.track();
138        self.0.rows.borrow().get(index).map(|entry| RowKey {
139            model: self.0.id,
140            row: entry.id,
141            scope: 0,
142        })
143    }
144
145    /// Find a record's current index by its stable identity.
146    pub fn row_index(&self, key: RowKey) -> Option<usize> {
147        self.0.structure.track();
148        self.row_index_untracked(key)
149    }
150
151    pub(crate) fn row_index_untracked(&self, key: RowKey) -> Option<usize> {
152        if key.model != self.0.id {
153            return None;
154        }
155        self.0
156            .rows
157            .borrow()
158            .iter()
159            .position(|entry| entry.id == key.row)
160    }
161
162    pub(crate) fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
163        self.0.structure.track();
164        for entry in &self.0.rows.borrow()[range] {
165            visit(RowKey {
166                model: self.0.id,
167                row: entry.id,
168                scope: 0,
169            });
170        }
171    }
172
173    pub(crate) fn visit_row_data(&self, count: usize, visit: impl FnMut(usize, RowKey, &T)) {
174        self.0.values.track();
175        self.visit_rows_untracked(count, visit);
176    }
177
178    /// Borrow the rows after the caller has established the appropriate dependencies.
179    pub(crate) fn visit_rows_untracked(
180        &self,
181        count: usize,
182        mut visit: impl FnMut(usize, RowKey, &T),
183    ) {
184        for (index, entry) in self.0.rows.borrow().iter().take(count).enumerate() {
185            visit(
186                index,
187                RowKey {
188                    model: self.0.id,
189                    row: entry.id,
190                    scope: 0,
191                },
192                &entry.value,
193            );
194        }
195    }
196
197    /// Locate a row after the caller has established the appropriate dependencies.
198    pub(crate) fn position_untracked(
199        &self,
200        range: std::ops::Range<usize>,
201        mut predicate: impl FnMut(&T) -> bool,
202    ) -> Option<usize> {
203        let start = range.start;
204        self.0
205            .rows
206            .borrow()
207            .get(range)?
208            .iter()
209            .position(|entry| predicate(&entry.value))
210            .map(|offset| start + offset)
211    }
212
213    pub(crate) fn project_row_untracked<R>(
214        &self,
215        index: usize,
216        project: impl FnOnce(&T) -> R,
217    ) -> Option<R> {
218        self.0
219            .rows
220            .borrow()
221            .get(index)
222            .map(|entry| project(&entry.value))
223    }
224
225    /// Subscribe to changes in the projected value of existing rows. The caller also tracks
226    /// structure changes and keeps the returned signal alive for as long as it uses the projection.
227    pub(crate) fn observe_projection<P: PartialEq>(
228        &self,
229        limit: usize,
230        project: impl Fn(&T) -> P + 'static,
231    ) -> Rc<ChangeSignal> {
232        self.observe_projection_changes(limit, move |_, before, after| {
233            project(before) != project(after)
234        })
235    }
236
237    pub(crate) fn observe_projection_changes(
238        &self,
239        limit: usize,
240        changed: impl Fn(usize, &T, &T) -> bool + 'static,
241    ) -> Rc<ChangeSignal> {
242        let signal = Rc::new(ChangeSignal::default());
243        let mut projections = self.0.projections.borrow_mut();
244        projections.retain(|projection| projection.signal.strong_count() != 0);
245        projections.push(RowProjection {
246            signal: Rc::downgrade(&signal),
247            limit,
248            changed: Box::new(changed),
249        });
250        signal
251    }
252
253    /// Observe row contents by stable key. Observers run while the model may be borrowed.
254    pub(crate) fn observe_rows(&self, observer: &Rc<RowObserver<T>>) {
255        let mut observers = self.0.row_observers.borrow_mut();
256        observers.retain(|observer| observer.strong_count() != 0);
257        observers.push(Rc::downgrade(observer));
258    }
259
260    fn row_changed(&self, id: u64, value: Option<&T>) {
261        let key = RowKey {
262            model: self.0.id,
263            row: id,
264            scope: 0,
265        };
266        self.0.row_observers.borrow_mut().retain(|observer| {
267            if let Some(observer) = observer.upgrade() {
268                observer(key, value);
269                true
270            } else {
271                false
272            }
273        });
274    }
275
276    pub(crate) fn row_lifetime(&self, key: RowKey) -> RowLifetime {
277        let mut lifetimes = self.0.lifetimes.borrow_mut();
278        RowLifetime(Some(Rc::downgrade(lifetimes.entry(key.row).or_default())))
279    }
280
281    pub(crate) fn structure_stamp(&self) -> (u64, u64) {
282        self.0.structure.track();
283        (self.0.id, self.0.revision.get())
284    }
285
286    /// Identify the exact model contents and order seen by an asynchronous edit.
287    #[doc(hidden)]
288    pub fn edit_stamp(&self) -> (u64, u64) {
289        (self.0.id, self.0.edit_revision.get())
290    }
291
292    pub(crate) fn contents_stamp(&self) -> (u64, u64) {
293        self.0.values.track();
294        self.edit_stamp()
295    }
296
297    pub fn len(&self) -> usize {
298        self.0.count.track();
299        self.0.rows.borrow().len()
300    }
301
302    pub fn is_empty(&self) -> bool {
303        self.len() == 0
304    }
305
306    pub fn push(&self, value: T) {
307        let index = {
308            let mut rows = self.0.rows.borrow_mut();
309            let index = rows.len();
310            let entry = self.entry(value);
311            self.row_changed(entry.id, Some(&entry.value));
312            rows.push(entry);
313            index
314        };
315        self.structure_changed(index, true);
316    }
317
318    /// Insert at a model index. An index beyond the end leaves the model unchanged.
319    pub fn insert(&self, index: usize, value: T) -> bool {
320        {
321            let mut rows = self.0.rows.borrow_mut();
322            if index > rows.len() {
323                return false;
324            }
325            let entry = self.entry(value);
326            self.row_changed(entry.id, Some(&entry.value));
327            rows.insert(index, entry);
328        }
329        self.structure_changed(index, true);
330        true
331    }
332
333    pub fn remove(&self, index: usize) -> Option<T> {
334        let removed = {
335            let mut rows = self.0.rows.borrow_mut();
336            if index >= rows.len() {
337                return None;
338            }
339            rows.remove(index)
340        };
341        self.row_changed(removed.id, None);
342        self.0.lifetimes.borrow_mut().remove(&removed.id);
343        self.structure_changed(index, true);
344        Some(removed.value)
345    }
346
347    pub(crate) fn sorted_indices_untracked(
348        &self,
349        limit: usize,
350        compare: impl FnMut(&T, &T) -> Comparison,
351    ) -> Vec<usize> {
352        self.projected_indices_untracked(limit, None, |_| true, Some(compare))
353    }
354
355    pub(crate) fn projected_indices_untracked(
356        &self,
357        limit: usize,
358        base_order: Option<&[usize]>,
359        include: impl Fn(&T) -> bool,
360        compare: Option<impl FnMut(&T, &T) -> Comparison>,
361    ) -> Vec<usize> {
362        let rows = self.0.rows.borrow();
363        let mut order: Vec<_> = (0..rows.len().min(limit))
364            .map(|index| base_order.map_or(index, |order| order[index]))
365            .filter(|&index| include(&rows[index].value))
366            .collect();
367        if let Some(mut compare) = compare {
368            order.sort_by(|&a, &b| compare(&rows[a].value, &rows[b].value));
369        }
370        order
371    }
372
373    /// Stably reorder rows, retaining their keys and delegate lifetimes.
374    pub fn sort_by(&self, compare: impl FnMut(&T, &T) -> Comparison) -> bool {
375        let order = self.sorted_indices_untracked(usize::MAX, compare);
376        let Some(first_changed) = order.iter().enumerate().position(|(new, old)| new != *old)
377        else {
378            return false;
379        };
380        {
381            let mut rows = self.0.rows.borrow_mut();
382            let mut source: Vec<_> = rows.drain(first_changed..).map(Some).collect();
383            rows.extend(order.into_iter().skip(first_changed).map(|index| {
384                source[index - first_changed]
385                    .take()
386                    .expect("sort permutation contains each row once")
387            }));
388        }
389        self.structure_changed(first_changed, false);
390        true
391    }
392
393    fn structure_changed(&self, index: usize, count_changed: bool) {
394        self.0.revision.set(self.0.revision.get().wrapping_add(1));
395        // Notify readers before discarding signals for indices whose rows have shifted.
396        let shifted = self.0.row_signals.borrow_mut().signals.split_off(&index);
397        for signal in shifted.into_values() {
398            signal.notify();
399        }
400        if count_changed {
401            self.0.count.notify();
402        }
403        self.0.structure.notify();
404        self.values_changed();
405    }
406
407    fn values_changed(&self) {
408        self.0
409            .edit_revision
410            .set(self.0.edit_revision.get().wrapping_add(1));
411        self.0.values.notify();
412    }
413}
414
415impl<T> VecModel<T> {
416    pub(crate) fn project_row<R>(&self, index: usize, project: impl FnOnce(&T) -> R) -> Option<R> {
417        let rows = self.0.rows.borrow();
418        if let Some(entry) = rows.get(index) {
419            if ChangeSignal::is_tracking() {
420                self.0.row_signals.borrow_mut().track(index);
421            }
422            Some(project(&entry.value))
423        } else {
424            self.0.count.track();
425            None
426        }
427    }
428}
429
430impl<T: Clone> VecModel<T> {
431    pub fn row(&self, index: usize) -> Option<T> {
432        self.project_row(index, T::clone)
433    }
434
435    pub fn snapshot(&self) -> Vec<T> {
436        self.0.values.track();
437        self.snapshot_untracked()
438    }
439
440    /// Copy rows that the caller has already sampled from the live model.
441    #[doc(hidden)]
442    pub fn snapshot_untracked(&self) -> Vec<T> {
443        self.0
444            .rows
445            .borrow()
446            .iter()
447            .map(|entry| entry.value.clone())
448            .collect()
449    }
450
451    /// Transfer an owned model's rows at a by-value boundary. A shared model
452    /// still needs a tracked read because its other owners can edit it.
453    #[doc(hidden)]
454    pub fn into_snapshot(self) -> Vec<T> {
455        match Rc::try_unwrap(self.0) {
456            Ok(data) => data
457                .rows
458                .into_inner()
459                .into_iter()
460                .map(|entry| entry.value)
461                .collect(),
462            Err(data) => Self(data).snapshot(),
463        }
464    }
465}
466
467impl<T: PartialEq> VecModel<T> {
468    /// Commit a value against the row and value observed by an editor.
469    pub fn set_row_if_current(&self, index: usize, key: RowKey, expected: &T, value: T) -> bool {
470        self.update_row_if_key(index, key, |current| (current == expected).then_some(value))
471    }
472
473    /// Update an identified record from its latest value. Returning None declines the edit.
474    pub fn update_row_if_key(
475        &self,
476        index: usize,
477        key: RowKey,
478        update: impl FnOnce(&T) -> Option<T>,
479    ) -> bool {
480        let next = {
481            let rows = self.0.rows.borrow();
482            let Some(entry) = rows
483                .get(index)
484                .filter(|entry| key.model == self.0.id && entry.id == key.row)
485            else {
486                return false;
487            };
488            update(&entry.value)
489        };
490        next.is_some_and(|value| self.set_row(index, value))
491    }
492
493    /// Replace one row. Returns false for an invalid index or equal value.
494    pub fn set_row(&self, index: usize, value: T) -> bool {
495        let mut value = value;
496        let changed = {
497            let mut rows = self.0.rows.borrow_mut();
498            let Some(current) = rows.get_mut(index) else {
499                return false;
500            };
501            self.swap_row(index, current, &mut value)
502        };
503        if changed {
504            self.values_changed();
505        }
506        changed
507    }
508
509    pub(crate) fn replace_rows_if_current(
510        &self,
511        stamp: (u64, u64),
512        mut values: Vec<(usize, T)>,
513    ) -> bool {
514        if self.edit_stamp() != stamp {
515            return false;
516        }
517        let mut rows = self.0.rows.borrow_mut();
518        if values.iter().any(|(index, _)| *index >= rows.len()) {
519            return false;
520        }
521        let mut changed = false;
522        for (index, value) in &mut values {
523            changed |= self.swap_row(*index, &mut rows[*index], value);
524        }
525        drop(rows);
526        if changed {
527            self.values_changed();
528        }
529        changed
530    }
531
532    fn swap_row(&self, index: usize, entry: &mut Entry<T>, next: &mut T) -> bool {
533        if &entry.value == next {
534            return false;
535        }
536        self.0.projections.borrow_mut().retain(|projection| {
537            let Some(signal) = projection.signal.upgrade() else {
538                return false;
539            };
540            if index < projection.limit && (projection.changed)(index, &entry.value, next) {
541                signal.notify();
542            }
543            true
544        });
545        std::mem::swap(&mut entry.value, next);
546        self.row_changed(entry.id, Some(&entry.value));
547        if let Some(signal) = self.0.row_signals.borrow().signals.get(&index) {
548            signal.notify();
549        }
550        true
551    }
552
553    /// Compare the current values, independently of handle identity.
554    pub fn values_eq(&self, other: &Self) -> bool {
555        self.compare_values(other, |model| model.0.values.track())
556    }
557
558    /// Compare expression operands, tracking only models that can outlive
559    /// the comparison and be changed by another owner.
560    #[doc(hidden)]
561    pub fn values_eq_owned(self, other: Self) -> bool {
562        self.compare_values(&other, |model| {
563            if model.is_shared() {
564                model.0.values.track();
565            }
566        })
567    }
568
569    fn compare_values(&self, other: &Self, track: impl Fn(&Self)) -> bool {
570        if self == other {
571            return true;
572        }
573        track(self);
574        track(other);
575        self.0.rows.borrow().iter().map(|row| &row.value).eq(other
576            .0
577            .rows
578            .borrow()
579            .iter()
580            .map(|row| &row.value))
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587    use crate::Property;
588    use std::cell::Cell;
589
590    #[test]
591    fn sorting_retains_stable_keys_and_invalidates_only_affected_reads() {
592        let model = VecModel::from(vec![(0, 'a'), (2, 'b'), (1, 'c'), (2, 'd')]);
593        let keys: Vec<_> = (0..4).map(|index| model.row_key(index).unwrap()).collect();
594        let lifetime = model.row_lifetime(keys[2]);
595        let len = Property::default();
596        let first = Property::default();
597        let second = Property::default();
598        let count_reads = Cell::new(0);
599        let prefix_reads = Cell::new(0);
600        let count = || {
601            len.get(|| {
602                count_reads.set(count_reads.get() + 1);
603                model.len()
604            })
605        };
606        let prefix = || {
607            first.get(|| {
608                prefix_reads.set(prefix_reads.get() + 1);
609                model.row(0)
610            })
611        };
612        let row = || second.get(|| model.row(1));
613        assert_eq!(
614            (count(), prefix(), row()),
615            (4, Some((0, 'a')), Some((2, 'b')))
616        );
617        assert!(model.sort_by(|a, b| a.0.cmp(&b.0)));
618        assert_eq!(
619            (count(), prefix(), row()),
620            (4, Some((0, 'a')), Some((1, 'c')))
621        );
622        assert_eq!((count_reads.get(), prefix_reads.get()), (1, 1));
623        assert_eq!(model.snapshot(), [(0, 'a'), (1, 'c'), (2, 'b'), (2, 'd')]);
624        assert_eq!(model.row_key(1), Some(keys[2]));
625        assert_eq!(model.row_key(2), Some(keys[1]));
626        assert_eq!(model.row_key(3), Some(keys[3]));
627        assert!(lifetime.is_live(keys[2], model.structure_stamp().0, 4));
628        assert!(!model.sort_by(|a, b| a.0.cmp(&b.0)));
629    }
630
631    #[test]
632    fn watched_model_rows_survive_pruning_and_detect_shifts() {
633        use crate::property::watch_reads;
634
635        let model = VecModel::from((0..128).collect::<Vec<_>>());
636        watch_reads(|reads| {
637            for index in 0..100 {
638                assert_eq!(model.row(index), Some(index));
639            }
640            assert!(model.set_row(120, 0));
641            assert!(!reads.changed());
642            assert!(model.set_row(0, 120));
643            assert!(reads.changed());
644        });
645        watch_reads(|reads| {
646            assert_eq!(model.row(1), Some(1));
647            assert_eq!(model.remove(0), Some(120));
648            assert!(reads.changed());
649        });
650    }
651
652    #[test]
653    fn consuming_snapshot_tracks_only_models_with_a_live_owner() {
654        let temporary = Property::default();
655        assert_eq!(
656            temporary.get(|| VecModel::from(vec![1]).into_snapshot()),
657            [1]
658        );
659        assert!(!temporary.is_dirty());
660
661        let shared = VecModel::from(vec![2]);
662        let snapshot = Property::default();
663        let read = || snapshot.get(|| shared.clone().into_snapshot());
664        assert_eq!(read(), [2]);
665        assert!(!snapshot.is_dirty());
666        assert!(shared.set_row(0, 3));
667        assert!(snapshot.is_dirty());
668        assert_eq!(read(), [3]);
669    }
670
671    #[test]
672    fn model_tracks_rows_length_and_snapshots_independently() {
673        let model = VecModel::from(vec![10, 20, 30]);
674        let count = Property::default();
675        let second = Property::default();
676        let missing = Property::default();
677        let snapshot = Property::default();
678        let reads = Cell::new(0);
679        let len = || {
680            count.get(|| {
681                reads.set(reads.get() + 1);
682                model.len()
683            })
684        };
685        let row = || second.get(|| model.row(1));
686        let tail = || missing.get(|| model.row(3));
687        let values = || snapshot.get(|| model.snapshot());
688
689        assert_eq!((len(), row(), tail()), (3, Some(20), None));
690        assert_eq!(values(), [10, 20, 30]);
691        assert!(model.set_row(0, 11));
692        assert_eq!((len(), row()), (3, Some(20)));
693        assert_eq!(reads.get(), 1);
694        assert_eq!(values(), [11, 20, 30]);
695        assert!(!model.set_row(0, 11));
696        assert!(!model.set_row(9, 11));
697        model.push(40);
698        assert_eq!((len(), row(), tail()), (4, Some(20), Some(40)));
699        assert!(model.insert(0, 5));
700        assert_eq!((len(), row(), tail()), (5, Some(11), Some(30)));
701        assert_eq!(model.remove(0), Some(5));
702        assert_eq!((len(), row(), tail()), (4, Some(20), Some(40)));
703    }
704}