Skip to main content

flow_value/
tree.rs

1//! The balanced tree a [`List`](crate::List) keeps its elements in, a
2//! [`Dict`](crate::Dict) its entries, a [`Set`](crate::Set) its members and a
3//! [`Text`](crate::Text) its runs.
4//!
5//! A tree is a height-balanced (AVL) binary tree: each leaf holds from one to
6//! as many elements as a leaf of their kind holds, in order, each branch
7//! records how many elements and how
8//! many levels lie below it, what they measure, and the key of the first of
9//! them when they are a dictionary's entries, and the two subtrees of every
10//! branch differ in height by at most one. Every tree is balanced, however
11//! it was made: [`Node::branch`], which rebuilds a tree read from history,
12//! restores the balance a foreign writer did not keep. A tree of `k` leaves is therefore less than
13//! `1.45 · log2(k + 2)` levels high, so every recursion here is shallow.
14//!
15//! Nodes are shared through `Arc`. Every operation takes trees by value and
16//! returns a new one, rebuilding only the nodes on the path it changes: a node
17//! nothing else holds is reused in place, and one another tree still holds is
18//! copied, so that tree is untouched. For a tree of `n` elements:
19//!
20//! - finding the element at a position costs O(log n);
21//! - [`push_back`] and [`push_front`] cost O(log n + CHUNK);
22//! - [`join`] of trees of heights `a` and `b` costs O(|a − b| + 1), and
23//!   [`concat`] O(CHUNK · log n) at worst;
24//! - [`split`] and [`cut`] cost O(log n), with a leaf's elements walked and
25//!   one of them cut.
26//!
27//! Deeply nested *values* are not this module's concern: dropping a node
28//! drops its elements one by one, and each value's own `Drop` dismantles
29//! what it holds without recursing.
30
31use std::fmt;
32use std::sync::Arc;
33
34use crate::error::{DataError, StructureError};
35use crate::text::Run;
36use crate::value::{Meta, Value, compare};
37
38pub(crate) use sealed::Measure;
39
40/// The most values a leaf holds.
41///
42/// A larger leaf makes a tree shallower and iteration cheaper, and makes
43/// each change copy more, in memory and in what history stores for it
44/// (`trace.md`, *Lists*, where a leaf holds at most eight).
45pub(crate) const CHUNK: usize = 8;
46
47/// What a tree holds: a list's elements, a dictionary's entries as key and
48/// value pairs, a set's members, or a text's runs. No other type is one.
49pub trait Element: Clone + fmt::Debug + sealed::Sealed {}
50
51impl Element for Value {}
52
53impl Element for (Value, Value) {}
54
55impl Element for Member {}
56
57impl Element for Run {}
58
59/// A set's member: a value that is its own key.
60#[derive(Clone, Debug)]
61pub struct Member(Value);
62
63impl Member {
64    /// Returns the member `value` is.
65    pub fn new(value: Value) -> Member {
66        Member(value)
67    }
68
69    /// Returns the value.
70    pub fn value(&self) -> &Value {
71        &self.0
72    }
73
74    pub(crate) fn value_mut(&mut self) -> &mut Value {
75        &mut self.0
76    }
77}
78
79/// An element kept in key order: a dictionary's entry, or a set's member.
80pub trait Keyed: Element + sealed::Sealed<Key = Value, Measure = Meta> {
81    /// Returns the key it is sorted by.
82    fn sort_key(&self) -> &Value {
83        sealed::Sealed::key(self)
84    }
85}
86
87impl Keyed for (Value, Value) {}
88
89impl Keyed for Member {}
90
91mod sealed {
92    use std::fmt;
93
94    use super::{CHUNK, Member};
95    use crate::text::{Run, Span};
96    use crate::value::{Meta, Value};
97
98    /// What every node records of the elements below it, so that a range of
99    /// them is measured from the nodes wholly inside it.
100    pub trait Measure: Copy + PartialEq + fmt::Debug {
101        /// What no elements measure.
102        const EMPTY: Self;
103
104        /// Returns what the elements `self` and `other` measure do together.
105        #[must_use]
106        fn join(self, other: Self) -> Self;
107    }
108
109    /// What a tree reads of what it holds.
110    pub trait Sealed {
111        /// What a branch keeps of its first element to be searched by: a
112        /// dictionary entry's key, and nothing of a list's element.
113        type Key: Clone + fmt::Debug;
114
115        /// What every node records of the elements below it.
116        type Measure: Measure;
117
118        /// The most elements a leaf holds: as many as one leaf of history
119        /// holds (`trace.md`, *Trees*), eight values or one run of text.
120        const LEAF: usize;
121
122        /// Returns what a branch keeps of this element.
123        fn key(&self) -> &Self::Key;
124
125        /// Returns what this element measures.
126        fn measure(&self) -> Self::Measure;
127    }
128
129    impl Sealed for Value {
130        type Key = ();
131        type Measure = Meta;
132        const LEAF: usize = CHUNK;
133
134        fn key(&self) -> &() {
135            &()
136        }
137
138        fn measure(&self) -> Meta {
139            Meta::EMPTY.with(self)
140        }
141    }
142
143    impl Sealed for (Value, Value) {
144        type Key = Value;
145        type Measure = Meta;
146        const LEAF: usize = CHUNK;
147
148        fn key(&self) -> &Value {
149            &self.0
150        }
151
152        fn measure(&self) -> Meta {
153            Meta::EMPTY.with(&self.0).with(&self.1)
154        }
155    }
156
157    impl Sealed for Member {
158        type Key = Value;
159        type Measure = Meta;
160        const LEAF: usize = CHUNK;
161
162        fn key(&self) -> &Value {
163            &self.0
164        }
165
166        fn measure(&self) -> Meta {
167            Meta::EMPTY.with(&self.0)
168        }
169    }
170
171    impl Sealed for Run {
172        type Key = ();
173        type Measure = Span;
174        const LEAF: usize = 1;
175
176        fn key(&self) -> &() {
177            &()
178        }
179
180        fn measure(&self) -> Span {
181            self.span()
182        }
183    }
184}
185
186/// A shared node of a tree: a whole tree, or a part of one.
187///
188/// Cloning one shares it, and two handles to one node have one
189/// [`Node::id`]. A list's or a dictionary's tree is made of nodes, which the
190/// lists and dictionaries made from it share: [`List::parts`] and
191/// [`Dict::root`] read the nodes a value is made of, [`Node::shape`] what
192/// each node holds, and [`Node::leaf`] and [`Node::branch`] build a tree
193/// again, node by node, so that what was shared stays shared.
194///
195/// [`List::parts`]: crate::List::parts
196/// [`Dict::root`]: crate::Dict::root
197#[derive(Debug)]
198pub struct Node<T: Element = Value>(Arc<Inner<T>>);
199
200impl<T: Element> Clone for Node<T> {
201    fn clone(&self) -> Self {
202        Node(Arc::clone(&self.0))
203    }
204}
205
206/// A shared node: a whole tree, or a part of one.
207pub(crate) type Tree<T = Value> = Node<T>;
208
209/// What a node is.
210#[derive(Clone, Debug)]
211enum Inner<T: Element> {
212    /// From one to `T::LEAF` elements, in order, and what they measure.
213    Leaf(Vec<T>, T::Measure),
214    /// The elements of `left`, then those of `right`.
215    Branch(Branch<T>),
216}
217
218/// Two subtrees whose heights differ by at most one.
219#[derive(Clone, Debug)]
220struct Branch<T: Element> {
221    left: Tree<T>,
222    right: Tree<T>,
223    /// How many elements lie below.
224    len: usize,
225    /// How many levels lie below: one more than the higher subtree's.
226    height: u8,
227    /// What the elements below measure, exactly.
228    measure: T::Measure,
229    /// What the first element below keeps to be searched by.
230    first: T::Key,
231}
232
233/// What a node holds: its elements, when it is a leaf, or its two
234/// subtrees, when it is a branch.
235#[derive(Debug)]
236pub enum Shape<'a, T: Element> {
237    /// From one to as many elements as a leaf of their kind holds, in
238    /// order.
239    Leaf(&'a [T]),
240    /// The elements of the left node, then those of the right; each holds at
241    /// least one.
242    Branch(&'a Node<T>, &'a Node<T>),
243}
244
245impl<T: Element> Node<T> {
246    /// Returns the leaf holding `items`.
247    ///
248    /// # Errors
249    ///
250    /// [`StructureError::Leaf`] unless they number from one to as many as a
251    /// leaf of their kind holds.
252    pub fn leaf(items: Vec<T>) -> Result<Self, StructureError> {
253        if (1..=T::LEAF).contains(&items.len()) {
254            Ok(leaf(items))
255        } else {
256            Err(StructureError::Leaf)
257        }
258    }
259
260    /// Returns the tree holding `left`'s elements, then `right`'s.
261    ///
262    /// When the two are as high as each other or within one level, which
263    /// they are whenever this crate made the tree being rebuilt, this is one
264    /// new branch over exactly `left` and `right`, so each stays shared.
265    /// Every tree here is balanced (AVL), and indexing, insertion, removal,
266    /// joining and cutting rely on that for their cost; so when the two
267    /// differ by more, as a tree from another writer may, the lower is
268    /// joined into the higher's near spine and the branches on that path
269    /// are rebuilt balanced, in O(difference in height). Every node below
270    /// that path stays shared, and the elements and their order are the
271    /// same either way.
272    pub fn branch(left: Self, right: Self) -> Self {
273        if left.level().abs_diff(right.level()) <= 1 {
274            branch(left, right)
275        } else {
276            join(left, right)
277        }
278    }
279
280    /// Returns what tells this node apart from every other node alive: two
281    /// handles answer alike exactly when they share one node. The answer
282    /// means something only while a handle to the node is kept, since a
283    /// node made after this one is dropped may answer the same.
284    pub fn id(&self) -> usize {
285        Arc::as_ptr(&self.0).addr()
286    }
287
288    /// Returns how many elements lie in the tree.
289    pub fn len(&self) -> usize {
290        match &*self.0 {
291            Inner::Leaf(items, _) => items.len(),
292            Inner::Branch(branch) => branch.len,
293        }
294    }
295
296    /// Returns `false`: a node holds at least one element.
297    pub fn is_empty(&self) -> bool {
298        false
299    }
300
301    /// Returns the tree of the `count` elements that follow this tree's
302    /// first `skip`, sharing every node the cut does not pass through.
303    ///
304    /// # Errors
305    ///
306    /// [`StructureError::Window`] unless `count` is at least one and the
307    /// tree holds `skip + count` elements.
308    pub fn window(&self, skip: usize, count: usize) -> Result<Self, StructureError> {
309        let fits = count > 0 && skip.checked_add(count).is_some_and(|end| end <= self.len());
310        if !fits {
311            return Err(StructureError::Window);
312        }
313        range(self.clone(), skip, count).ok_or(StructureError::Window)
314    }
315
316    /// Returns how many levels of branches lie below: 0 for a leaf.
317    pub fn height(&self) -> usize {
318        usize::from(self.level())
319    }
320
321    /// Returns what the node holds.
322    pub fn shape(&self) -> Shape<'_, T> {
323        match &*self.0 {
324            Inner::Leaf(items, _) => Shape::Leaf(items),
325            Inner::Branch(branch) => Shape::Branch(&branch.left, &branch.right),
326        }
327    }
328
329    /// Returns how many levels lie below: 0 for a leaf.
330    fn level(&self) -> u8 {
331        match &*self.0 {
332            Inner::Leaf(..) => 0,
333            Inner::Branch(branch) => branch.height,
334        }
335    }
336
337    /// Returns what the elements below measure, exactly, as every node
338    /// records it.
339    pub(crate) fn measure(&self) -> T::Measure {
340        match &*self.0 {
341            Inner::Leaf(_, measure) => *measure,
342            Inner::Branch(branch) => branch.measure,
343        }
344    }
345
346    /// Returns what the first element below keeps to be searched by.
347    fn first(&self) -> T::Key {
348        match &*self.0 {
349            Inner::Leaf(items, _) => sealed::Sealed::key(&items[0]).clone(),
350            Inner::Branch(branch) => branch.first.clone(),
351        }
352    }
353}
354
355/// Returns what the `len` elements of `tree` from `start` measure,
356/// exactly: the nodes wholly inside the range answer from what they record,
357/// so only the two paths to its ends are walked, in O(log n + CHUNK).
358pub(crate) fn range_measure<T: Element>(tree: &Tree<T>, start: usize, len: usize) -> T::Measure {
359    if len == 0 {
360        return Measure::EMPTY;
361    }
362    if start == 0 && len == tree.len() {
363        return tree.measure();
364    }
365    match &*tree.0 {
366        Inner::Leaf(items, _) => measure(&items[start..start + len]),
367        Inner::Branch(branch) => {
368            let before = branch.left.len();
369            let in_left = before.saturating_sub(start).min(len);
370            let left = range_measure(&branch.left, start.min(before), in_left);
371            let right = range_measure(&branch.right, start.saturating_sub(before), len - in_left);
372            left.join(right)
373        }
374    }
375}
376
377/// Returns what `items` measure together.
378fn measure<T: Element>(items: &[T]) -> T::Measure {
379    items
380        .iter()
381        .map(sealed::Sealed::measure)
382        .fold(Measure::EMPTY, Measure::join)
383}
384
385/// Returns the leaf holding `items`, which must number from one to
386/// `T::LEAF`.
387pub(crate) fn leaf<T: Element>(items: Vec<T>) -> Tree<T> {
388    let measure = measure(&items);
389    Node(Arc::new(Inner::Leaf(items, measure)))
390}
391
392/// Returns the branch over `left` and `right`, which must be balanced.
393fn branch<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
394    Node(Arc::new(Inner::Branch(Branch {
395        len: left.len() + right.len(),
396        height: left.level().max(right.level()) + 1,
397        measure: left.measure().join(right.measure()),
398        first: left.first(),
399        left,
400        right,
401    })))
402}
403
404/// Returns the subtrees of `tree`, a branch: moved out when nothing else
405/// holds it, shared otherwise.
406fn children<T: Element>(tree: Tree<T>) -> (Tree<T>, Tree<T>) {
407    let Inner::Branch(branch) = Arc::unwrap_or_clone(tree.0) else {
408        unreachable!("a leaf has no subtrees")
409    };
410    (branch.left, branch.right)
411}
412
413/// Returns the tree of `items`, in order, or `None` when there are none.
414///
415/// The leaves are full but for the last, and the tree is as low as their
416/// number allows.
417pub(crate) fn build<T: Element>(items: impl IntoIterator<Item = T>) -> Option<Tree<T>> {
418    let mut items = items.into_iter();
419    let first: Vec<T> = items.by_ref().take(T::LEAF).collect();
420    if first.len() < T::LEAF {
421        return (!first.is_empty()).then(|| leaf(first));
422    }
423    let mut leaves = vec![leaf(first)];
424    loop {
425        let chunk: Vec<T> = items.by_ref().take(T::LEAF).collect();
426        if chunk.is_empty() {
427            break;
428        }
429        leaves.push(leaf(chunk));
430    }
431    let count = leaves.len();
432    Some(balanced(&mut leaves.into_iter(), count))
433}
434
435/// Returns the next `count` of `leaves`, at least one, under a tree whose
436/// two halves at every branch hold leaf counts differing by at most one, so
437/// their heights do too.
438fn balanced<T: Element>(leaves: &mut impl Iterator<Item = Tree<T>>, count: usize) -> Tree<T> {
439    if count == 1 {
440        return leaves.next().expect("one leaf is left for each count");
441    }
442    let left = balanced(leaves, count / 2);
443    let right = balanced(leaves, count - count / 2);
444    branch(left, right)
445}
446
447/// Returns the tree holding `left`'s elements, then `right`'s.
448///
449/// The lower tree descends the near spine of the higher until it meets a
450/// subtree as high as it, and each branch rebuilt on the way back up is
451/// rebalanced, so the cost is the difference in height.
452pub(crate) fn join<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
453    join_with(left, right, &|_, _| None)
454}
455
456/// Returns the tree holding `left`'s elements, then `right`'s, as [`join`]
457/// does, but where `fuse` makes one tree of the two it meets on the way
458/// down, at the top or where the lower tree lands, that tree takes their
459/// place.
460///
461/// A fused tree may be lower than the two were, so the branches above it
462/// are rejoined as [`join`] joins any two, and the cost stays the difference
463/// in height.
464pub(crate) fn join_with<T: Element>(
465    left: Tree<T>,
466    right: Tree<T>,
467    fuse: &impl Fn(&Tree<T>, &Tree<T>) -> Option<Tree<T>>,
468) -> Tree<T> {
469    if let Some(fused) = fuse(&left, &right) {
470        return fused;
471    }
472    let (low, high) = (left.level(), right.level());
473    if low > high + 1 {
474        let (outer, inner) = children(left);
475        let joined = join_with(inner, right, fuse);
476        if outer.level().abs_diff(joined.level()) <= 2 {
477            balance(outer, joined)
478        } else {
479            join(outer, joined)
480        }
481    } else if high > low + 1 {
482        let (inner, outer) = children(right);
483        let joined = join_with(left, inner, fuse);
484        if outer.level().abs_diff(joined.level()) <= 2 {
485            balance(joined, outer)
486        } else {
487            join(joined, outer)
488        }
489    } else {
490        branch(left, right)
491    }
492}
493
494/// Returns a balanced tree holding `left`'s elements, then `right`'s, when
495/// each is balanced and their heights differ by at most two.
496///
497/// A difference of two is the case AVL insertion repairs: one rotation when
498/// the higher side's outer subtree is at least as high as its inner one, and
499/// two when it is lower. Either way the result is balanced, and as high as
500/// the higher side or one less.
501fn balance<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
502    let (low, high) = (left.level(), right.level());
503    if high > low + 1 {
504        let (inner, outer) = children(right);
505        if inner.level() > outer.level() {
506            let (a, b) = children(inner);
507            branch(branch(left, a), branch(b, outer))
508        } else {
509            branch(branch(left, inner), outer)
510        }
511    } else if low > high + 1 {
512        let (outer, inner) = children(left);
513        if inner.level() > outer.level() {
514            let (a, b) = children(inner);
515            branch(branch(outer, a), branch(b, right))
516        } else {
517            branch(outer, branch(inner, right))
518        }
519    } else {
520        branch(left, right)
521    }
522}
523
524/// Returns `left` joined to `right` when both are present, or whichever is.
525fn join_either<T: Element>(left: Option<Tree<T>>, right: Option<Tree<T>>) -> Option<Tree<T>> {
526    match (left, right) {
527        (Some(left), Some(right)) => Some(join(left, right)),
528        (left, right) => left.or(right),
529    }
530}
531
532/// A way of counting positions along a tree's elements, by which [`cut`]
533/// finds where to split it: by element, or along what the elements measure.
534pub(crate) trait Along<T: Element> {
535    /// Returns how many positions the elements of `tree` span.
536    fn node(&self, tree: &Tree<T>) -> usize;
537
538    /// Returns how many positions `item` spans.
539    fn item(&self, item: &T) -> usize;
540
541    /// Returns `item` cut into what lies before position `at`, which is
542    /// inside it, and what lies from there, or `None` when it cannot be cut
543    /// there.
544    fn cut(&self, item: &T, at: usize) -> Option<(T, T)>;
545}
546
547/// Counting positions by element: a cut always falls between two.
548struct Count;
549
550impl<T: Element> Along<T> for Count {
551    fn node(&self, tree: &Tree<T>) -> usize {
552        tree.len()
553    }
554
555    fn item(&self, _: &T) -> usize {
556        1
557    }
558
559    fn cut(&self, _: &T, _: usize) -> Option<(T, T)> {
560        unreachable!("a position counted by element lies between two")
561    }
562}
563
564/// The trees of what lies before a position and of the rest, each `None`
565/// when it would hold none.
566pub(crate) type Halves<T> = (Option<Tree<T>>, Option<Tree<T>>);
567
568/// Returns the tree of `tree`'s first `at` elements and that of the rest,
569/// each `None` when it would hold none.
570pub(crate) fn split<T: Element>(tree: Tree<T>, at: usize) -> Halves<T> {
571    cut(tree, at, &Count).expect("a position counted by element lies between two")
572}
573
574/// Returns the tree of what lies before position `at` of `tree`, counted
575/// `along` it, and that of the rest, each `None` when it would hold none;
576/// or `None` when the element `at` falls inside cannot be cut there.
577///
578/// Cutting descends to the position, cuts the one element it falls inside,
579/// and joins the subtrees it passes on either side on the way back up.
580/// Those joins' costs telescope: each is the difference between consecutive
581/// heights, so the whole is O(log n), with one leaf's elements walked.
582pub(crate) fn cut<T: Element>(
583    tree: Tree<T>,
584    at: usize,
585    along: &impl Along<T>,
586) -> Option<Halves<T>> {
587    if at == 0 {
588        return Some((None, Some(tree)));
589    }
590    if at >= along.node(&tree) {
591        return Some((Some(tree), None));
592    }
593    if let Inner::Leaf(items, _) = &*tree.0 {
594        let mut before = 0;
595        let mut index = 0;
596        while before + along.item(&items[index]) <= at {
597            before += along.item(&items[index]);
598            index += 1;
599        }
600        // The element is cut where the tree holds it, so what cutting it
601        // learns stays with it for the next cut.
602        let mut head = items[..index].to_vec();
603        let mut rest = items[index..].to_vec();
604        if at > before {
605            let (first, second) = along.cut(&items[index], at - before)?;
606            head.push(first);
607            rest[0] = second;
608        }
609        return Some((Some(leaf(head)), Some(leaf(rest))));
610    }
611    let (left, right) = children(tree);
612    let before = along.node(&left);
613    Some(if at <= before {
614        let (first, rest) = cut(left, at, along)?;
615        (first, join_either(rest, Some(right)))
616    } else {
617        let (first, rest) = cut(right, at - before, along)?;
618        (join_either(Some(left), first), rest)
619    })
620}
621
622/// Returns the tree of the `len` elements of `tree` from `start`, or `None`
623/// when there are none.
624pub(crate) fn range<T: Element>(tree: Tree<T>, start: usize, len: usize) -> Option<Tree<T>> {
625    let (_, rest) = split(tree, start);
626    split(rest?, len).0
627}
628
629/// Returns `tree` with `item` added at the end.
630///
631/// The item joins the last leaf when that has room, which copies the leaf and
632/// the path to it if another tree holds them; otherwise it is a new leaf.
633pub(crate) fn push_back<T: Element>(mut tree: Tree<T>, item: T) -> Tree<T> {
634    match add_at_back(&mut tree, item) {
635        None => tree,
636        Some(item) => join(tree, leaf(vec![item])),
637    }
638}
639
640/// Adds `item` to the last leaf of `tree` when that has room, copying each
641/// node on the way that another tree holds, or returns it when the leaf is
642/// full.
643///
644/// The way down is one pass: a full leaf is found only once the branches
645/// above it are made this tree's own, which costs a copy of each of them that
646/// another tree holds, and `join` then reuses them.
647fn add_at_back<T: Element>(tree: &mut Tree<T>, item: T) -> Option<T> {
648    if let Inner::Leaf(items, _) = &*tree.0
649        && items.len() == T::LEAF
650    {
651        return Some(item);
652    }
653    match Arc::make_mut(&mut tree.0) {
654        Inner::Leaf(items, measure) => {
655            *measure = measure.join(sealed::Sealed::measure(&item));
656            items.push(item);
657        }
658        Inner::Branch(branch) => {
659            let full = add_at_back(&mut branch.right, item);
660            if full.is_none() {
661                branch.len += 1;
662                branch.measure = branch.left.measure().join(branch.right.measure());
663            }
664            return full;
665        }
666    }
667    None
668}
669
670/// Returns `tree` with `item` put in at position `at`, at most its length.
671///
672/// The item joins the leaf at that position, copied if another tree holds
673/// it; a leaf that would hold more than `T::LEAF` splits in two, and each
674/// branch on the way back up is rebalanced. The cost is O(log n + CHUNK).
675pub(crate) fn insert<T: Element>(tree: Tree<T>, at: usize, item: T) -> Tree<T> {
676    match Arc::unwrap_or_clone(tree.0) {
677        Inner::Leaf(mut items, _) => {
678            items.insert(at, item);
679            if items.len() <= T::LEAF {
680                leaf(items)
681            } else {
682                let rest = items.split_off(items.len() / 2);
683                branch(leaf(items), leaf(rest))
684            }
685        }
686        Inner::Branch(Branch { left, right, .. }) => {
687            let before = left.len();
688            if at <= before {
689                balance(insert(left, at, item), right)
690            } else {
691                balance(left, insert(right, at - before, item))
692            }
693        }
694    }
695}
696
697/// Returns `tree` with the element at `at`, which must be less than its
698/// length, replaced by `item`, copying only the path to it.
699pub(crate) fn replace<T: Element>(mut tree: Tree<T>, at: usize, item: T) -> Tree<T> {
700    fn set<T: Element>(tree: &mut Tree<T>, at: usize, item: T) {
701        match Arc::make_mut(&mut tree.0) {
702            Inner::Leaf(items, recorded) => {
703                items[at] = item;
704                *recorded = measure(items);
705            }
706            Inner::Branch(branch) => {
707                let before = branch.left.len();
708                if at < before {
709                    set(&mut branch.left, at, item);
710                } else {
711                    set(&mut branch.right, at - before, item);
712                }
713                branch.measure = branch.left.measure().join(branch.right.measure());
714                if at == 0 {
715                    branch.first = branch.left.first();
716                }
717            }
718        }
719    }
720    set(&mut tree, at, item);
721    tree
722}
723
724/// Returns `tree` without the element at `at`, which must be less than its
725/// length, or `None` when that was its only element. A leaf left empty is
726/// dropped, and each branch on the way back up is rebalanced.
727pub(crate) fn remove<T: Element>(tree: Tree<T>, at: usize) -> Option<Tree<T>> {
728    match Arc::unwrap_or_clone(tree.0) {
729        Inner::Leaf(mut items, _) => {
730            items.remove(at);
731            (!items.is_empty()).then(|| leaf(items))
732        }
733        Inner::Branch(Branch { left, right, .. }) => {
734            let before = left.len();
735            Some(if at < before {
736                match remove(left, at) {
737                    Some(left) => balance(left, right),
738                    None => right,
739                }
740            } else {
741                match remove(right, at - before) {
742                    Some(right) => balance(left, right),
743                    None => left,
744                }
745            })
746        }
747    }
748}
749
750/// Returns the tree holding `left`'s elements, then `right`'s.
751///
752/// A right side of at most a leaf's elements is added to the left one
753/// element at a time, so that joining a short list fills the leaf at the seam
754/// rather than leaving a short leaf in the middle; a longer one is joined as
755/// it is.
756pub(crate) fn concat<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
757    if right.len() <= T::LEAF {
758        Iter::new(Some(&right), 0, right.len())
759            .cloned()
760            .fold(left, push_back)
761    } else {
762        join(left, right)
763    }
764}
765
766#[cfg(test)]
767thread_local! {
768    /// How many nodes finding leaves has visited on this thread, so a test
769    /// can bound the work walking a tree does.
770    pub(crate) static VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
771}
772
773/// Counts one node visited on the way to a leaf, in tests.
774fn visited() {
775    #[cfg(test)]
776    VISITED.with(|visited| visited.set(visited.get() + 1));
777}
778
779/// The side of a branch a way down did not take.
780#[derive(Clone, Copy, PartialEq, Eq)]
781enum Side {
782    Left,
783    Right,
784}
785
786/// Returns the leaf holding the element at `index`, which must be less than
787/// `tree`'s length, and the element's position within that leaf.
788fn chunk<T: Element>(tree: &Node<T>, index: usize) -> (&[T], usize) {
789    chunk_passing(tree, index, |_, _| {})
790}
791
792/// Returns what [`chunk`] does, handing `passed` each subtree the way down
793/// passes and the side it lies on, nearest the root first.
794fn chunk_passing<'a, T: Element>(
795    mut tree: &'a Node<T>,
796    mut index: usize,
797    mut passed: impl FnMut(Side, &'a Node<T>),
798) -> (&'a [T], usize) {
799    loop {
800        visited();
801        match &*tree.0 {
802            Inner::Leaf(items, _) => return (items, index),
803            Inner::Branch(branch) => {
804                let before = branch.left.len();
805                if index < before {
806                    passed(Side::Right, &branch.right);
807                    tree = &branch.left;
808                } else {
809                    index -= before;
810                    passed(Side::Left, &branch.left);
811                    tree = &branch.right;
812                }
813            }
814        }
815    }
816}
817
818/// Returns the element at `index`, which must be less than `tree`'s length.
819#[inline]
820pub(crate) fn get<T: Element>(tree: &Node<T>, index: usize) -> &T {
821    let (items, at) = chunk(tree, index);
822    &items[at]
823}
824
825/// Returns the elements of every leaf of `tree` that nothing else holds,
826/// along with every node above it: what dropping `tree` would drop.
827///
828/// A tree another holds, or one of a single leaf, which is most of the lists
829/// a run drops, costs no allocation.
830pub(crate) fn unshared<T: Element>(tree: &mut Tree<T>) -> impl Iterator<Item = &mut T> {
831    let mut first = None;
832    let mut leaves: Vec<&mut Vec<T>> = Vec::new();
833    let mut pending: Vec<&mut Tree<T>> = Vec::new();
834    let mut next = Some(tree);
835    while let Some(node) = next.take().or_else(|| pending.pop()) {
836        match Arc::get_mut(&mut node.0) {
837            Some(Inner::Leaf(items, _)) => match first {
838                None => first = Some(items),
839                Some(_) => leaves.push(items),
840            },
841            Some(Inner::Branch(branch)) => {
842                pending.push(&mut branch.right);
843                next = Some(&mut branch.left);
844            }
845            None => {}
846        }
847    }
848    first.into_iter().chain(leaves).flatten()
849}
850
851/// The elements of a tree from one position up to another, in order and
852/// from either end.
853///
854/// Each end finds its first leaf from the root and keeps the subtrees it
855/// passed on its far side; every later leaf is the first of the nearest of
856/// them, found down its near spine. So each end visits a node at most once,
857/// and visiting `k` elements costs O(k + log n). Skipping with
858/// [`Iterator::nth`] finds the leaf it lands in from the root again.
859#[derive(Clone, Debug)]
860pub(crate) struct Iter<'a, T: Element = Value> {
861    tree: Option<&'a Node<T>>,
862    /// The position of the next element from the front.
863    front: usize,
864    /// One past the position of the next element from the back.
865    back: usize,
866    /// The rest of the leaf the front is in, starting at `front`.
867    head: std::slice::Iter<'a, T>,
868    /// The rest of the leaf the back is in, ending before `back`.
869    tail: std::slice::Iter<'a, T>,
870    /// The subtrees after the front's leaf, the nearest last, or `None`
871    /// until the front has found its leaf from the root.
872    ahead: Option<Vec<&'a Node<T>>>,
873    /// The subtrees before the back's leaf, the nearest last, or `None`
874    /// until the back has found its leaf from the root.
875    behind: Option<Vec<&'a Node<T>>>,
876}
877
878impl<'a, T: Element> Iter<'a, T> {
879    /// Returns the `len` elements of `tree` from `start`.
880    pub(crate) fn new(tree: Option<&'a Node<T>>, start: usize, len: usize) -> Self {
881        Iter {
882            tree,
883            front: start,
884            back: start + len,
885            head: [].iter(),
886            tail: [].iter(),
887            ahead: None,
888            behind: None,
889        }
890    }
891}
892
893impl<'a, T: Element> Iter<'a, T> {
894    /// Moves the front into the leaf holding the next element, which is at
895    /// `front - 1`, and returns that element.
896    #[cold]
897    fn enter_head(&mut self) -> Option<&'a T> {
898        let (node, index) = match self.ahead.as_mut().map(Vec::pop) {
899            Some(next) => (next?, 0),
900            None => (self.tree?, self.front - 1),
901        };
902        let ahead = self.ahead.get_or_insert_with(Vec::new);
903        let (items, at) = chunk_passing(node, index, |side, node| {
904            if side == Side::Right {
905                ahead.push(node);
906            }
907        });
908        let end = items.len().min(at + 1 + (self.back - self.front));
909        self.head = items[at + 1..end].iter();
910        items.get(at)
911    }
912
913    /// Moves the back into the leaf holding the next element from the back,
914    /// which is at `back`, and returns that element.
915    #[cold]
916    fn enter_tail(&mut self) -> Option<&'a T> {
917        let (node, index) = match self.behind.as_mut().map(Vec::pop) {
918            Some(next) => {
919                let next = next?;
920                (next, next.len() - 1)
921            }
922            None => (self.tree?, self.back),
923        };
924        let behind = self.behind.get_or_insert_with(Vec::new);
925        let (items, at) = chunk_passing(node, index, |side, node| {
926            if side == Side::Left {
927                behind.push(node);
928            }
929        });
930        let start = at.saturating_sub(self.back - self.front);
931        self.tail = items[start..at].iter();
932        items.get(at)
933    }
934}
935
936impl<'a, T: Element> Iterator for Iter<'a, T> {
937    type Item = &'a T;
938
939    #[inline]
940    fn next(&mut self) -> Option<&'a T> {
941        if self.front == self.back {
942            return None;
943        }
944        self.front += 1;
945        self.head.next().or_else(|| self.enter_head())
946    }
947
948    /// Skips `n` elements by finding the next leaf from the root, in
949    /// O(log n), rather than visiting each.
950    fn nth(&mut self, n: usize) -> Option<&'a T> {
951        if n >= self.back - self.front {
952            self.front = self.back;
953            return None;
954        }
955        self.front += n + 1;
956        self.ahead = None;
957        self.enter_head()
958    }
959
960    #[inline]
961    fn size_hint(&self) -> (usize, Option<usize>) {
962        let left = self.back - self.front;
963        (left, Some(left))
964    }
965}
966
967impl<'a, T: Element> DoubleEndedIterator for Iter<'a, T> {
968    #[inline]
969    fn next_back(&mut self) -> Option<&'a T> {
970        if self.front == self.back {
971            return None;
972        }
973        self.back -= 1;
974        self.tail.next_back().or_else(|| self.enter_tail())
975    }
976
977    /// Skips `n` elements from the back as [`Iterator::nth`] does from the
978    /// front.
979    fn nth_back(&mut self, n: usize) -> Option<&'a T> {
980        if n >= self.back - self.front {
981            self.back = self.front;
982            return None;
983        }
984        self.back -= n + 1;
985        self.behind = None;
986        self.enter_tail()
987    }
988}
989
990impl<T: Element> ExactSizeIterator for Iter<'_, T> {}
991
992/// Where a key lies among the elements of a tree kept in key order: its
993/// position and its element when an element has it, and otherwise the
994/// position it would take.
995pub(crate) type Found<'a, T> = Result<(usize, &'a T), usize>;
996
997/// Returns where `key` lies among the elements of `tree`, whose keys
998/// ascend: its position and its element when an element has it, and
999/// otherwise the position it would take.
1000///
1001/// The way down compares `key` with the first key of each right subtree it
1002/// passes, which every node keeps, so it makes one comparison per level and
1003/// at most four in the leaf it reaches: O(log n) comparisons in O(log n)
1004/// steps.
1005pub(crate) fn find<'a, T: Keyed>(
1006    mut tree: &'a Node<T>,
1007    key: &Value,
1008) -> Result<Found<'a, T>, DataError> {
1009    let mut before = 0;
1010    loop {
1011        match &*tree.0 {
1012            Inner::Branch(branch) => {
1013                let first = match &*branch.right.0 {
1014                    Inner::Leaf(items, _) => items[0].sort_key(),
1015                    Inner::Branch(right) => &right.first,
1016                };
1017                if compare(key, first)?.is_lt() {
1018                    tree = &branch.left;
1019                } else {
1020                    before += branch.left.len();
1021                    tree = &branch.right;
1022                }
1023            }
1024            Inner::Leaf(items, _) => {
1025                let mut failure = None;
1026                let found = items.binary_search_by(|candidate| {
1027                    compare(candidate.sort_key(), key).unwrap_or_else(|error| {
1028                        failure = Some(error);
1029                        std::cmp::Ordering::Equal
1030                    })
1031                });
1032                if let Some(error) = failure {
1033                    return Err(error);
1034                }
1035                return Ok(match found {
1036                    Ok(at) => Ok((before + at, &items[at])),
1037                    Err(at) => Err(before + at),
1038                });
1039            }
1040        }
1041    }
1042}
1043
1044/// Checks every invariant of `tree` and returns its height, for tests.
1045#[cfg(test)]
1046pub(crate) fn check<T: Element>(tree: &Node<T>) -> u8 {
1047    match &*tree.0 {
1048        Inner::Leaf(items, _) => {
1049            assert!(
1050                (1..=T::LEAF).contains(&items.len()),
1051                "a leaf holds 1 to LEAF elements"
1052            );
1053            0
1054        }
1055        Inner::Branch(branch) => {
1056            let (left, right) = (check(&branch.left), check(&branch.right));
1057            assert!(left.abs_diff(right) <= 1, "subtrees differ by at most one");
1058            assert_eq!(branch.height, left.max(right) + 1, "height is recorded");
1059            assert_eq!(
1060                branch.len,
1061                branch.left.len() + branch.right.len(),
1062                "length is recorded"
1063            );
1064            assert_eq!(
1065                branch.measure,
1066                branch.left.measure().join(branch.right.measure()),
1067                "measure is recorded"
1068            );
1069            branch.height
1070        }
1071    }
1072}
1073
1074/// Checks that every branch of a dictionary's tree keeps the key of its
1075/// first entry, for tests.
1076#[cfg(test)]
1077pub(crate) fn check_keys<T: Keyed>(tree: &Node<T>) {
1078    if let Inner::Branch(branch) = &*tree.0 {
1079        let mut leftmost = &branch.left;
1080        while let Inner::Branch(next) = &*leftmost.0 {
1081            leftmost = &next.left;
1082        }
1083        let Inner::Leaf(items, _) = &*leftmost.0 else {
1084            unreachable!("the walk ends at a leaf")
1085        };
1086        assert_eq!(
1087            compare(&branch.first, items[0].sort_key()),
1088            Ok(std::cmp::Ordering::Equal),
1089            "a branch keeps its first key"
1090        );
1091        check_keys(&branch.left);
1092        check_keys(&branch.right);
1093    }
1094}
1095
1096/// Adds the ids of `tree`'s leaves to `out`, in order, for tests.
1097#[cfg(test)]
1098pub(crate) fn leaves<T: Element>(tree: &Tree<T>, out: &mut Vec<usize>) {
1099    match &*tree.0 {
1100        Inner::Leaf(..) => out.push(tree.id()),
1101        Inner::Branch(branch) => {
1102            leaves(&branch.left, out);
1103            leaves(&branch.right, out);
1104        }
1105    }
1106}