1use 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
40pub(crate) const CHUNK: usize = 8;
46
47pub 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#[derive(Clone, Debug)]
61pub struct Member(Value);
62
63impl Member {
64 pub fn new(value: Value) -> Member {
66 Member(value)
67 }
68
69 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
79pub trait Keyed: Element + sealed::Sealed<Key = Value, Measure = Meta> {
81 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 pub trait Measure: Copy + PartialEq + fmt::Debug {
101 const EMPTY: Self;
103
104 #[must_use]
106 fn join(self, other: Self) -> Self;
107 }
108
109 pub trait Sealed {
111 type Key: Clone + fmt::Debug;
114
115 type Measure: Measure;
117
118 const LEAF: usize;
121
122 fn key(&self) -> &Self::Key;
124
125 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#[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
206pub(crate) type Tree<T = Value> = Node<T>;
208
209#[derive(Clone, Debug)]
211enum Inner<T: Element> {
212 Leaf(Vec<T>, T::Measure),
214 Branch(Branch<T>),
216}
217
218#[derive(Clone, Debug)]
220struct Branch<T: Element> {
221 left: Tree<T>,
222 right: Tree<T>,
223 len: usize,
225 height: u8,
227 measure: T::Measure,
229 first: T::Key,
231}
232
233#[derive(Debug)]
236pub enum Shape<'a, T: Element> {
237 Leaf(&'a [T]),
240 Branch(&'a Node<T>, &'a Node<T>),
243}
244
245impl<T: Element> Node<T> {
246 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 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 pub fn id(&self) -> usize {
285 Arc::as_ptr(&self.0).addr()
286 }
287
288 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 pub fn is_empty(&self) -> bool {
298 false
299 }
300
301 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 pub fn height(&self) -> usize {
318 usize::from(self.level())
319 }
320
321 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 fn level(&self) -> u8 {
331 match &*self.0 {
332 Inner::Leaf(..) => 0,
333 Inner::Branch(branch) => branch.height,
334 }
335 }
336
337 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 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
355pub(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
377fn measure<T: Element>(items: &[T]) -> T::Measure {
379 items
380 .iter()
381 .map(sealed::Sealed::measure)
382 .fold(Measure::EMPTY, Measure::join)
383}
384
385pub(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
392fn 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
404fn 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
413pub(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
435fn 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
447pub(crate) fn join<T: Element>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
453 join_with(left, right, &|_, _| None)
454}
455
456pub(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
494fn 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
524fn 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
532pub(crate) trait Along<T: Element> {
535 fn node(&self, tree: &Tree<T>) -> usize;
537
538 fn item(&self, item: &T) -> usize;
540
541 fn cut(&self, item: &T, at: usize) -> Option<(T, T)>;
545}
546
547struct 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
564pub(crate) type Halves<T> = (Option<Tree<T>>, Option<Tree<T>>);
567
568pub(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
574pub(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 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
622pub(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
629pub(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
640fn 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
670pub(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
697pub(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
724pub(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
750pub(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 pub(crate) static VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
771}
772
773fn visited() {
775 #[cfg(test)]
776 VISITED.with(|visited| visited.set(visited.get() + 1));
777}
778
779#[derive(Clone, Copy, PartialEq, Eq)]
781enum Side {
782 Left,
783 Right,
784}
785
786fn chunk<T: Element>(tree: &Node<T>, index: usize) -> (&[T], usize) {
789 chunk_passing(tree, index, |_, _| {})
790}
791
792fn 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#[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
825pub(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#[derive(Clone, Debug)]
860pub(crate) struct Iter<'a, T: Element = Value> {
861 tree: Option<&'a Node<T>>,
862 front: usize,
864 back: usize,
866 head: std::slice::Iter<'a, T>,
868 tail: std::slice::Iter<'a, T>,
870 ahead: Option<Vec<&'a Node<T>>>,
873 behind: Option<Vec<&'a Node<T>>>,
876}
877
878impl<'a, T: Element> Iter<'a, T> {
879 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 #[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 #[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 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 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
992pub(crate) type Found<'a, T> = Result<(usize, &'a T), usize>;
996
997pub(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#[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#[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#[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}