Skip to main content

flow_value/
collection.rs

1//! `List`, `Dict` and `Set` (`data.md`).
2//!
3//! # What each costs
4//!
5//! A [`List`] is up to [`EDGE`] elements at its front, a window onto a
6//! balanced tree of chunks of elements shared between every list made from
7//! it (the `tree` module), and up to [`EDGE`] elements at its back. A list of
8//! at most [`EDGE`] elements has no tree. For a list of `n` elements, indexing
9//! costs O(log n); taking a contiguous part — the `[x, ..rest]` and
10//! `[..init, last]` patterns — costs O(EDGE) and shares the whole tree;
11//! growing at either end costs O(EDGE) amortized and leaves the tree as it
12//! was until an end holds [`EDGE`], when those move into the tree as one
13//! leaf in O(log n); joining two lists costs O(log n + EDGE). None of these
14//! copies a tree node another value still holds, so a list grown from a
15//! stored one shares every node of it: what history stores for the grown
16//! list is its ends and the nodes that differ (`trace.md`, *Lists*). Growing
17//! or joining a part first cuts the tree down to it, in O(log n), so only a
18//! part kept alive as it is keeps its whole tree alive.
19//!
20//! A [`Dict`] keeps its entries and a [`Set`] its members in key order in
21//! the same kind of tree, and inserting or removing copies only the path to
22//! the element. Looking up costs logarithmic time.
23//!
24//! None of this is observable: `data.md` leaves a representation to the
25//! implementation, and two equal values behave equally in every operation.
26
27use std::cmp::Ordering;
28use std::sync::Arc;
29
30use crate::error::{DataError, StructureError};
31use crate::int::Int;
32use crate::tree::{self, CHUNK, Keyed, Measure, Member, Node, Tree};
33use crate::value::{Meta, Value, compare};
34
35/// The most elements a list keeps at either end, outside its tree.
36pub(crate) const EDGE: usize = CHUNK;
37
38/// The elements at one end of a list, outside its tree: at most [`EDGE`],
39/// shared between lists until one of them changes its end.
40#[derive(Clone, Debug, Default)]
41#[expect(
42    clippy::rc_buffer,
43    reason = "an end grows and shrinks in place through `Arc::make_mut` while no other list holds it"
44)]
45pub(crate) struct End(Option<Arc<Vec<Value>>>);
46
47impl End {
48    fn of(items: Vec<Value>) -> End {
49        End((!items.is_empty()).then(|| Arc::new(items)))
50    }
51
52    pub(crate) fn as_slice(&self) -> &[Value] {
53        self.0.as_deref().map_or(&[], Vec::as_slice)
54    }
55
56    pub(crate) fn len(&self) -> usize {
57        self.as_slice().len()
58    }
59
60    pub(crate) fn is_empty(&self) -> bool {
61        self.0.is_none()
62    }
63
64    /// What tells these elements apart from every other end alive: 0 for
65    /// none.
66    fn id(&self) -> usize {
67        self.0.as_ref().map_or(0, |items| Arc::as_ptr(items).addr())
68    }
69
70    /// The elements, owned: moved out when nothing else holds them.
71    fn take(&mut self) -> Vec<Value> {
72        self.0.take().map(Arc::unwrap_or_clone).unwrap_or_default()
73    }
74
75    /// The elements to change in place, copied first if another list holds
76    /// them.
77    fn items(&mut self) -> &mut Vec<Value> {
78        Arc::make_mut(
79            self.0
80                .get_or_insert_with(|| Arc::new(Vec::with_capacity(EDGE))),
81        )
82    }
83
84    /// The elements dropping this end would drop.
85    fn unshared(&mut self) -> impl Iterator<Item = &mut Value> {
86        self.0.as_mut().and_then(Arc::get_mut).into_iter().flatten()
87    }
88}
89
90/// Dropping a list drops its ends and the nodes of its tree that nothing else
91/// holds, and hands the elements in them to `dismantle` in the value module,
92/// so a deep value drops without deep recursion.
93impl Drop for List {
94    fn drop(&mut self) {
95        crate::value::dismantle(self.unshared_parts());
96    }
97}
98
99/// A list: a finite sequence, in order.
100#[derive(Clone, Debug)]
101pub struct List {
102    /// The elements before the tree's, at most [`EDGE`].
103    pub(crate) front: End,
104    /// The tree the middle elements lie in, which may hold more: a part of a
105    /// list shares the tree of the list it was cut from.
106    pub(crate) root: Option<Tree>,
107    /// Where in the tree the middle elements start.
108    pub(crate) start: usize,
109    /// How many elements the list takes from the tree.
110    pub(crate) middle: usize,
111    /// The elements after the tree's, at most [`EDGE`].
112    pub(crate) back: End,
113    /// What its elements measure, exactly.
114    pub(crate) meta: Meta,
115}
116
117impl Default for List {
118    fn default() -> Self {
119        List::of(End::default(), None, End::default(), Meta::EMPTY)
120    }
121}
122
123impl List {
124    /// Returns the empty list.
125    pub fn new() -> Self {
126        List::default()
127    }
128
129    /// Returns `front`, then all of `tree`'s elements, then `back`, measuring
130    /// `meta`. A list of at most [`EDGE`] elements is moved to its back.
131    fn of(front: End, tree: Option<Tree>, back: End, meta: Meta) -> List {
132        let middle = tree.as_ref().map_or(0, Node::len);
133        let mut list = List {
134            front,
135            root: tree,
136            start: 0,
137            middle,
138            back,
139            meta,
140        };
141        list.settle();
142        list
143    }
144
145    /// Returns `front`, then the `middle` elements of `root` from `start`,
146    /// then `back`, settled and measured exactly.
147    fn window(front: End, root: Option<Node>, start: usize, middle: usize, back: End) -> List {
148        let mut list = List {
149            front,
150            root,
151            start,
152            middle,
153            back,
154            meta: Meta::EMPTY,
155        };
156        list.settle();
157        list.meta = list.measure();
158        list
159    }
160
161    /// Keeps a short list in its back, so a list of at most [`EDGE`]
162    /// elements has no tree and joining one adds to an end.
163    fn settle(&mut self) {
164        if self.middle == 0 {
165            self.root = None;
166            self.start = 0;
167            if !self.front.is_empty() && self.front.len() + self.back.len() <= EDGE {
168                let mut back = self.front.take();
169                back.append(&mut self.back.take());
170                self.back = End::of(back);
171            }
172        } else if self.len() <= EDGE {
173            let items: Vec<Value> = self.iter().cloned().collect();
174            self.front = End::default();
175            self.root = None;
176            self.start = 0;
177            self.middle = 0;
178            self.back = End::of(items);
179        }
180    }
181
182    /// What the elements measure, exactly: the ends' elements and those of
183    /// the window the list takes from its tree, in O(EDGE + log n).
184    fn measure(&self) -> Meta {
185        let ends = Meta::around(self.front.as_slice().iter().chain(self.back.as_slice()));
186        self.root.as_ref().map_or(ends, |root| {
187            ends.join(tree::range_measure(root, self.start, self.middle))
188        })
189    }
190
191    /// Returns what the list is made of: the list is `front`, then the
192    /// elements of `tree` it takes, then `back`.
193    ///
194    /// The front and the back hold at most eight elements each. A list of
195    /// more than eight whose ends do not hold all of it has a tree, and
196    /// one of at most eight has none and holds everything at its back.
197    pub fn parts(&self) -> ListParts<'_> {
198        ListParts {
199            front: self.front.as_slice(),
200            tree: self
201                .root
202                .as_ref()
203                .map(|root| (root, self.start, self.middle)),
204            back: self.back.as_slice(),
205        }
206    }
207
208    /// Returns the whole list as one balanced tree, or `None` when it is
209    /// empty: its front, the elements it takes from its tree and its back,
210    /// joined. The tree shares every node of the list's own that the cut
211    /// and the joins do not pass through, so it costs O(log n) new nodes.
212    pub fn tree(&self) -> Option<Node> {
213        let middle = self.root.clone().and_then(|root| {
214            if self.start == 0 && self.middle == root.len() {
215                Some(root)
216            } else {
217                tree::range(root, self.start, self.middle)
218            }
219        });
220        let end = |items: &[Value]| (!items.is_empty()).then(|| tree::leaf(items.to_vec()));
221        [
222            end(self.front.as_slice()),
223            middle,
224            end(self.back.as_slice()),
225        ]
226        .into_iter()
227        .flatten()
228        .reduce(tree::join)
229    }
230
231    /// Returns the list of `front`, then the `taken` elements of `tree`
232    /// that follow its first `skip`, then `back`, sharing `tree`.
233    ///
234    /// The list's measure is that of its ends and of the window, which the
235    /// tree's nodes record, so this costs O(EDGE + log n) whatever the tree
236    /// holds, but for a list of at most eight elements, which keeps no tree
237    /// and is copied out of it.
238    ///
239    /// # Errors
240    ///
241    /// [`StructureError::End`] when an end holds more than eight elements,
242    /// and [`StructureError::Window`] when the tree does not hold
243    /// `skip + taken` elements.
244    pub fn from_parts(
245        front: Vec<Value>,
246        tree: Option<(Node, usize, usize)>,
247        back: Vec<Value>,
248    ) -> Result<List, StructureError> {
249        if front.len() > EDGE || back.len() > EDGE {
250            return Err(StructureError::End);
251        }
252        let (root, start, middle) = match tree {
253            None => (None, 0, 0),
254            Some((root, skip, taken)) => {
255                let fits = skip.checked_add(taken).is_some_and(|end| end <= root.len());
256                if !fits {
257                    return Err(StructureError::Window);
258                }
259                (Some(root), skip, taken)
260            }
261        };
262        Ok(List::window(
263            End::of(front),
264            root,
265            start,
266            middle,
267            End::of(back),
268        ))
269    }
270
271    /// What tells this list apart from every other list alive: the ends it
272    /// holds, its tree, and the window it takes from that tree.
273    pub(crate) fn id(&self) -> [usize; 5] {
274        [
275            self.front.id(),
276            self.root.as_ref().map_or(0, Node::id),
277            self.start,
278            self.middle,
279            self.back.id(),
280        ]
281    }
282
283    /// Returns how many elements there are.
284    pub fn len(&self) -> usize {
285        self.front.len() + self.middle + self.back.len()
286    }
287
288    /// Returns whether there are none.
289    pub fn is_empty(&self) -> bool {
290        self.len() == 0
291    }
292
293    /// Returns the element at a zero-based position.
294    pub fn get(&self, index: usize) -> Option<&Value> {
295        if let Some(item) = self.front.as_slice().get(index) {
296            return Some(item);
297        }
298        let index = index - self.front.len();
299        if index < self.middle {
300            return Some(tree::get(self.root.as_ref()?, self.start + index));
301        }
302        self.back.as_slice().get(index - self.middle)
303    }
304
305    /// Returns the element at a zero-based `Int` position: `None` for a
306    /// negative one or one not less than the length (`list.get`).
307    pub fn get_int(&self, index: &Int) -> Option<&Value> {
308        self.get(index.to_index()?)
309    }
310
311    /// Returns the elements, in order.
312    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator {
313        self.elements()
314    }
315
316    pub(crate) fn elements(&self) -> Elements<'_> {
317        Elements {
318            front: self.front.as_slice().iter(),
319            middle: tree::Iter::new(self.root.as_ref(), self.start, self.middle),
320            back: self.back.as_slice().iter(),
321        }
322    }
323
324    /// Returns the elements of the ends and of the nodes nothing else holds:
325    /// what dropping the list would drop.
326    pub(crate) fn unshared_parts(&mut self) -> impl Iterator<Item = &mut Value> {
327        self.front
328            .unshared()
329            .chain(self.root.iter_mut().flat_map(tree::unshared))
330            .chain(self.back.unshared())
331    }
332
333    /// Returns the elements from `start` up to, not including, `end`, sharing
334    /// this list's tree, or `None` unless `start ≤ end ≤ length`.
335    pub fn slice(&self, start: usize, end: usize) -> Option<List> {
336        if start > end || end > self.len() {
337            return None;
338        }
339        let ends = |kept: &End, from: usize, to: usize| -> End {
340            let items = kept.as_slice();
341            let (from, to) = (from.min(items.len()), to.min(items.len()));
342            if from == 0 && to == items.len() {
343                kept.clone()
344            } else {
345                End::of(items[from..to].to_vec())
346            }
347        };
348        let front = ends(&self.front, start, end);
349        let in_middle = |at: usize| at.saturating_sub(self.front.len()).min(self.middle);
350        let (first, past) = (in_middle(start), in_middle(end));
351        let in_back = |at: usize| at.saturating_sub(self.front.len() + self.middle);
352        let back = ends(&self.back, in_back(start), in_back(end));
353        let root = (past > first).then(|| self.root.clone()).flatten();
354        Some(List::window(
355            front,
356            root,
357            self.start + first,
358            past - first,
359            back,
360        ))
361    }
362
363    /// Returns `self` with `item` added at the end.
364    #[must_use]
365    pub fn push_back(mut self, item: Value) -> List {
366        self.meta = self.meta.with(&item);
367        if self.back.len() == EDGE {
368            let full = self.back.take();
369            self.add_leaf_at_back(full);
370        }
371        self.back.items().push(item);
372        self
373    }
374
375    /// Returns `self` with `item` added at the front.
376    #[must_use]
377    pub fn push_front(mut self, item: Value) -> List {
378        self.meta = self.meta.with(&item);
379        if self.front.len() == EDGE {
380            let full = self.front.take();
381            self.add_leaf_at_front(full);
382        } else if self.front.is_empty() && self.middle == 0 && self.back.len() < EDGE {
383            self.back.items().insert(0, item);
384            return self;
385        }
386        self.front.items().insert(0, item);
387        self
388    }
389
390    /// Moves `items`, a full end, into the tree after its elements.
391    fn add_leaf_at_back(&mut self, items: Vec<Value>) {
392        let leaf = tree::leaf(items);
393        let tree = match self.take_tree() {
394            Some(tree) => tree::join(tree, leaf),
395            None => leaf,
396        };
397        self.middle = tree.len();
398        self.root = Some(tree);
399    }
400
401    /// Moves `items`, a full end, into the tree before its elements.
402    fn add_leaf_at_front(&mut self, items: Vec<Value>) {
403        let leaf = tree::leaf(items);
404        let tree = match self.take_tree() {
405            Some(tree) => tree::join(leaf, tree),
406            None => leaf,
407        };
408        self.middle = tree.len();
409        self.root = Some(tree);
410    }
411
412    /// Returns `self + other`, sharing both lists' trees.
413    #[must_use]
414    pub fn concat(mut self, mut other: List) -> List {
415        let meta = self.meta.join(other.meta);
416        if other.middle == 0 {
417            // Adding a list with no tree: its elements join this back.
418            let mut added = other.front.take();
419            added.append(&mut other.back.take());
420            let mut list = self;
421            list.meta = meta;
422            for item in added {
423                list = list.push_back(item);
424            }
425            return list;
426        }
427        if self.middle == 0 {
428            let mut added = self.front.take();
429            added.append(&mut self.back.take());
430            let mut list = other;
431            list.meta = meta;
432            for item in added.into_iter().rev() {
433                list = list.push_front(item);
434            }
435            return list;
436        }
437        let front = std::mem::take(&mut self.front);
438        let back = std::mem::take(&mut other.back);
439        let mut seam = self.back.take();
440        seam.append(&mut other.front.take());
441        let (left, right) = (self.take_middle(), other.take_middle());
442        let left = seam.into_iter().fold(left, tree::push_back);
443        List::of(front, Some(tree::concat(left, right)), back, meta)
444    }
445
446    /// Returns `items` reordered by `keys`, one key per item, stably: items
447    /// whose keys are equal keep their order (`list.sort_by`).
448    ///
449    /// Returns `None` when there is not exactly one key per item.
450    ///
451    /// # Errors
452    ///
453    /// A [`DataError`] when two keys cannot be compared: one is not data, or
454    /// the two are of different shapes.
455    pub fn sort_by_keys(&self, keys: &[Value]) -> Result<Option<List>, DataError> {
456        if keys.len() != self.len() {
457            return Ok(None);
458        }
459        let mut order: Vec<usize> = (0..self.len()).collect();
460        let mut failure = None;
461        order.sort_by(|&a, &b| {
462            compare(&keys[a], &keys[b]).unwrap_or_else(|error| {
463                failure = Some(error);
464                Ordering::Equal
465            })
466        });
467        if let Some(error) = failure {
468            return Err(error);
469        }
470        let items: Vec<&Value> = self.iter().collect();
471        Ok(Some(
472            order.into_iter().map(|at| items[at].clone()).collect(),
473        ))
474    }
475
476    /// The tree [`List::take_tree`] takes from a list with a middle.
477    fn take_middle(&mut self) -> Tree {
478        self.take_tree().expect("a list with a middle has a tree")
479    }
480
481    /// Takes the tree, cut down to exactly this list's middle elements,
482    /// leaving the list with no middle; `None` when it has none.
483    fn take_tree(&mut self) -> Option<Tree> {
484        let root = self.root.take()?;
485        let (start, middle) = (self.start, self.middle);
486        self.start = 0;
487        self.middle = 0;
488        if start == 0 && middle == root.len() {
489            Some(root)
490        } else {
491            tree::range(root, start, middle)
492        }
493    }
494}
495
496/// What a [`List`] is made of ([`List::parts`]).
497#[derive(Clone, Copy, Debug)]
498pub struct ListParts<'a> {
499    /// The elements before the tree's: at most eight.
500    pub front: &'a [Value],
501    /// The tree, how many of its elements to pass over, and how many to
502    /// take: present only when the list takes at least one.
503    pub tree: Option<(&'a Node, usize, usize)>,
504    /// The elements after the tree's: at most eight.
505    pub back: &'a [Value],
506}
507
508impl FromIterator<Value> for List {
509    fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
510        let mut meta = Meta::EMPTY;
511        let items: Vec<Value> = items
512            .into_iter()
513            .inspect(|item| meta = meta.with(item))
514            .collect();
515        if items.len() <= EDGE {
516            return List::of(End::default(), None, End::of(items), meta);
517        }
518        List::of(End::default(), tree::build(items), End::default(), meta)
519    }
520}
521
522/// A list's elements, in order and from either end: its front, the middle
523/// it takes from its tree, and its back.
524#[derive(Clone, Debug)]
525pub(crate) struct Elements<'a> {
526    front: std::slice::Iter<'a, Value>,
527    middle: tree::Iter<'a>,
528    back: std::slice::Iter<'a, Value>,
529}
530
531impl<'a> Iterator for Elements<'a> {
532    type Item = &'a Value;
533
534    #[inline]
535    fn next(&mut self) -> Option<&'a Value> {
536        self.front
537            .next()
538            .or_else(|| self.middle.next())
539            .or_else(|| self.back.next())
540    }
541
542    fn nth(&mut self, mut n: usize) -> Option<&'a Value> {
543        let front = self.front.len();
544        if n < front {
545            return self.front.nth(n);
546        }
547        self.front.nth(front);
548        n -= front;
549        let middle = self.middle.len();
550        if n < middle {
551            return self.middle.nth(n);
552        }
553        self.middle.nth(middle);
554        self.back.nth(n - middle)
555    }
556
557    #[inline]
558    fn size_hint(&self) -> (usize, Option<usize>) {
559        let left = self.front.len() + self.middle.len() + self.back.len();
560        (left, Some(left))
561    }
562}
563
564impl<'a> DoubleEndedIterator for Elements<'a> {
565    #[inline]
566    fn next_back(&mut self) -> Option<&'a Value> {
567        self.back
568            .next_back()
569            .or_else(|| self.middle.next_back())
570            .or_else(|| self.front.next_back())
571    }
572
573    fn nth_back(&mut self, mut n: usize) -> Option<&'a Value> {
574        let back = self.back.len();
575        if n < back {
576            return self.back.nth_back(n);
577        }
578        self.back.nth_back(back);
579        n -= back;
580        let middle = self.middle.len();
581        if n < middle {
582            return self.middle.nth_back(n);
583        }
584        self.middle.nth_back(middle);
585        self.front.nth_back(n - middle)
586    }
587}
588
589impl ExactSizeIterator for Elements<'_> {}
590
591/// Which of several items with one key [`sort_unique`] keeps.
592#[derive(Clone, Copy, PartialEq, Eq)]
593enum Keep {
594    /// The first written, as a set does.
595    First,
596    /// The last written, as a dictionary literal does.
597    Last,
598}
599
600/// Sorts `items` stably by `key_of`, then keeps one item per key: the first
601/// or the last written, as `keep` says.
602fn sort_unique<T>(
603    mut items: Vec<T>,
604    key_of: impl Fn(&T) -> &Value,
605    keep: Keep,
606) -> Result<Vec<T>, DataError> {
607    let keep_last = keep == Keep::Last;
608    let mut failure = None;
609    items.sort_by(|a, b| {
610        compare(key_of(a), key_of(b)).unwrap_or_else(|error| {
611            failure = Some(error);
612            Ordering::Equal
613        })
614    });
615    if let Some(error) = failure {
616        return Err(error);
617    }
618    if keep_last {
619        items.reverse();
620    }
621    // Equal keys are adjacent, and every comparison above succeeded, so
622    // these cannot fail; the stable sort put the first-written first, and the
623    // reversal put the last-written first, which is the one `dedup` keeps.
624    items.dedup_by(|later, earlier| compare(key_of(later), key_of(earlier)) == Ok(Ordering::Equal));
625    if keep_last {
626        items.reverse();
627    }
628    Ok(items)
629}
630
631/// A tree of elements kept in ascending key order, distinct by key: what a
632/// [`Dict`] and a [`Set`] each are, over their own element.
633///
634/// Looking up, inserting or removing a key costs O(log n) comparisons and
635/// steps: the way down compares the key with the first key of each right
636/// subtree it passes. Inserting or removing copies only the path to the
637/// element, so one made from a stored one shares every other node of it.
638#[derive(Clone, Debug)]
639struct Ordered<E: Keyed> {
640    root: Option<Tree<E>>,
641}
642
643impl<E: Keyed> Default for Ordered<E> {
644    fn default() -> Self {
645        Ordered { root: None }
646    }
647}
648
649impl<E: Keyed> Ordered<E> {
650    /// Returns the tree of `items`, sorted by key and keeping one item per
651    /// key, the first or the last written as `keep` says.
652    fn of(items: Vec<E>, keep: Keep) -> Result<Self, DataError> {
653        let items = sort_unique(items, Keyed::sort_key, keep)?;
654        Ok(Ordered {
655            root: tree::build(items),
656        })
657    }
658
659    /// Returns the tree `root`, whose keys must ascend and be distinct; a
660    /// debug build checks that.
661    fn from_tree(root: Option<Node<E>>) -> Self {
662        let ordered = Ordered { root };
663        debug_assert!(
664            ordered
665                .iter()
666                .zip(ordered.iter().skip(1))
667                .all(|(earlier, later)| {
668                    compare(earlier.sort_key(), later.sort_key()) == Ok(Ordering::Less)
669                }),
670            "keys ascend"
671        );
672        ordered
673    }
674
675    fn len(&self) -> usize {
676        self.root.as_ref().map_or(0, Node::len)
677    }
678
679    fn is_empty(&self) -> bool {
680        self.root.is_none()
681    }
682
683    fn iter(&self) -> tree::Iter<'_, E> {
684        tree::Iter::new(self.root.as_ref(), 0, self.len())
685    }
686
687    /// The element at `index` in order, if there is one.
688    fn get(&self, index: usize) -> Option<&E> {
689        let root = self.root.as_ref()?;
690        (index < root.len()).then(|| tree::get(root, index))
691    }
692
693    /// What the elements measure, exactly, as the root records it.
694    fn meta(&self) -> Meta {
695        self.root.as_ref().map_or(Meta::EMPTY, Node::measure)
696    }
697
698    fn id(&self) -> usize {
699        self.root.as_ref().map_or(0, Node::id)
700    }
701
702    /// Finds `key`: its position and element when present, and otherwise
703    /// where it would go.
704    fn find(&self, key: &Value) -> Result<tree::Found<'_, E>, DataError> {
705        match &self.root {
706            Some(root) => tree::find(root, key),
707            None => Ok(Err(0)),
708        }
709    }
710
711    /// Returns `self` with `item`; of it and an element with its key, the
712    /// one `keep` says: the element held, or `item`, written last.
713    fn insert(mut self, item: E, keep: Keep) -> Result<Self, DataError> {
714        let found = self.find(item.sort_key())?.map(|(at, _)| at);
715        self.root = Some(match (self.root.take(), found, keep) {
716            (Some(root), Ok(at), Keep::Last) => tree::replace(root, at, item),
717            (Some(root), Ok(_), Keep::First) => root,
718            (Some(root), Err(at), _) => tree::insert(root, at, item),
719            (None, _, _) => tree::leaf(vec![item]),
720        });
721        Ok(self)
722    }
723
724    /// Returns `self` without the element whose key is `key`.
725    fn remove(mut self, key: &Value) -> Result<Self, DataError> {
726        if let Ok((at, _)) = self.find(key)? {
727            self.root = self.root.take().and_then(|root| tree::remove(root, at));
728        }
729        Ok(self)
730    }
731
732    /// The elements of the nodes nothing else holds: what dropping the tree
733    /// would drop.
734    fn unshared(&mut self) -> impl Iterator<Item = &mut E> {
735        self.root.iter_mut().flat_map(tree::unshared)
736    }
737}
738
739impl Drop for Dict {
740    fn drop(&mut self) {
741        crate::value::dismantle(self.unshared_parts());
742    }
743}
744
745/// A dictionary: keys mapped to values, sorted by key.
746///
747/// Its entries lie in a balanced tree of chunks, as a list's elements do, in
748/// key order, and every branch keeps the key of its first entry. Looking up,
749/// inserting or removing a key costs O(log n) comparisons and steps.
750#[derive(Clone, Debug, Default)]
751pub struct Dict {
752    entries: Ordered<(Value, Value)>,
753}
754
755impl Dict {
756    /// Returns the empty dictionary.
757    pub fn new() -> Self {
758        Dict::default()
759    }
760
761    /// Returns the dictionary of `entries`, where a later entry with a key
762    /// equal to an earlier one's wins (the dictionary literal's rule).
763    ///
764    /// # Errors
765    ///
766    /// A [`DataError`] when two keys cannot be compared.
767    pub fn from_entries(
768        entries: impl IntoIterator<Item = (Value, Value)>,
769    ) -> Result<Dict, DataError> {
770        Ok(Dict {
771            entries: Ordered::of(entries.into_iter().collect(), Keep::Last)?,
772        })
773    }
774
775    /// Returns how many entries there are.
776    pub fn len(&self) -> usize {
777        self.entries.len()
778    }
779
780    /// Returns whether there are none.
781    pub fn is_empty(&self) -> bool {
782        self.entries.is_empty()
783    }
784
785    pub(crate) fn entries(&self) -> tree::Iter<'_, (Value, Value)> {
786        self.entries.iter()
787    }
788
789    /// The entry at `index` in key order, if there is one.
790    pub(crate) fn entry(&self, index: usize) -> Option<&(Value, Value)> {
791        self.entries.get(index)
792    }
793
794    /// What its keys and values measure, exactly.
795    pub(crate) fn meta(&self) -> Meta {
796        self.entries.meta()
797    }
798
799    /// Returns the keys and values of the nodes nothing else holds: what
800    /// dropping the dictionary would drop.
801    pub(crate) fn unshared_parts(&mut self) -> impl Iterator<Item = &mut Value> {
802        self.entries
803            .unshared()
804            .flat_map(|(key, value)| [key, value])
805    }
806
807    /// Returns the entries, in key order.
808    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Value, &Value)> {
809        self.entries().map(|(key, value)| (key, value))
810    }
811
812    /// Returns the keys, in key order.
813    pub fn keys(&self) -> impl ExactSizeIterator<Item = &Value> {
814        self.entries().map(|(key, _)| key)
815    }
816
817    /// Returns the values, in key order.
818    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
819        self.entries().map(|(_, value)| value)
820    }
821
822    /// Returns the value at `key`.
823    ///
824    /// # Errors
825    ///
826    /// A [`DataError`] when `key` cannot be compared with the keys held.
827    pub fn get(&self, key: &Value) -> Result<Option<&Value>, DataError> {
828        Ok(self.entries.find(key)?.ok().map(|(_, (_, value))| value))
829    }
830
831    /// Returns the tree the entries lie in, in ascending key order, or
832    /// `None` when there are none.
833    pub fn root(&self) -> Option<&Node<(Value, Value)>> {
834        self.entries.root.as_ref()
835    }
836
837    /// Returns the dictionary whose entries are those of `root`, sharing it.
838    ///
839    /// The keys must ascend across the whole tree and be distinct, as those
840    /// of [`Dict::root`] do; the caller checks that, as reading history
841    /// does, and a debug build checks it again. This costs constant time.
842    pub fn from_tree(root: Option<Node<(Value, Value)>>) -> Dict {
843        Dict {
844            entries: Ordered::from_tree(root),
845        }
846    }
847
848    /// What tells this dictionary apart from every other alive: its tree.
849    pub(crate) fn id(&self) -> usize {
850        self.entries.id()
851    }
852
853    /// Returns `self` with `key` mapped to `value`, replacing any earlier
854    /// value.
855    ///
856    /// # Errors
857    ///
858    /// A [`DataError`] when `key` cannot be compared with the keys held.
859    pub fn insert(mut self, key: Value, value: Value) -> Result<Dict, DataError> {
860        self.entries = std::mem::take(&mut self.entries).insert((key, value), Keep::Last)?;
861        Ok(self)
862    }
863
864    /// Returns `self` without `key`.
865    ///
866    /// # Errors
867    ///
868    /// A [`DataError`] when `key` cannot be compared with the keys held.
869    pub fn remove(mut self, key: &Value) -> Result<Dict, DataError> {
870        self.entries = std::mem::take(&mut self.entries).remove(key)?;
871        Ok(self)
872    }
873}
874
875impl Drop for Set {
876    fn drop(&mut self) {
877        crate::value::dismantle(self.unshared_parts());
878    }
879}
880
881/// A set: distinct values, sorted.
882///
883/// Its members lie in a balanced tree in ascending order, so looking one up,
884/// inserting or removing one costs O(log n), and a set made from a stored one
885/// shares every node the change does not touch.
886#[derive(Clone, Debug, Default)]
887pub struct Set {
888    members: Ordered<Member>,
889}
890
891impl Set {
892    /// Returns the set of `items`' distinct elements (`set.from`).
893    ///
894    /// # Errors
895    ///
896    /// A [`DataError`] when two elements cannot be compared.
897    pub fn from_items(items: impl IntoIterator<Item = Value>) -> Result<Set, DataError> {
898        Ok(Set {
899            members: Ordered::of(items.into_iter().map(Member::new).collect(), Keep::First)?,
900        })
901    }
902
903    /// Returns how many elements there are.
904    pub fn len(&self) -> usize {
905        self.members.len()
906    }
907
908    /// Returns whether there are none.
909    pub fn is_empty(&self) -> bool {
910        self.members.is_empty()
911    }
912
913    /// Returns the elements, in order.
914    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Value> {
915        self.members.iter().map(Member::value)
916    }
917
918    pub(crate) fn members(&self) -> tree::Iter<'_, Member> {
919        self.members.iter()
920    }
921
922    /// The element at `index` in order, if there is one.
923    pub(crate) fn member(&self, index: usize) -> Option<&Value> {
924        self.members.get(index).map(Member::value)
925    }
926
927    /// What its elements measure, exactly.
928    pub(crate) fn meta(&self) -> Meta {
929        self.members.meta()
930    }
931
932    /// Returns the elements of the nodes nothing else holds: what dropping
933    /// the set would drop.
934    pub(crate) fn unshared_parts(&mut self) -> impl Iterator<Item = &mut Value> {
935        self.members.unshared().map(Member::value_mut)
936    }
937
938    /// Returns the tree the members lie in, in ascending order, or `None`
939    /// when there are none.
940    pub fn root(&self) -> Option<&Node<Member>> {
941        self.members.root.as_ref()
942    }
943
944    /// Returns the set whose members are those of `root`, sharing it.
945    ///
946    /// The members must ascend across the whole tree and be distinct, as
947    /// those of [`Set::root`] do; the caller checks that, as reading history
948    /// does, and a debug build checks it again.
949    pub fn from_tree(root: Option<Node<Member>>) -> Set {
950        Set {
951            members: Ordered::from_tree(root),
952        }
953    }
954
955    /// What tells this set apart from every other alive: its tree.
956    pub(crate) fn id(&self) -> usize {
957        self.members.id()
958    }
959
960    /// Returns whether `item` is an element.
961    ///
962    /// # Errors
963    ///
964    /// A [`DataError`] when `item` cannot be compared with the elements.
965    pub fn contains(&self, item: &Value) -> Result<bool, DataError> {
966        Ok(self.members.find(item)?.is_ok())
967    }
968
969    /// Returns `self` with `item` among its elements; `self` itself when
970    /// it already is one.
971    ///
972    /// # Errors
973    ///
974    /// A [`DataError`] when `item` cannot be compared with the elements.
975    pub fn insert(mut self, item: Value) -> Result<Set, DataError> {
976        self.members = std::mem::take(&mut self.members).insert(Member::new(item), Keep::First)?;
977        Ok(self)
978    }
979
980    /// Returns `self` without `item`.
981    ///
982    /// # Errors
983    ///
984    /// A [`DataError`] when `item` cannot be compared with the elements.
985    pub fn remove(mut self, item: &Value) -> Result<Set, DataError> {
986        self.members = std::mem::take(&mut self.members).remove(item)?;
987        Ok(self)
988    }
989}