Skip to main content

devpage_design/tree/
mod.rs

1//! A scene's tree as a tree: each node's identity, its place among its
2//! siblings, and the index that finds a node by its identity. Nothing here
3//! knows what a node draws.
4
5use std::collections::BTreeMap;
6use std::fmt;
7
8/// A node's identity: where it came from — the element ids from the design's
9/// root through each instance down to the element that made it. It survives
10/// every edit that keeps the element: an insert before it, a sibling moved
11/// past it, a line added above it.
12#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
13pub struct NodeId(pub Vec<u32>);
14
15impl fmt::Debug for NodeId {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        write!(f, "{self}")
18    }
19}
20
21impl fmt::Display for NodeId {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        let parts: Vec<String> = self.0.iter().map(u32::to_string).collect();
24        f.write_str(&parts.join("/"))
25    }
26}
27
28/// A node's place among its siblings: a key that sorts between its
29/// neighbours', chosen when it is placed, so a node placed anywhere — before
30/// the first of 100,000 — takes a key of its own and renumbers none. Its
31/// digits are bytes compared in order; the last is never zero, so there is
32/// always room between two keys.
33#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct OrderKey(Box<[u8]>);
35
36impl fmt::Debug for OrderKey {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "{:02x?}", self.0)
39    }
40}
41
42impl OrderKey {
43    /// The `i`th of `n` keys spread evenly, in order — for siblings placed
44    /// all at once.
45    pub fn nth(i: usize, n: usize) -> OrderKey {
46        // As few base-255 digits, 1 to 255, as hold `n` keys.
47        let mut digits = 1;
48        let mut room = 255usize;
49        while room < n {
50            digits += 1;
51            room = room.saturating_mul(255);
52        }
53        let mut v = i;
54        let mut out = vec![0u8; digits];
55        for d in out.iter_mut().rev() {
56            *d = (v % 255) as u8 + 1;
57            v /= 255;
58        }
59        // `i` fits: room ≥ n > i.
60        OrderKey(out.into_boxed_slice())
61    }
62
63    /// A key after `a` — or the first, from nothing — and before `b`, or
64    /// with nothing after it.
65    pub fn between(a: Option<&OrderKey>, b: Option<&OrderKey>) -> OrderKey {
66        let a: &[u8] = a.map_or(&[], |k| &k.0);
67        let mut b: Option<&[u8]> = b.map(|k| &*k.0);
68        let mut out = Vec::new();
69        let mut i = 0;
70        loop {
71            let da = a.get(i).copied().unwrap_or(0) as u16;
72            let db = match b {
73                // `a < b`, so while their digits agree `b` has more.
74                Some(b) => b.get(i).copied().unwrap_or(0) as u16,
75                None => 256,
76            };
77            if db > da + 1 {
78                out.push(((da + db) / 2) as u8);
79                return OrderKey(out.into_boxed_slice());
80            }
81            out.push(da as u8);
82            if db == da + 1 {
83                // Anything after `a`'s digits here is below `b`.
84                b = None;
85            }
86            i += 1;
87        }
88    }
89}
90
91/// A node's children in order, each under its order key.
92#[derive(Clone, Default)]
93pub struct Children<T>(BTreeMap<OrderKey, T>);
94
95impl<T: fmt::Debug> fmt::Debug for Children<T> {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.debug_list().entries(self.0.values()).finish()
98    }
99}
100
101/// Two lists of children are the same when they hold the same nodes in the
102/// same order, whatever keys placed them.
103impl<T: PartialEq> PartialEq for Children<T> {
104    fn eq(&self, other: &Self) -> bool {
105        self.0.len() == other.0.len() && self.0.values().eq(other.0.values())
106    }
107}
108
109impl<T> Children<T> {
110    pub fn new() -> Self {
111        Children(BTreeMap::new())
112    }
113
114    /// Children placed all at once, keys spread evenly.
115    pub fn from_vec(nodes: Vec<T>) -> Self {
116        let n = nodes.len();
117        Children(
118            nodes
119                .into_iter()
120                .enumerate()
121                .map(|(i, t)| (OrderKey::nth(i, n), t))
122                .collect(),
123        )
124    }
125
126    pub fn len(&self) -> usize {
127        self.0.len()
128    }
129
130    pub fn is_empty(&self) -> bool {
131        self.0.is_empty()
132    }
133
134    /// The children in order.
135    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + ExactSizeIterator {
136        self.0.values()
137    }
138
139    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + ExactSizeIterator {
140        self.0.values_mut()
141    }
142
143    /// The children in order, with their keys.
144    pub fn entries(&self) -> impl DoubleEndedIterator<Item = (&OrderKey, &T)> {
145        self.0.iter()
146    }
147
148    pub fn get(&self, key: &OrderKey) -> Option<&T> {
149        self.0.get(key)
150    }
151
152    pub fn get_mut(&mut self, key: &OrderKey) -> Option<&mut T> {
153        self.0.get_mut(key)
154    }
155
156    /// The child `at` places from the first, counting each one before it:
157    /// for tests, and for callers that hold a place, not a key.
158    pub fn nth(&self, at: usize) -> Option<&T> {
159        self.0.values().nth(at)
160    }
161
162    /// The child `at` places from the first, to change.
163    pub fn nth_mut(&mut self, at: usize) -> Option<&mut T> {
164        self.0.values_mut().nth(at)
165    }
166
167    pub fn first_key(&self) -> Option<&OrderKey> {
168        self.0.keys().next()
169    }
170
171    pub fn last_key(&self) -> Option<&OrderKey> {
172        self.0.keys().next_back()
173    }
174
175    /// The key of the child after the one under `key`, if any.
176    pub fn key_after(&self, key: &OrderKey) -> Option<&OrderKey> {
177        use std::ops::Bound::{Excluded, Unbounded};
178        self.0
179            .range((Excluded(key), Unbounded))
180            .next()
181            .map(|(k, _)| k)
182    }
183
184    /// The key of the child before the one under `key`, if any.
185    pub fn key_before(&self, key: &OrderKey) -> Option<&OrderKey> {
186        self.0.range(..key).next_back().map(|(k, _)| k)
187    }
188
189    /// Places `t` last, and returns its key.
190    pub fn push(&mut self, t: T) -> OrderKey {
191        let key = OrderKey::between(self.last_key(), None);
192        self.0.insert(key.clone(), t);
193        key
194    }
195
196    /// Places `t` right after the child under `after`, or first when `None`,
197    /// and returns its key.
198    pub fn insert_after(&mut self, after: Option<&OrderKey>, t: T) -> OrderKey {
199        let next = match after {
200            Some(a) => self.key_after(a).cloned(),
201            None => self.first_key().cloned(),
202        };
203        let key = OrderKey::between(after, next.as_ref());
204        self.0.insert(key.clone(), t);
205        key
206    }
207
208    /// Places `t` under `key`, which no child has: where it was taken from.
209    pub fn put(&mut self, key: OrderKey, t: T) {
210        self.0.insert(key, t);
211    }
212
213    pub fn remove(&mut self, key: &OrderKey) -> Option<T> {
214        self.0.remove(key)
215    }
216
217    pub fn clear(&mut self) {
218        self.0.clear()
219    }
220
221    /// How many children come before the one under `key`: its place.
222    pub fn rank(&self, key: &OrderKey) -> usize {
223        self.0.range(..key).count()
224    }
225}
226
227impl<'a, T> IntoIterator for &'a Children<T> {
228    type Item = &'a T;
229    type IntoIter = std::collections::btree_map::Values<'a, OrderKey, T>;
230    fn into_iter(self) -> Self::IntoIter {
231        self.0.values()
232    }
233}
234
235impl<T> std::ops::Index<usize> for Children<T> {
236    type Output = T;
237    fn index(&self, at: usize) -> &T {
238        self.nth(at).expect("a child at that place")
239    }
240}
241
242impl<T> FromIterator<T> for Children<T> {
243    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
244        Children::from_vec(iter.into_iter().collect())
245    }
246}
247
248/// Where a node is in a tree: the order keys from the root down to it — the
249/// root's is empty. Sorted, these are the nodes in tree order: a node before
250/// its children, children in order.
251pub type Order = Vec<OrderKey>;
252
253/// A node of a tree, as far as its shape goes.
254pub trait Node: Sized {
255    fn id(&self) -> &NodeId;
256    fn children(&self) -> &Children<Self>;
257}
258
259/// Where each node of a tree is, by its id.
260#[derive(Clone, Debug, Default)]
261pub struct Ids(std::collections::HashMap<NodeId, Order>);
262
263impl Ids {
264    /// Every node of the tree under `root`.
265    pub fn of<N: Node>(root: &N) -> Ids {
266        let mut ids = Ids::default();
267        ids.add(root, Vec::new());
268        ids
269    }
270
271    /// `n` and the nodes under it, `n` at `order`.
272    pub fn add<N: Node>(&mut self, n: &N, order: Order) {
273        for (k, c) in n.children().entries() {
274            let mut o = order.clone();
275            o.push(k.clone());
276            self.add(c, o);
277        }
278        self.0.insert(n.id().clone(), order);
279    }
280
281    /// Forgets `n` and the nodes under it.
282    pub fn remove<N: Node>(&mut self, n: &N) {
283        self.0.remove(n.id());
284        for c in n.children() {
285            self.remove(c);
286        }
287    }
288
289    pub fn get(&self, id: &NodeId) -> Option<&Order> {
290        self.0.get(id)
291    }
292
293    pub fn contains(&self, id: &NodeId) -> bool {
294        self.0.contains_key(id)
295    }
296
297    pub fn len(&self) -> usize {
298        self.0.len()
299    }
300
301    pub fn is_empty(&self) -> bool {
302        self.0.is_empty()
303    }
304}
305
306#[cfg(test)]
307mod tests;