flow-lang-value 0.1.0-rc.5

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
//! The balanced tree a [`List`](crate::List) keeps its elements in, a
//! [`Dict`](crate::Dict) its entries, a [`Set`](crate::Set) its members and a
//! [`Text`](crate::Text) its runs.
//!
//! A tree is a height-balanced (AVL) binary tree: each leaf holds from one to
//! as many elements as a leaf of their kind holds, in order, each branch
//! records how many elements and how
//! many levels lie below it, what they measure, and the key of the first of
//! them when they are a dictionary's entries, and the two subtrees of every
//! branch differ in height by at most one. Every tree is balanced, however
//! it was made: [`Node::branch`], which rebuilds a tree read from history,
//! restores the balance a foreign writer did not keep. A tree of `k` leaves is therefore less than
//! `1.45 · log2(k + 2)` levels high, so every recursion here is shallow.
//!
//! Nodes are shared through `Arc`. Every operation takes trees by value and
//! returns a new one, rebuilding only the nodes on the path it changes: a node
//! nothing else holds is reused in place, and one another tree still holds is
//! copied, so that tree is untouched. For a tree of `n` elements:
//!
//! - finding the element at a position costs O(log n);
//! - [`push_back`] and [`push_front`] cost O(log n + CHUNK);
//! - [`join`] of trees of heights `a` and `b` costs O(|a − b| + 1), and
//!   [`concat`] O(CHUNK · log n) at worst;
//! - [`split`] and [`cut`] cost O(log n), with a leaf's elements walked and
//!   one of them cut.
//!
//! Deeply nested *values* are not this module's concern: dropping a node
//! drops its elements one by one, and each value's own `Drop` dismantles
//! what it holds without recursing.

use std::fmt;
use std::sync::Arc;

use crate::error::{DataError, StructureError};
use crate::text::Run;
use crate::value::{Meta, Value, compare};

pub(crate) use sealed::Measure;

/// The most values a leaf holds.
///
/// A larger leaf makes a tree shallower and iteration cheaper, and makes
/// each change copy more, in memory and in what history stores for it
/// (`trace.md`, *Lists*, where a leaf holds at most eight).
pub(crate) const CHUNK: usize = 8;

/// What a tree holds: a list's elements, a dictionary's entries as key and
/// value pairs, a set's members, or a text's runs. No other type is one.
pub trait Element: Clone + fmt::Debug + sealed::Sealed {}

impl Element for Value {}

impl Element for (Value, Value) {}

impl Element for Member {}

impl Element for Run {}

/// A set's member: a value that is its own key.
#[derive(Clone, Debug)]
pub struct Member(Value);

impl Member {
    /// Returns the member `value` is.
    pub fn new(value: Value) -> Member {
        Member(value)
    }

    /// Returns the value.
    pub fn value(&self) -> &Value {
        &self.0
    }

    pub(crate) fn value_mut(&mut self) -> &mut Value {
        &mut self.0
    }
}

/// An element kept in key order: a dictionary's entry, or a set's member.
pub trait Keyed: Element + sealed::Sealed<Key = Value, Measure = Meta> {
    /// Returns the key it is sorted by.
    fn sort_key(&self) -> &Value {
        sealed::Sealed::key(self)
    }
}

impl Keyed for (Value, Value) {}

impl Keyed for Member {}

mod sealed {
    use std::fmt;

    use super::{CHUNK, Member};
    use crate::text::{Run, Span};
    use crate::value::{Meta, Value};

    /// What every node records of the elements below it, so that a range of
    /// them is measured from the nodes wholly inside it.
    pub trait Measure: Copy + PartialEq + fmt::Debug {
        /// What no elements measure.
        const EMPTY: Self;

        /// Returns what the elements `self` and `other` measure do together.
        #[must_use]
        fn join(self, other: Self) -> Self;
    }

    /// What a tree reads of what it holds.
    pub trait Sealed {
        /// What a branch keeps of its first element to be searched by: a
        /// dictionary entry's key, and nothing of a list's element.
        type Key: Clone + fmt::Debug;

        /// What every node records of the elements below it.
        type Measure: Measure;

        /// The most elements a leaf holds: as many as one leaf of history
        /// holds (`trace.md`, *Trees*), eight values or one run of text.
        const LEAF: usize;

        /// Returns what a branch keeps of this element.
        fn key(&self) -> &Self::Key;

        /// Returns what this element measures.
        fn measure(&self) -> Self::Measure;
    }

    impl Sealed for Value {
        type Key = ();
        type Measure = Meta;
        const LEAF: usize = CHUNK;

        fn key(&self) -> &() {
            &()
        }

        fn measure(&self) -> Meta {
            Meta::EMPTY.with(self)
        }
    }

    impl Sealed for (Value, Value) {
        type Key = Value;
        type Measure = Meta;
        const LEAF: usize = CHUNK;

        fn key(&self) -> &Value {
            &self.0
        }

        fn measure(&self) -> Meta {
            Meta::EMPTY.with(&self.0).with(&self.1)
        }
    }

    impl Sealed for Member {
        type Key = Value;
        type Measure = Meta;
        const LEAF: usize = CHUNK;

        fn key(&self) -> &Value {
            &self.0
        }

        fn measure(&self) -> Meta {
            Meta::EMPTY.with(&self.0)
        }
    }

    impl Sealed for Run {
        type Key = ();
        type Measure = Span;
        const LEAF: usize = 1;

        fn key(&self) -> &() {
            &()
        }

        fn measure(&self) -> Span {
            self.span()
        }
    }
}

/// A shared node of a tree: a whole tree, or a part of one.
///
/// Cloning one shares it, and two handles to one node have one
/// [`Node::id`]. A list's or a dictionary's tree is made of nodes, which the
/// lists and dictionaries made from it share: [`List::parts`] and
/// [`Dict::root`] read the nodes a value is made of, [`Node::shape`] what
/// each node holds, and [`Node::leaf`] and [`Node::branch`] build a tree
/// again, node by node, so that what was shared stays shared.
///
/// [`List::parts`]: crate::List::parts
/// [`Dict::root`]: crate::Dict::root
#[derive(Debug)]
pub struct Node<T: Element = Value>(Arc<Inner<T>>);

impl<T: Element> Clone for Node<T> {
    fn clone(&self) -> Self {
        Node(Arc::clone(&self.0))
    }
}

/// A shared node: a whole tree, or a part of one.
pub(crate) type Tree<T = Value> = Node<T>;

/// What a node is.
#[derive(Clone, Debug)]
enum Inner<T: Element> {
    /// From one to `T::LEAF` elements, in order, and what they measure.
    Leaf(Vec<T>, T::Measure),
    /// The elements of `left`, then those of `right`.
    Branch(Branch<T>),
}

/// Two subtrees whose heights differ by at most one.
#[derive(Clone, Debug)]
struct Branch<T: Element> {
    left: Tree<T>,
    right: Tree<T>,
    /// How many elements lie below.
    len: usize,
    /// How many levels lie below: one more than the higher subtree's.
    height: u8,
    /// What the elements below measure, exactly.
    measure: T::Measure,
    /// What the first element below keeps to be searched by.
    first: T::Key,
}

/// What a node holds: its elements, when it is a leaf, or its two
/// subtrees, when it is a branch.
#[derive(Debug)]
pub enum Shape<'a, T: Element> {
    /// From one to as many elements as a leaf of their kind holds, in
    /// order.
    Leaf(&'a [T]),
    /// The elements of the left node, then those of the right; each holds at
    /// least one.
    Branch(&'a Node<T>, &'a Node<T>),
}

impl<T: Element> Node<T> {
    /// Returns the leaf holding `items`.
    ///
    /// # Errors
    ///
    /// [`StructureError::Leaf`] unless they number from one to as many as a
    /// leaf of their kind holds.
    pub fn leaf(items: Vec<T>) -> Result<Self, StructureError> {
        if (1..=T::LEAF).contains(&items.len()) {
            Ok(leaf(items))
        } else {
            Err(StructureError::Leaf)
        }
    }

    /// Returns the tree holding `left`'s elements, then `right`'s.
    ///
    /// When the two are as high as each other or within one level, which
    /// they are whenever this crate made the tree being rebuilt, this is one
    /// new branch over exactly `left` and `right`, so each stays shared.
    /// Every tree here is balanced (AVL), and indexing, insertion, removal,
    /// joining and cutting rely on that for their cost; so when the two
    /// differ by more, as a tree from another writer may, the lower is
    /// joined into the higher's near spine and the branches on that path
    /// are rebuilt balanced, in O(difference in height). Every node below
    /// that path stays shared, and the elements and their order are the
    /// same either way.
    pub fn branch(left: Self, right: Self) -> Self {
        if left.level().abs_diff(right.level()) <= 1 {
            branch(left, right)
        } else {
            join(left, right)
        }
    }

    /// Returns what tells this node apart from every other node alive: two
    /// handles answer alike exactly when they share one node. The answer
    /// means something only while a handle to the node is kept, since a
    /// node made after this one is dropped may answer the same.
    pub fn id(&self) -> usize {
        Arc::as_ptr(&self.0).addr()
    }

    /// Returns how many elements lie in the tree.
    pub fn len(&self) -> usize {
        match &*self.0 {
            Inner::Leaf(items, _) => items.len(),
            Inner::Branch(branch) => branch.len,
        }
    }

    /// Returns `false`: a node holds at least one element.
    pub fn is_empty(&self) -> bool {
        false
    }

    /// Returns the tree of the `count` elements that follow this tree's
    /// first `skip`, sharing every node the cut does not pass through.
    ///
    /// # Errors
    ///
    /// [`StructureError::Window`] unless `count` is at least one and the
    /// tree holds `skip + count` elements.
    pub fn window(&self, skip: usize, count: usize) -> Result<Self, StructureError> {
        let fits = count > 0 && skip.checked_add(count).is_some_and(|end| end <= self.len());
        if !fits {
            return Err(StructureError::Window);
        }
        range(self.clone(), skip, count).ok_or(StructureError::Window)
    }

    /// Returns how many levels of branches lie below: 0 for a leaf.
    pub fn height(&self) -> usize {
        usize::from(self.level())
    }

    /// Returns what the node holds.
    pub fn shape(&self) -> Shape<'_, T> {
        match &*self.0 {
            Inner::Leaf(items, _) => Shape::Leaf(items),
            Inner::Branch(branch) => Shape::Branch(&branch.left, &branch.right),
        }
    }

    /// Returns how many levels lie below: 0 for a leaf.
    fn level(&self) -> u8 {
        match &*self.0 {
            Inner::Leaf(..) => 0,
            Inner::Branch(branch) => branch.height,
        }
    }

    /// Returns what the elements below measure, exactly, as every node
    /// records it.
    pub(crate) fn measure(&self) -> T::Measure {
        match &*self.0 {
            Inner::Leaf(_, measure) => *measure,
            Inner::Branch(branch) => branch.measure,
        }
    }

    /// Returns what the first element below keeps to be searched by.
    fn first(&self) -> T::Key {
        match &*self.0 {
            Inner::Leaf(items, _) => sealed::Sealed::key(&items[0]).clone(),
            Inner::Branch(branch) => branch.first.clone(),
        }
    }
}

/// Returns what the `len` elements of `tree` from `start` measure,
/// exactly: the nodes wholly inside the range answer from what they record,
/// so only the two paths to its ends are walked, in O(log n + CHUNK).
pub(crate) fn range_measure<T: Element>(tree: &Tree<T>, start: usize, len: usize) -> T::Measure {
    if len == 0 {
        return Measure::EMPTY;
    }
    if start == 0 && len == tree.len() {
        return tree.measure();
    }
    match &*tree.0 {
        Inner::Leaf(items, _) => measure(&items[start..start + len]),
        Inner::Branch(branch) => {
            let before = branch.left.len();
            let in_left = before.saturating_sub(start).min(len);
            let left = range_measure(&branch.left, start.min(before), in_left);
            let right = range_measure(&branch.right, start.saturating_sub(before), len - in_left);
            left.join(right)
        }
    }
}

/// Returns what `items` measure together.
fn measure<T: Element>(items: &[T]) -> T::Measure {
    items
        .iter()
        .map(sealed::Sealed::measure)
        .fold(Measure::EMPTY, Measure::join)
}

/// Returns the leaf holding `items`, which must number from one to
/// `T::LEAF`.
pub(crate) fn leaf<T: Element>(items: Vec<T>) -> Tree<T> {
    let measure = measure(&items);
    Node(Arc::new(Inner::Leaf(items, measure)))
}

/// Returns the branch over `left` and `right`, which must be balanced.
fn branch<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
    Node(Arc::new(Inner::Branch(Branch {
        len: left.len() + right.len(),
        height: left.level().max(right.level()) + 1,
        measure: left.measure().join(right.measure()),
        first: left.first(),
        left,
        right,
    })))
}

/// Returns the subtrees of `tree`, a branch: moved out when nothing else
/// holds it, shared otherwise.
fn children<T: Element>(tree: Tree<T>) -> (Tree<T>, Tree<T>) {
    let Inner::Branch(branch) = Arc::unwrap_or_clone(tree.0) else {
        unreachable!("a leaf has no subtrees")
    };
    (branch.left, branch.right)
}

/// Returns the tree of `items`, in order, or `None` when there are none.
///
/// The leaves are full but for the last, and the tree is as low as their
/// number allows.
pub(crate) fn build<T: Element>(items: impl IntoIterator<Item = T>) -> Option<Tree<T>> {
    let mut items = items.into_iter();
    let first: Vec<T> = items.by_ref().take(T::LEAF).collect();
    if first.len() < T::LEAF {
        return (!first.is_empty()).then(|| leaf(first));
    }
    let mut leaves = vec![leaf(first)];
    loop {
        let chunk: Vec<T> = items.by_ref().take(T::LEAF).collect();
        if chunk.is_empty() {
            break;
        }
        leaves.push(leaf(chunk));
    }
    let count = leaves.len();
    Some(balanced(&mut leaves.into_iter(), count))
}

/// Returns the next `count` of `leaves`, at least one, under a tree whose
/// two halves at every branch hold leaf counts differing by at most one, so
/// their heights do too.
fn balanced<T: Element>(leaves: &mut impl Iterator<Item = Tree<T>>, count: usize) -> Tree<T> {
    if count == 1 {
        return leaves.next().expect("one leaf is left for each count");
    }
    let left = balanced(leaves, count / 2);
    let right = balanced(leaves, count - count / 2);
    branch(left, right)
}

/// Returns the tree holding `left`'s elements, then `right`'s.
///
/// The lower tree descends the near spine of the higher until it meets a
/// subtree as high as it, and each branch rebuilt on the way back up is
/// rebalanced, so the cost is the difference in height.
pub(crate) fn join<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
    join_with(left, right, &|_, _| None)
}

/// Returns the tree holding `left`'s elements, then `right`'s, as [`join`]
/// does, but where `fuse` makes one tree of the two it meets on the way
/// down, at the top or where the lower tree lands, that tree takes their
/// place.
///
/// A fused tree may be lower than the two were, so the branches above it
/// are rejoined as [`join`] joins any two, and the cost stays the difference
/// in height.
pub(crate) fn join_with<T: Element>(
    left: Tree<T>,
    right: Tree<T>,
    fuse: &impl Fn(&Tree<T>, &Tree<T>) -> Option<Tree<T>>,
) -> Tree<T> {
    if let Some(fused) = fuse(&left, &right) {
        return fused;
    }
    let (low, high) = (left.level(), right.level());
    if low > high + 1 {
        let (outer, inner) = children(left);
        let joined = join_with(inner, right, fuse);
        if outer.level().abs_diff(joined.level()) <= 2 {
            balance(outer, joined)
        } else {
            join(outer, joined)
        }
    } else if high > low + 1 {
        let (inner, outer) = children(right);
        let joined = join_with(left, inner, fuse);
        if outer.level().abs_diff(joined.level()) <= 2 {
            balance(joined, outer)
        } else {
            join(joined, outer)
        }
    } else {
        branch(left, right)
    }
}

/// Returns a balanced tree holding `left`'s elements, then `right`'s, when
/// each is balanced and their heights differ by at most two.
///
/// A difference of two is the case AVL insertion repairs: one rotation when
/// the higher side's outer subtree is at least as high as its inner one, and
/// two when it is lower. Either way the result is balanced, and as high as
/// the higher side or one less.
fn balance<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
    let (low, high) = (left.level(), right.level());
    if high > low + 1 {
        let (inner, outer) = children(right);
        if inner.level() > outer.level() {
            let (a, b) = children(inner);
            branch(branch(left, a), branch(b, outer))
        } else {
            branch(branch(left, inner), outer)
        }
    } else if low > high + 1 {
        let (outer, inner) = children(left);
        if inner.level() > outer.level() {
            let (a, b) = children(inner);
            branch(branch(outer, a), branch(b, right))
        } else {
            branch(outer, branch(inner, right))
        }
    } else {
        branch(left, right)
    }
}

/// Returns `left` joined to `right` when both are present, or whichever is.
fn join_either<T: Element>(left: Option<Tree<T>>, right: Option<Tree<T>>) -> Option<Tree<T>> {
    match (left, right) {
        (Some(left), Some(right)) => Some(join(left, right)),
        (left, right) => left.or(right),
    }
}

/// A way of counting positions along a tree's elements, by which [`cut`]
/// finds where to split it: by element, or along what the elements measure.
pub(crate) trait Along<T: Element> {
    /// Returns how many positions the elements of `tree` span.
    fn node(&self, tree: &Tree<T>) -> usize;

    /// Returns how many positions `item` spans.
    fn item(&self, item: &T) -> usize;

    /// Returns `item` cut into what lies before position `at`, which is
    /// inside it, and what lies from there, or `None` when it cannot be cut
    /// there.
    fn cut(&self, item: &T, at: usize) -> Option<(T, T)>;
}

/// Counting positions by element: a cut always falls between two.
struct Count;

impl<T: Element> Along<T> for Count {
    fn node(&self, tree: &Tree<T>) -> usize {
        tree.len()
    }

    fn item(&self, _: &T) -> usize {
        1
    }

    fn cut(&self, _: &T, _: usize) -> Option<(T, T)> {
        unreachable!("a position counted by element lies between two")
    }
}

/// The trees of what lies before a position and of the rest, each `None`
/// when it would hold none.
pub(crate) type Halves<T> = (Option<Tree<T>>, Option<Tree<T>>);

/// Returns the tree of `tree`'s first `at` elements and that of the rest,
/// each `None` when it would hold none.
pub(crate) fn split<T: Element>(tree: Tree<T>, at: usize) -> Halves<T> {
    cut(tree, at, &Count).expect("a position counted by element lies between two")
}

/// Returns the tree of what lies before position `at` of `tree`, counted
/// `along` it, and that of the rest, each `None` when it would hold none;
/// or `None` when the element `at` falls inside cannot be cut there.
///
/// Cutting descends to the position, cuts the one element it falls inside,
/// and joins the subtrees it passes on either side on the way back up.
/// Those joins' costs telescope: each is the difference between consecutive
/// heights, so the whole is O(log n), with one leaf's elements walked.
pub(crate) fn cut<T: Element>(
    tree: Tree<T>,
    at: usize,
    along: &impl Along<T>,
) -> Option<Halves<T>> {
    if at == 0 {
        return Some((None, Some(tree)));
    }
    if at >= along.node(&tree) {
        return Some((Some(tree), None));
    }
    if let Inner::Leaf(items, _) = &*tree.0 {
        let mut before = 0;
        let mut index = 0;
        while before + along.item(&items[index]) <= at {
            before += along.item(&items[index]);
            index += 1;
        }
        // The element is cut where the tree holds it, so what cutting it
        // learns stays with it for the next cut.
        let mut head = items[..index].to_vec();
        let mut rest = items[index..].to_vec();
        if at > before {
            let (first, second) = along.cut(&items[index], at - before)?;
            head.push(first);
            rest[0] = second;
        }
        return Some((Some(leaf(head)), Some(leaf(rest))));
    }
    let (left, right) = children(tree);
    let before = along.node(&left);
    Some(if at <= before {
        let (first, rest) = cut(left, at, along)?;
        (first, join_either(rest, Some(right)))
    } else {
        let (first, rest) = cut(right, at - before, along)?;
        (join_either(Some(left), first), rest)
    })
}

/// Returns the tree of the `len` elements of `tree` from `start`, or `None`
/// when there are none.
pub(crate) fn range<T: Element>(tree: Tree<T>, start: usize, len: usize) -> Option<Tree<T>> {
    let (_, rest) = split(tree, start);
    split(rest?, len).0
}

/// Returns `tree` with `item` added at the end.
///
/// The item joins the last leaf when that has room, which copies the leaf and
/// the path to it if another tree holds them; otherwise it is a new leaf.
pub(crate) fn push_back<T: Element>(mut tree: Tree<T>, item: T) -> Tree<T> {
    match add_at_back(&mut tree, item) {
        None => tree,
        Some(item) => join(tree, leaf(vec![item])),
    }
}

/// Adds `item` to the last leaf of `tree` when that has room, copying each
/// node on the way that another tree holds, or returns it when the leaf is
/// full.
///
/// The way down is one pass: a full leaf is found only once the branches
/// above it are made this tree's own, which costs a copy of each of them that
/// another tree holds, and `join` then reuses them.
fn add_at_back<T: Element>(tree: &mut Tree<T>, item: T) -> Option<T> {
    if let Inner::Leaf(items, _) = &*tree.0
        && items.len() == T::LEAF
    {
        return Some(item);
    }
    match Arc::make_mut(&mut tree.0) {
        Inner::Leaf(items, measure) => {
            *measure = measure.join(sealed::Sealed::measure(&item));
            items.push(item);
        }
        Inner::Branch(branch) => {
            let full = add_at_back(&mut branch.right, item);
            if full.is_none() {
                branch.len += 1;
                branch.measure = branch.left.measure().join(branch.right.measure());
            }
            return full;
        }
    }
    None
}

/// Returns `tree` with `item` put in at position `at`, at most its length.
///
/// The item joins the leaf at that position, copied if another tree holds
/// it; a leaf that would hold more than `T::LEAF` splits in two, and each
/// branch on the way back up is rebalanced. The cost is O(log n + CHUNK).
pub(crate) fn insert<T: Element>(tree: Tree<T>, at: usize, item: T) -> Tree<T> {
    match Arc::unwrap_or_clone(tree.0) {
        Inner::Leaf(mut items, _) => {
            items.insert(at, item);
            if items.len() <= T::LEAF {
                leaf(items)
            } else {
                let rest = items.split_off(items.len() / 2);
                branch(leaf(items), leaf(rest))
            }
        }
        Inner::Branch(Branch { left, right, .. }) => {
            let before = left.len();
            if at <= before {
                balance(insert(left, at, item), right)
            } else {
                balance(left, insert(right, at - before, item))
            }
        }
    }
}

/// Returns `tree` with the element at `at`, which must be less than its
/// length, replaced by `item`, copying only the path to it.
pub(crate) fn replace<T: Element>(mut tree: Tree<T>, at: usize, item: T) -> Tree<T> {
    fn set<T: Element>(tree: &mut Tree<T>, at: usize, item: T) {
        match Arc::make_mut(&mut tree.0) {
            Inner::Leaf(items, recorded) => {
                items[at] = item;
                *recorded = measure(items);
            }
            Inner::Branch(branch) => {
                let before = branch.left.len();
                if at < before {
                    set(&mut branch.left, at, item);
                } else {
                    set(&mut branch.right, at - before, item);
                }
                branch.measure = branch.left.measure().join(branch.right.measure());
                if at == 0 {
                    branch.first = branch.left.first();
                }
            }
        }
    }
    set(&mut tree, at, item);
    tree
}

/// Returns `tree` without the element at `at`, which must be less than its
/// length, or `None` when that was its only element. A leaf left empty is
/// dropped, and each branch on the way back up is rebalanced.
pub(crate) fn remove<T: Element>(tree: Tree<T>, at: usize) -> Option<Tree<T>> {
    match Arc::unwrap_or_clone(tree.0) {
        Inner::Leaf(mut items, _) => {
            items.remove(at);
            (!items.is_empty()).then(|| leaf(items))
        }
        Inner::Branch(Branch { left, right, .. }) => {
            let before = left.len();
            Some(if at < before {
                match remove(left, at) {
                    Some(left) => balance(left, right),
                    None => right,
                }
            } else {
                match remove(right, at - before) {
                    Some(right) => balance(left, right),
                    None => left,
                }
            })
        }
    }
}

/// Returns the tree holding `left`'s elements, then `right`'s.
///
/// A right side of at most a leaf's elements is added to the left one
/// element at a time, so that joining a short list fills the leaf at the seam
/// rather than leaving a short leaf in the middle; a longer one is joined as
/// it is.
pub(crate) fn concat<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
    if right.len() <= T::LEAF {
        Iter::new(Some(&right), 0, right.len())
            .cloned()
            .fold(left, push_back)
    } else {
        join(left, right)
    }
}

#[cfg(test)]
thread_local! {
    /// How many nodes finding leaves has visited on this thread, so a test
    /// can bound the work walking a tree does.
    pub(crate) static VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Counts one node visited on the way to a leaf, in tests.
fn visited() {
    #[cfg(test)]
    VISITED.with(|visited| visited.set(visited.get() + 1));
}

/// The side of a branch a way down did not take.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
    Left,
    Right,
}

/// Returns the leaf holding the element at `index`, which must be less than
/// `tree`'s length, and the element's position within that leaf.
fn chunk<T: Element>(tree: &Node<T>, index: usize) -> (&[T], usize) {
    chunk_passing(tree, index, |_, _| {})
}

/// Returns what [`chunk`] does, handing `passed` each subtree the way down
/// passes and the side it lies on, nearest the root first.
fn chunk_passing<'a, T: Element>(
    mut tree: &'a Node<T>,
    mut index: usize,
    mut passed: impl FnMut(Side, &'a Node<T>),
) -> (&'a [T], usize) {
    loop {
        visited();
        match &*tree.0 {
            Inner::Leaf(items, _) => return (items, index),
            Inner::Branch(branch) => {
                let before = branch.left.len();
                if index < before {
                    passed(Side::Right, &branch.right);
                    tree = &branch.left;
                } else {
                    index -= before;
                    passed(Side::Left, &branch.left);
                    tree = &branch.right;
                }
            }
        }
    }
}

/// Returns the element at `index`, which must be less than `tree`'s length.
#[inline]
pub(crate) fn get<T: Element>(tree: &Node<T>, index: usize) -> &T {
    let (items, at) = chunk(tree, index);
    &items[at]
}

/// Returns the elements of every leaf of `tree` that nothing else holds,
/// along with every node above it: what dropping `tree` would drop.
///
/// A tree another holds, or one of a single leaf, which is most of the lists
/// a run drops, costs no allocation.
pub(crate) fn unshared<T: Element>(tree: &mut Tree<T>) -> impl Iterator<Item = &mut T> {
    let mut first = None;
    let mut leaves: Vec<&mut Vec<T>> = Vec::new();
    let mut pending: Vec<&mut Tree<T>> = Vec::new();
    let mut next = Some(tree);
    while let Some(node) = next.take().or_else(|| pending.pop()) {
        match Arc::get_mut(&mut node.0) {
            Some(Inner::Leaf(items, _)) => match first {
                None => first = Some(items),
                Some(_) => leaves.push(items),
            },
            Some(Inner::Branch(branch)) => {
                pending.push(&mut branch.right);
                next = Some(&mut branch.left);
            }
            None => {}
        }
    }
    first.into_iter().chain(leaves).flatten()
}

/// The elements of a tree from one position up to another, in order and
/// from either end.
///
/// Each end finds its first leaf from the root and keeps the subtrees it
/// passed on its far side; every later leaf is the first of the nearest of
/// them, found down its near spine. So each end visits a node at most once,
/// and visiting `k` elements costs O(k + log n). Skipping with
/// [`Iterator::nth`] finds the leaf it lands in from the root again.
#[derive(Clone, Debug)]
pub(crate) struct Iter<'a, T: Element = Value> {
    tree: Option<&'a Node<T>>,
    /// The position of the next element from the front.
    front: usize,
    /// One past the position of the next element from the back.
    back: usize,
    /// The rest of the leaf the front is in, starting at `front`.
    head: std::slice::Iter<'a, T>,
    /// The rest of the leaf the back is in, ending before `back`.
    tail: std::slice::Iter<'a, T>,
    /// The subtrees after the front's leaf, the nearest last, or `None`
    /// until the front has found its leaf from the root.
    ahead: Option<Vec<&'a Node<T>>>,
    /// The subtrees before the back's leaf, the nearest last, or `None`
    /// until the back has found its leaf from the root.
    behind: Option<Vec<&'a Node<T>>>,
}

impl<'a, T: Element> Iter<'a, T> {
    /// Returns the `len` elements of `tree` from `start`.
    pub(crate) fn new(tree: Option<&'a Node<T>>, start: usize, len: usize) -> Self {
        Iter {
            tree,
            front: start,
            back: start + len,
            head: [].iter(),
            tail: [].iter(),
            ahead: None,
            behind: None,
        }
    }
}

impl<'a, T: Element> Iter<'a, T> {
    /// Moves the front into the leaf holding the next element, which is at
    /// `front - 1`, and returns that element.
    #[cold]
    fn enter_head(&mut self) -> Option<&'a T> {
        let (node, index) = match self.ahead.as_mut().map(Vec::pop) {
            Some(next) => (next?, 0),
            None => (self.tree?, self.front - 1),
        };
        let ahead = self.ahead.get_or_insert_with(Vec::new);
        let (items, at) = chunk_passing(node, index, |side, node| {
            if side == Side::Right {
                ahead.push(node);
            }
        });
        let end = items.len().min(at + 1 + (self.back - self.front));
        self.head = items[at + 1..end].iter();
        items.get(at)
    }

    /// Moves the back into the leaf holding the next element from the back,
    /// which is at `back`, and returns that element.
    #[cold]
    fn enter_tail(&mut self) -> Option<&'a T> {
        let (node, index) = match self.behind.as_mut().map(Vec::pop) {
            Some(next) => {
                let next = next?;
                (next, next.len() - 1)
            }
            None => (self.tree?, self.back),
        };
        let behind = self.behind.get_or_insert_with(Vec::new);
        let (items, at) = chunk_passing(node, index, |side, node| {
            if side == Side::Left {
                behind.push(node);
            }
        });
        let start = at.saturating_sub(self.back - self.front);
        self.tail = items[start..at].iter();
        items.get(at)
    }
}

impl<'a, T: Element> Iterator for Iter<'a, T> {
    type Item = &'a T;

    #[inline]
    fn next(&mut self) -> Option<&'a T> {
        if self.front == self.back {
            return None;
        }
        self.front += 1;
        self.head.next().or_else(|| self.enter_head())
    }

    /// Skips `n` elements by finding the next leaf from the root, in
    /// O(log n), rather than visiting each.
    fn nth(&mut self, n: usize) -> Option<&'a T> {
        if n >= self.back - self.front {
            self.front = self.back;
            return None;
        }
        self.front += n + 1;
        self.ahead = None;
        self.enter_head()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = self.back - self.front;
        (left, Some(left))
    }
}

impl<'a, T: Element> DoubleEndedIterator for Iter<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> {
        if self.front == self.back {
            return None;
        }
        self.back -= 1;
        self.tail.next_back().or_else(|| self.enter_tail())
    }

    /// Skips `n` elements from the back as [`Iterator::nth`] does from the
    /// front.
    fn nth_back(&mut self, n: usize) -> Option<&'a T> {
        if n >= self.back - self.front {
            self.back = self.front;
            return None;
        }
        self.back -= n + 1;
        self.behind = None;
        self.enter_tail()
    }
}

impl<T: Element> ExactSizeIterator for Iter<'_, T> {}

/// Where a key lies among the elements of a tree kept in key order: its
/// position and its element when an element has it, and otherwise the
/// position it would take.
pub(crate) type Found<'a, T> = Result<(usize, &'a T), usize>;

/// Returns where `key` lies among the elements of `tree`, whose keys
/// ascend: its position and its element when an element has it, and
/// otherwise the position it would take.
///
/// The way down compares `key` with the first key of each right subtree it
/// passes, which every node keeps, so it makes one comparison per level and
/// at most four in the leaf it reaches: O(log n) comparisons in O(log n)
/// steps.
pub(crate) fn find<'a, T: Keyed>(
    mut tree: &'a Node<T>,
    key: &Value,
) -> Result<Found<'a, T>, DataError> {
    let mut before = 0;
    loop {
        match &*tree.0 {
            Inner::Branch(branch) => {
                let first = match &*branch.right.0 {
                    Inner::Leaf(items, _) => items[0].sort_key(),
                    Inner::Branch(right) => &right.first,
                };
                if compare(key, first)?.is_lt() {
                    tree = &branch.left;
                } else {
                    before += branch.left.len();
                    tree = &branch.right;
                }
            }
            Inner::Leaf(items, _) => {
                let mut failure = None;
                let found = items.binary_search_by(|candidate| {
                    compare(candidate.sort_key(), key).unwrap_or_else(|error| {
                        failure = Some(error);
                        std::cmp::Ordering::Equal
                    })
                });
                if let Some(error) = failure {
                    return Err(error);
                }
                return Ok(match found {
                    Ok(at) => Ok((before + at, &items[at])),
                    Err(at) => Err(before + at),
                });
            }
        }
    }
}

/// Checks every invariant of `tree` and returns its height, for tests.
#[cfg(test)]
pub(crate) fn check<T: Element>(tree: &Node<T>) -> u8 {
    match &*tree.0 {
        Inner::Leaf(items, _) => {
            assert!(
                (1..=T::LEAF).contains(&items.len()),
                "a leaf holds 1 to LEAF elements"
            );
            0
        }
        Inner::Branch(branch) => {
            let (left, right) = (check(&branch.left), check(&branch.right));
            assert!(left.abs_diff(right) <= 1, "subtrees differ by at most one");
            assert_eq!(branch.height, left.max(right) + 1, "height is recorded");
            assert_eq!(
                branch.len,
                branch.left.len() + branch.right.len(),
                "length is recorded"
            );
            assert_eq!(
                branch.measure,
                branch.left.measure().join(branch.right.measure()),
                "measure is recorded"
            );
            branch.height
        }
    }
}

/// Checks that every branch of a dictionary's tree keeps the key of its
/// first entry, for tests.
#[cfg(test)]
pub(crate) fn check_keys<T: Keyed>(tree: &Node<T>) {
    if let Inner::Branch(branch) = &*tree.0 {
        let mut leftmost = &branch.left;
        while let Inner::Branch(next) = &*leftmost.0 {
            leftmost = &next.left;
        }
        let Inner::Leaf(items, _) = &*leftmost.0 else {
            unreachable!("the walk ends at a leaf")
        };
        assert_eq!(
            compare(&branch.first, items[0].sort_key()),
            Ok(std::cmp::Ordering::Equal),
            "a branch keeps its first key"
        );
        check_keys(&branch.left);
        check_keys(&branch.right);
    }
}

/// Adds the ids of `tree`'s leaves to `out`, in order, for tests.
#[cfg(test)]
pub(crate) fn leaves<T: Element>(tree: &Tree<T>, out: &mut Vec<usize>) {
    match &*tree.0 {
        Inner::Leaf(..) => out.push(tree.id()),
        Inner::Branch(branch) => {
            leaves(&branch.left, out);
            leaves(&branch.right, out);
        }
    }
}