Skip to main content

glory_ui/list/
cache.rs

1use std::collections::{HashMap, HashSet};
2use std::hash::Hash;
3use std::ops::Range;
4
5use super::Error;
6
7/// A runtime adapter supplies indexed data access and owns row mounting. `key`
8/// must be O(1) or O(log n), and keys must be globally stable/unique. Validation
9/// checks the current window only, avoiding an O(n) scan on every scroll.
10pub trait RowHost {
11    type Key: Clone + Eq + Hash;
12    type Row;
13    fn key(&mut self, index: usize) -> Self::Key;
14    fn mount(&mut self, index: usize, key: &Self::Key) -> Self::Row;
15    /// Refresh an existing row after a data revision or its index changes.
16    fn update(&mut self, index: usize, key: &Self::Key, row: &mut Self::Row);
17    fn place(&mut self, row: &Self::Row, before: Option<&Self::Row>);
18    /// Empty logical widgets do not provide a physical insertion anchor.
19    fn has_content(&self, _row: &Self::Row) -> bool {
20        true
21    }
22    fn dispose(&mut self, row: Self::Row);
23}
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub struct ReconcileStats {
27    pub keys_read: usize,
28    pub created: usize,
29    pub updated: usize,
30    pub moved: usize,
31    pub disposed: usize,
32}
33
34#[derive(Debug)]
35struct Entry<Row> {
36    index: usize,
37    // Position in the last committed window, independent of the source index.
38    // Kept with the live row instead of cloning every key into a temporary map.
39    order: usize,
40    row: Row,
41}
42
43struct Next<Key> {
44    index: usize,
45    key: Key,
46    old: Option<usize>,
47}
48
49/// Owns the mounted window plus an optional single pin. Other leaving rows are
50/// disposed immediately. The widget adapter resolves the focused stable key;
51/// this is not a keep-alive cache of every row ever visited.
52#[derive(Debug)]
53pub struct Cache<Key, Row> {
54    rows: HashMap<Key, Entry<Row>>,
55    order: Vec<Key>,
56    range: Range<usize>,
57    revision: Option<u64>,
58    pin: Option<(usize, Key)>,
59}
60
61impl<Key: Clone + Eq + Hash, Row> Default for Cache<Key, Row> {
62    fn default() -> Self {
63        Self {
64            rows: HashMap::new(),
65            order: Vec::new(),
66            range: 0..0,
67            revision: None,
68            pin: None,
69        }
70    }
71}
72
73impl<Key: Clone + Eq + Hash, Row> Cache<Key, Row> {
74    pub fn len(&self) -> usize {
75        self.rows.len()
76    }
77    pub fn is_empty(&self) -> bool {
78        self.rows.is_empty()
79    }
80    pub fn row(&self, key: &Key) -> Option<&Row> {
81        self.rows.get(key).map(|entry| &entry.row)
82    }
83    pub fn order(&self) -> &[Key] {
84        &self.order
85    }
86
87    pub fn reconcile(
88        &mut self,
89        range: Range<usize>,
90        revision: u64,
91        host: &mut impl RowHost<Key = Key, Row = Row>,
92    ) -> Result<ReconcileStats, Error> {
93        self.reconcile_pinned(range, revision, None, host)
94    }
95
96    /// Reconcile the window plus at most one indexed stable key. The caller
97    /// resolves/validates the pin without scanning the source. It is part of
98    /// the same order/LIS reconciliation, never a separate historical cache.
99    pub fn reconcile_pinned(
100        &mut self,
101        range: Range<usize>,
102        revision: u64,
103        pin: Option<(usize, Key)>,
104        host: &mut impl RowHost<Key = Key, Row = Row>,
105    ) -> Result<ReconcileStats, Error> {
106        if range.start > range.end {
107            return Err(Error::InvalidRange);
108        }
109        if self.range == range && self.revision == Some(revision) && self.pin == pin {
110            return Ok(ReconcileStats::default());
111        }
112        let extra = usize::from(
113            pin.as_ref()
114                .is_some_and(|(index, _)| !range.contains(index)),
115        );
116        let requested = range.len().checked_add(extra).ok_or(Error::Allocation)?;
117        let mut next = Vec::new();
118        next.try_reserve(requested).map_err(|_| Error::Allocation)?;
119        let mut keys = HashSet::new();
120        keys.try_reserve(requested).map_err(|_| Error::Allocation)?;
121        for index in range.clone() {
122            let key = host.key(index);
123            if !keys.insert(key.clone()) {
124                return Err(Error::DuplicateKey);
125            }
126            let old = self.rows.get(&key).map(|entry| entry.order);
127            next.push(Next { index, key, old });
128        }
129        if let Some((index, key)) = &pin {
130            if range.contains(index) {
131                if next[index - range.start].key != *key {
132                    return Err(Error::InvalidLookup);
133                }
134            } else {
135                if !keys.insert(key.clone()) {
136                    return Err(Error::DuplicateKey);
137                }
138                let row = Next {
139                    index: *index,
140                    key: key.clone(),
141                    old: self.rows.get(key).map(|entry| entry.order),
142                };
143                if *index < range.start {
144                    next.insert(0, row);
145                } else {
146                    next.push(row);
147                }
148            }
149        }
150        // All key validation precedes side effects on mounted instances.
151        // Ordinary scrolls, distant seeks, insertions and deletions retain row
152        // order. Only a real inversion needs the LIS allocations and search.
153        let mut previous = None;
154        let reordered = next.iter().filter_map(|row| row.old).any(|old| {
155            let inverted = previous.is_some_and(|previous| previous >= old);
156            previous = Some(old);
157            inverted
158        });
159        let stable = reordered.then(|| {
160            let positions: Vec<_> = next.iter().map(|row| row.old).collect();
161            stable_positions(&positions)
162        });
163        let mut stats = ReconcileStats {
164            keys_read: range.len(),
165            ..ReconcileStats::default()
166        };
167        for key in &self.order {
168            if !keys.contains(key) {
169                host.dispose(self.rows.remove(key).expect("mounted key").row);
170                stats.disposed += 1;
171            }
172        }
173        let changed = self.revision != Some(revision);
174        for (order, Next { index, key, .. }) in next.iter().enumerate() {
175            if let Some(entry) = self.rows.get_mut(key) {
176                if changed || entry.index != *index {
177                    host.update(*index, key, &mut entry.row);
178                    entry.index = *index;
179                    stats.updated += 1;
180                }
181                entry.order = order;
182            } else {
183                let row = host.mount(*index, key);
184                self.rows.insert(
185                    key.clone(),
186                    Entry {
187                        index: *index,
188                        order,
189                        row,
190                    },
191                );
192                stats.created += 1;
193            }
194        }
195        if stats.created != 0 || reordered {
196            let mut before = None;
197            for i in (0..next.len()).rev() {
198                if next[i].old.is_none() || stable.as_ref().is_some_and(|stable| !stable[i]) {
199                    let anchor = before.map(|index: usize| &self.rows[&next[index].key].row);
200                    host.place(&self.rows[&next[i].key].row, anchor);
201                    if next[i].old.is_some() {
202                        stats.moved += 1;
203                    }
204                }
205                if host.has_content(&self.rows[&next[i].key].row) {
206                    before = Some(i);
207                }
208            }
209        }
210        self.order = next.into_iter().map(|next| next.key).collect();
211        self.range = range;
212        self.revision = Some(revision);
213        self.pin = pin;
214        Ok(stats)
215    }
216
217    pub fn clear(&mut self, host: &mut impl RowHost<Key = Key, Row = Row>) {
218        for key in self.order.drain(..) {
219            host.dispose(self.rows.remove(&key).expect("mounted key").row);
220        }
221        self.range = 0..0;
222        self.revision = None;
223        self.pin = None;
224    }
225}
226
227/// Mark a longest increasing subsequence of retained old positions. This keeps
228/// window shifts free of moves, while minimizing moves on actual data reorder.
229fn stable_positions(positions: &[Option<usize>]) -> Vec<bool> {
230    let mut tails: Vec<usize> = Vec::new();
231    let mut previous = vec![None; positions.len()];
232    for (i, position) in positions.iter().enumerate() {
233        let Some(position) = position else { continue };
234        let at =
235            tails.partition_point(|tail| positions[*tail].expect("retained position") < *position);
236        if at > 0 {
237            previous[i] = Some(tails[at - 1]);
238        }
239        if at == tails.len() {
240            tails.push(i);
241        } else {
242            tails[at] = i;
243        }
244    }
245    let mut stable = vec![false; positions.len()];
246    let mut cursor = tails.last().copied();
247    while let Some(i) = cursor {
248        stable[i] = true;
249        cursor = previous[i];
250    }
251    stable
252}