Skip to main content

sum_tree/
sum_tree.rs

1mod cursor;
2#[cfg(any(test, feature = "test-support"))]
3pub mod property_test;
4mod tree_map;
5
6pub use cursor::{Cursor, FilterCursor, Iter};
7use heapless::Vec as ArrayVec;
8use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator as _};
9use std::marker::PhantomData;
10use std::mem;
11use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
12pub use tree_map::{MapSeekTarget, TreeMap, TreeSet};
13use ztracing::instrument;
14
15#[cfg(test)]
16pub const TREE_BASE: usize = 2;
17#[cfg(not(test))]
18pub const TREE_BASE: usize = 6;
19
20// Helper for when we cannot use ArrayVec::<T>::push().unwrap() as T doesn't impl Debug
21trait CapacityResultExt {
22    fn unwrap_oob(self);
23}
24
25impl<T> CapacityResultExt for Result<(), T> {
26    fn unwrap_oob(self) {
27        self.unwrap_or_else(|_| panic!("item should fit into fixed size ArrayVec"))
28    }
29}
30
31/// An item that can be stored in a [`SumTree`]
32///
33/// Must be summarized by a type that implements [`Summary`]
34pub trait Item: Clone {
35    type Summary: Summary;
36
37    fn summary(&self, cx: <Self::Summary as Summary>::Context<'_>) -> Self::Summary;
38}
39
40/// An [`Item`] whose summary has a specific key that can be used to identify it
41pub trait KeyedItem: Item {
42    type Key: for<'a> Dimension<'a, Self::Summary> + Ord;
43
44    fn key(&self) -> Self::Key;
45}
46
47/// A type that describes the Sum of all [`Item`]s in a subtree of the [`SumTree`]
48///
49/// Each Summary type can have multiple [`Dimension`]s that it measures,
50/// which can be used to navigate the tree
51pub trait Summary: Clone {
52    type Context<'a>: Copy;
53    fn zero<'a>(cx: Self::Context<'a>) -> Self;
54    fn add_summary<'a>(&mut self, summary: &Self, cx: Self::Context<'a>);
55}
56
57pub trait ContextLessSummary: Clone {
58    fn zero() -> Self;
59    fn add_summary(&mut self, summary: &Self);
60}
61
62impl<T: ContextLessSummary> Summary for T {
63    type Context<'a> = ();
64
65    fn zero((): ()) -> Self {
66        T::zero()
67    }
68
69    fn add_summary(&mut self, summary: &Self, (): ()) {
70        T::add_summary(self, summary)
71    }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub struct NoSummary;
76
77/// Catch-all implementation for when you need something that implements [`Summary`] without a specific type.
78/// We implement it on a `NoSummary` instead of re-using `()`, as that avoids blanket impl collisions with `impl<T: Summary> Dimension for T`
79/// (as we also need unit type to be a fill-in dimension)
80impl ContextLessSummary for NoSummary {
81    fn zero() -> Self {
82        NoSummary
83    }
84
85    fn add_summary(&mut self, _: &Self) {}
86}
87
88/// Each [`Summary`] type can have more than one [`Dimension`] type that it measures.
89///
90/// You can use dimensions to seek to a specific location in the [`SumTree`]
91///
92/// # Example:
93/// Zed's rope has a `TextSummary` type that summarizes lines, characters, and bytes.
94/// Each of these are different dimensions we may want to seek to
95pub trait Dimension<'a, S: Summary>: Clone {
96    fn zero(cx: S::Context<'_>) -> Self;
97
98    fn add_summary(&mut self, summary: &'a S, cx: S::Context<'_>);
99    #[must_use]
100    fn with_added_summary(mut self, summary: &'a S, cx: S::Context<'_>) -> Self {
101        self.add_summary(summary, cx);
102        self
103    }
104
105    fn from_summary(summary: &'a S, cx: S::Context<'_>) -> Self {
106        let mut dimension = Self::zero(cx);
107        dimension.add_summary(summary, cx);
108        dimension
109    }
110}
111
112impl<'a, T: Summary> Dimension<'a, T> for T {
113    fn zero(cx: T::Context<'_>) -> Self {
114        Summary::zero(cx)
115    }
116
117    fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) {
118        Summary::add_summary(self, summary, cx);
119    }
120}
121
122pub trait SeekTarget<'a, S: Summary, D: Dimension<'a, S>> {
123    fn cmp(&self, cursor_location: &D, cx: S::Context<'_>) -> Ordering;
124}
125
126impl<'a, S: Summary, D: Dimension<'a, S> + Ord> SeekTarget<'a, S, D> for D {
127    fn cmp(&self, cursor_location: &Self, _: S::Context<'_>) -> Ordering {
128        Ord::cmp(self, cursor_location)
129    }
130}
131
132impl<'a, T: Summary> Dimension<'a, T> for () {
133    fn zero(_: T::Context<'_>) -> Self {}
134
135    fn add_summary(&mut self, _: &'a T, _: T::Context<'_>) {}
136}
137
138#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
139pub struct Dimensions<D1, D2, D3 = ()>(pub D1, pub D2, pub D3);
140
141impl<'a, T: Summary, D1: Dimension<'a, T>, D2: Dimension<'a, T>, D3: Dimension<'a, T>>
142    Dimension<'a, T> for Dimensions<D1, D2, D3>
143{
144    fn zero(cx: T::Context<'_>) -> Self {
145        Dimensions(D1::zero(cx), D2::zero(cx), D3::zero(cx))
146    }
147
148    fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) {
149        self.0.add_summary(summary, cx);
150        self.1.add_summary(summary, cx);
151        self.2.add_summary(summary, cx);
152    }
153}
154
155impl<'a, S, D1, D2, D3> SeekTarget<'a, S, Dimensions<D1, D2, D3>> for D1
156where
157    S: Summary,
158    D1: SeekTarget<'a, S, D1> + Dimension<'a, S>,
159    D2: Dimension<'a, S>,
160    D3: Dimension<'a, S>,
161{
162    fn cmp(&self, cursor_location: &Dimensions<D1, D2, D3>, cx: S::Context<'_>) -> Ordering {
163        self.cmp(&cursor_location.0, cx)
164    }
165}
166
167/// Bias is used to settle ambiguities when determining positions in an ordered sequence.
168///
169/// The primary use case is for text, where Bias influences
170/// which character an offset or anchor is associated with.
171///
172/// # Examples
173/// Given the buffer `AˇBCD`:
174/// - The offset of the cursor is 1
175/// - [Bias::Left] would attach the cursor to the character `A`
176/// - [Bias::Right] would attach the cursor to the character `B`
177///
178/// Given the buffer `A«BCˇ»D`:
179/// - The offset of the cursor is 3, and the selection is from 1 to 3
180/// - The left anchor of the selection has [Bias::Right], attaching it to the character `B`
181/// - The right anchor of the selection has [Bias::Left], attaching it to the character `C`
182///
183/// Given the buffer `{ˇ<...>`, where `<...>` is a folded region:
184/// - The display offset of the cursor is 1, but the offset in the buffer is determined by the bias
185/// - [Bias::Left] would attach the cursor to the character `{`, with a buffer offset of 1
186/// - [Bias::Right] would attach the cursor to the first character of the folded region,
187///   and the buffer offset would be the offset of the first character of the folded region
188#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Default)]
189pub enum Bias {
190    /// Attach to the character on the left
191    #[default]
192    Left,
193    /// Attach to the character on the right
194    Right,
195}
196
197impl Bias {
198    pub fn invert(self) -> Self {
199        match self {
200            Self::Left => Self::Right,
201            Self::Right => Self::Left,
202        }
203    }
204}
205
206/// A B+ tree in which each leaf node contains `Item`s of type `T` and a `Summary`s for each `Item`.
207/// Each internal node contains a `Summary` of the items in its subtree.
208///
209/// The maximum number of items per node is `TREE_BASE * 2`.
210///
211/// Any [`Dimension`] supported by the [`Summary`] type can be used to seek to a specific location in the tree.
212#[derive(Clone)]
213pub struct SumTree<T: Item>(Arc<Node<T>>);
214
215impl<T> fmt::Debug for SumTree<T>
216where
217    T: fmt::Debug + Item,
218    T::Summary: fmt::Debug,
219{
220    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
221        f.debug_tuple("SumTree").field(&self.0).finish()
222    }
223}
224
225impl<T: Item> SumTree<T> {
226    pub fn new(cx: <T::Summary as Summary>::Context<'_>) -> Self {
227        SumTree(Arc::new(Node::Leaf {
228            summary: <T::Summary as Summary>::zero(cx),
229            items: ArrayVec::new(),
230            item_summaries: ArrayVec::new(),
231        }))
232    }
233
234    /// Useful in cases where the item type has a non-trivial context type, but the zero value of the summary type doesn't depend on that context.
235    pub fn from_summary(summary: T::Summary) -> Self {
236        SumTree(Arc::new(Node::Leaf {
237            summary,
238            items: ArrayVec::new(),
239            item_summaries: ArrayVec::new(),
240        }))
241    }
242
243    pub fn from_item(item: T, cx: <T::Summary as Summary>::Context<'_>) -> Self {
244        let mut tree = Self::new(cx);
245        tree.push(item, cx);
246        tree
247    }
248
249    pub fn from_iter<I: IntoIterator<Item = T>>(
250        iter: I,
251        cx: <T::Summary as Summary>::Context<'_>,
252    ) -> Self {
253        let mut nodes = Vec::new();
254
255        let mut iter = iter.into_iter().fuse().peekable();
256        while iter.peek().is_some() {
257            let items: ArrayVec<T, { 2 * TREE_BASE }, u8> =
258                iter.by_ref().take(2 * TREE_BASE).collect();
259            let item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8> =
260                items.iter().map(|item| item.summary(cx)).collect();
261
262            let mut summary = item_summaries[0].clone();
263            for item_summary in &item_summaries[1..] {
264                <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
265            }
266
267            nodes.push(SumTree(Arc::new(Node::Leaf {
268                summary,
269                items,
270                item_summaries,
271            })));
272        }
273
274        let mut parent_nodes = Vec::new();
275        let mut height = 0;
276        while nodes.len() > 1 {
277            height += 1;
278            let mut current_parent_node = None;
279            for child_node in nodes.drain(..) {
280                let parent_node = current_parent_node.get_or_insert_with(|| {
281                    SumTree(Arc::new(Node::Internal {
282                        summary: <T::Summary as Summary>::zero(cx),
283                        height,
284                        child_summaries: ArrayVec::new(),
285                        child_trees: ArrayVec::new(),
286                    }))
287                });
288                let Node::Internal {
289                    summary,
290                    child_summaries,
291                    child_trees,
292                    ..
293                } = Arc::get_mut(&mut parent_node.0).unwrap()
294                else {
295                    unreachable!()
296                };
297                let child_summary = child_node.summary();
298                <T::Summary as Summary>::add_summary(summary, child_summary, cx);
299                child_summaries.push(child_summary.clone()).unwrap_oob();
300                child_trees.push(child_node.clone()).unwrap_oob();
301
302                if child_trees.len() == 2 * TREE_BASE {
303                    parent_nodes.extend(current_parent_node.take());
304                }
305            }
306            parent_nodes.extend(current_parent_node.take());
307            mem::swap(&mut nodes, &mut parent_nodes);
308        }
309
310        if nodes.is_empty() {
311            Self::new(cx)
312        } else {
313            debug_assert_eq!(nodes.len(), 1);
314            nodes.pop().unwrap()
315        }
316    }
317
318    pub fn from_par_iter<I, Iter>(iter: I, cx: <T::Summary as Summary>::Context<'_>) -> Self
319    where
320        I: IntoParallelIterator<Iter = Iter>,
321        Iter: IndexedParallelIterator<Item = T>,
322        T: Send + Sync,
323        T::Summary: Send + Sync,
324        for<'a> <T::Summary as Summary>::Context<'a>: Sync,
325    {
326        let mut nodes = iter
327            .into_par_iter()
328            .chunks(2 * TREE_BASE)
329            .map(|items| {
330                let items: ArrayVec<T, { 2 * TREE_BASE }, u8> = items.into_iter().collect();
331                let item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8> =
332                    items.iter().map(|item| item.summary(cx)).collect();
333                let mut summary = item_summaries[0].clone();
334                for item_summary in &item_summaries[1..] {
335                    <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
336                }
337                SumTree(Arc::new(Node::Leaf {
338                    summary,
339                    items,
340                    item_summaries,
341                }))
342            })
343            .collect::<Vec<_>>();
344
345        let mut height = 0;
346        while nodes.len() > 1 {
347            height += 1;
348            nodes = nodes
349                .into_par_iter()
350                .chunks(2 * TREE_BASE)
351                .map(|child_nodes| {
352                    let child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }, u8> =
353                        child_nodes.into_iter().collect();
354                    let child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8> = child_trees
355                        .iter()
356                        .map(|child_tree| child_tree.summary().clone())
357                        .collect();
358                    let mut summary = child_summaries[0].clone();
359                    for child_summary in &child_summaries[1..] {
360                        <T::Summary as Summary>::add_summary(&mut summary, child_summary, cx);
361                    }
362                    SumTree(Arc::new(Node::Internal {
363                        height,
364                        summary,
365                        child_summaries,
366                        child_trees,
367                    }))
368                })
369                .collect::<Vec<_>>();
370        }
371
372        if nodes.is_empty() {
373            Self::new(cx)
374        } else {
375            debug_assert_eq!(nodes.len(), 1);
376            nodes.pop().unwrap()
377        }
378    }
379
380    pub fn items<'a>(&'a self, cx: <T::Summary as Summary>::Context<'a>) -> Vec<T> {
381        let mut items = Vec::new();
382        let mut cursor = self.cursor::<()>(cx);
383        cursor.next();
384        while let Some(item) = cursor.item() {
385            items.push(item.clone());
386            cursor.next();
387        }
388        items
389    }
390
391    pub fn iter(&self) -> Iter<'_, T> {
392        Iter::new(self)
393    }
394
395    /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`.
396    ///
397    /// Only returns the item that exactly has the target match.
398    #[instrument(skip_all)]
399    pub fn find_exact<'a, 'slf, D, Target>(
400        &'slf self,
401        cx: <T::Summary as Summary>::Context<'a>,
402        target: &Target,
403        bias: Bias,
404    ) -> (D, D, Option<&'slf T>)
405    where
406        D: Dimension<'slf, T::Summary>,
407        Target: SeekTarget<'slf, T::Summary, D>,
408    {
409        let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
410        let comparison = target.cmp(&tree_end, cx);
411        if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
412        {
413            return (tree_end.clone(), tree_end, None);
414        }
415
416        let mut pos = D::zero(cx);
417        return match Self::find_iterate::<_, _, true>(cx, target, bias, &mut pos, self) {
418            Some((item, end)) => (pos, end, Some(item)),
419            None => (pos.clone(), pos, None),
420        };
421    }
422
423    /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
424    #[instrument(skip_all)]
425    pub fn find<'a, 'slf, D, Target>(
426        &'slf self,
427        cx: <T::Summary as Summary>::Context<'a>,
428        target: &Target,
429        bias: Bias,
430    ) -> (D, D, Option<&'slf T>)
431    where
432        D: Dimension<'slf, T::Summary>,
433        Target: SeekTarget<'slf, T::Summary, D>,
434    {
435        let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
436        let comparison = target.cmp(&tree_end, cx);
437        if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
438        {
439            return (tree_end.clone(), tree_end, None);
440        }
441
442        let mut pos = D::zero(cx);
443        return match Self::find_iterate::<_, _, false>(cx, target, bias, &mut pos, self) {
444            Some((item, end)) => (pos, end, Some(item)),
445            None => (pos.clone(), pos, None),
446        };
447    }
448
449    fn find_iterate<'tree, 'a, D, Target, const EXACT: bool>(
450        cx: <T::Summary as Summary>::Context<'a>,
451        target: &Target,
452        bias: Bias,
453        position: &mut D,
454        mut this: &'tree SumTree<T>,
455    ) -> Option<(&'tree T, D)>
456    where
457        D: Dimension<'tree, T::Summary>,
458        Target: SeekTarget<'tree, T::Summary, D>,
459    {
460        'iterate: loop {
461            match &*this.0 {
462                Node::Internal {
463                    child_summaries,
464                    child_trees,
465                    ..
466                } => {
467                    for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
468                        let child_end = position.clone().with_added_summary(child_summary, cx);
469
470                        let comparison = target.cmp(&child_end, cx);
471                        let target_in_child = comparison == Ordering::Less
472                            || (comparison == Ordering::Equal && bias == Bias::Left);
473                        if target_in_child {
474                            this = child_tree;
475                            continue 'iterate;
476                        }
477                        *position = child_end;
478                    }
479                }
480                Node::Leaf {
481                    items,
482                    item_summaries,
483                    ..
484                } => {
485                    for (item, item_summary) in items.iter().zip(item_summaries) {
486                        let mut child_end = position.clone();
487                        child_end.add_summary(item_summary, cx);
488
489                        let comparison = target.cmp(&child_end, cx);
490                        let entry_found = if EXACT {
491                            comparison == Ordering::Equal
492                        } else {
493                            comparison == Ordering::Less
494                                || (comparison == Ordering::Equal && bias == Bias::Left)
495                        };
496                        if entry_found {
497                            return Some((item, child_end));
498                        }
499
500                        *position = child_end;
501                    }
502                }
503            }
504            return None;
505        }
506    }
507
508    /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
509    #[instrument(skip_all)]
510    pub fn find_with_prev<'a, 'slf, D, Target>(
511        &'slf self,
512        cx: <T::Summary as Summary>::Context<'a>,
513        target: &Target,
514        bias: Bias,
515    ) -> (D, D, Option<(Option<&'slf T>, &'slf T)>)
516    where
517        D: Dimension<'slf, T::Summary>,
518        Target: SeekTarget<'slf, T::Summary, D>,
519    {
520        let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
521        let comparison = target.cmp(&tree_end, cx);
522        if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
523        {
524            return (tree_end.clone(), tree_end, None);
525        }
526
527        let mut pos = D::zero(cx);
528        return match Self::find_with_prev_iterate::<_, _, false>(cx, target, bias, &mut pos, self) {
529            Some((prev, item, end)) => (pos, end, Some((prev, item))),
530            None => (pos.clone(), pos, None),
531        };
532    }
533
534    fn find_with_prev_iterate<'tree, 'a, D, Target, const EXACT: bool>(
535        cx: <T::Summary as Summary>::Context<'a>,
536        target: &Target,
537        bias: Bias,
538        position: &mut D,
539        mut this: &'tree SumTree<T>,
540    ) -> Option<(Option<&'tree T>, &'tree T, D)>
541    where
542        D: Dimension<'tree, T::Summary>,
543        Target: SeekTarget<'tree, T::Summary, D>,
544    {
545        let mut prev = None;
546        'iterate: loop {
547            match &*this.0 {
548                Node::Internal {
549                    child_summaries,
550                    child_trees,
551                    ..
552                } => {
553                    for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
554                        let child_end = position.clone().with_added_summary(child_summary, cx);
555
556                        let comparison = target.cmp(&child_end, cx);
557                        let target_in_child = comparison == Ordering::Less
558                            || (comparison == Ordering::Equal && bias == Bias::Left);
559                        if target_in_child {
560                            this = child_tree;
561                            continue 'iterate;
562                        }
563                        prev = child_tree.last();
564                        *position = child_end;
565                    }
566                }
567                Node::Leaf {
568                    items,
569                    item_summaries,
570                    ..
571                } => {
572                    for (item, item_summary) in items.iter().zip(item_summaries) {
573                        let mut child_end = position.clone();
574                        child_end.add_summary(item_summary, cx);
575
576                        let comparison = target.cmp(&child_end, cx);
577                        let entry_found = if EXACT {
578                            comparison == Ordering::Equal
579                        } else {
580                            comparison == Ordering::Less
581                                || (comparison == Ordering::Equal && bias == Bias::Left)
582                        };
583                        if entry_found {
584                            return Some((prev, item, child_end));
585                        }
586
587                        prev = Some(item);
588                        *position = child_end;
589                    }
590                }
591            }
592            return None;
593        }
594    }
595
596    pub fn cursor<'a, 'b, D>(
597        &'a self,
598        cx: <T::Summary as Summary>::Context<'b>,
599    ) -> Cursor<'a, 'b, T, D>
600    where
601        D: Dimension<'a, T::Summary>,
602    {
603        Cursor::new(self, cx)
604    }
605
606    /// Note: If the summary type requires a non `()` context, then the filter cursor
607    /// that is returned cannot be used with Rust's iterators.
608    pub fn filter<'a, 'b, F, U>(
609        &'a self,
610        cx: <T::Summary as Summary>::Context<'b>,
611        filter_node: F,
612    ) -> FilterCursor<'a, 'b, F, T, U>
613    where
614        F: FnMut(&T::Summary) -> bool,
615        U: Dimension<'a, T::Summary>,
616    {
617        FilterCursor::new(self, cx, filter_node)
618    }
619
620    pub fn first(&self) -> Option<&T> {
621        self.leftmost_leaf().0.items().first()
622    }
623
624    pub fn last(&self) -> Option<&T> {
625        self.rightmost_leaf().0.items().last()
626    }
627
628    pub fn last_summary(&self) -> Option<&T::Summary> {
629        self.rightmost_leaf().0.child_summaries().last()
630    }
631
632    pub fn update_last(
633        &mut self,
634        f: impl FnOnce(&mut T),
635        cx: <T::Summary as Summary>::Context<'_>,
636    ) {
637        self.update_last_recursive(f, cx);
638    }
639
640    fn update_last_recursive(
641        &mut self,
642        f: impl FnOnce(&mut T),
643        cx: <T::Summary as Summary>::Context<'_>,
644    ) -> Option<T::Summary> {
645        match Arc::make_mut(&mut self.0) {
646            Node::Internal {
647                summary,
648                child_summaries,
649                child_trees,
650                ..
651            } => {
652                let last_summary = child_summaries.last_mut().unwrap();
653                let last_child = child_trees.last_mut().unwrap();
654                *last_summary = last_child.update_last_recursive(f, cx).unwrap();
655                *summary = sum(child_summaries.iter(), cx);
656                Some(summary.clone())
657            }
658            Node::Leaf {
659                summary,
660                items,
661                item_summaries,
662            } => {
663                if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
664                {
665                    (f)(item);
666                    *item_summary = item.summary(cx);
667                    *summary = sum(item_summaries.iter(), cx);
668                    Some(summary.clone())
669                } else {
670                    None
671                }
672            }
673        }
674    }
675
676    pub fn update_first(
677        &mut self,
678        f: impl FnOnce(&mut T),
679        cx: <T::Summary as Summary>::Context<'_>,
680    ) {
681        self.update_first_recursive(f, cx);
682    }
683
684    fn update_first_recursive(
685        &mut self,
686        f: impl FnOnce(&mut T),
687        cx: <T::Summary as Summary>::Context<'_>,
688    ) -> Option<T::Summary> {
689        match Arc::make_mut(&mut self.0) {
690            Node::Internal {
691                summary,
692                child_summaries,
693                child_trees,
694                ..
695            } => {
696                let first_summary = child_summaries.first_mut().unwrap();
697                let first_child = child_trees.first_mut().unwrap();
698                *first_summary = first_child.update_first_recursive(f, cx).unwrap();
699                *summary = sum(child_summaries.iter(), cx);
700                Some(summary.clone())
701            }
702            Node::Leaf {
703                summary,
704                items,
705                item_summaries,
706            } => {
707                if let Some((item, item_summary)) =
708                    items.first_mut().zip(item_summaries.first_mut())
709                {
710                    (f)(item);
711                    *item_summary = item.summary(cx);
712                    *summary = sum(item_summaries.iter(), cx);
713                    Some(summary.clone())
714                } else {
715                    None
716                }
717            }
718        }
719    }
720
721    pub fn extent<'a, D: Dimension<'a, T::Summary>>(
722        &'a self,
723        cx: <T::Summary as Summary>::Context<'_>,
724    ) -> D {
725        let mut extent = D::zero(cx);
726        match self.0.as_ref() {
727            Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
728                extent.add_summary(summary, cx);
729            }
730        }
731        extent
732    }
733
734    pub fn summary(&self) -> &T::Summary {
735        match self.0.as_ref() {
736            Node::Internal { summary, .. } => summary,
737            Node::Leaf { summary, .. } => summary,
738        }
739    }
740
741    pub fn is_empty(&self) -> bool {
742        match self.0.as_ref() {
743            Node::Internal { .. } => false,
744            Node::Leaf { items, .. } => items.is_empty(),
745        }
746    }
747
748    pub fn extend<I>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
749    where
750        I: IntoIterator<Item = T>,
751    {
752        self.append(Self::from_iter(iter, cx), cx);
753    }
754
755    pub fn par_extend<I, Iter>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
756    where
757        I: IntoParallelIterator<Iter = Iter>,
758        Iter: IndexedParallelIterator<Item = T>,
759        T: Send + Sync,
760        T::Summary: Send + Sync,
761        for<'a> <T::Summary as Summary>::Context<'a>: Sync,
762    {
763        self.append(Self::from_par_iter(iter, cx), cx);
764    }
765
766    pub fn push(&mut self, item: T, cx: <T::Summary as Summary>::Context<'_>) {
767        let summary = item.summary(cx);
768        self.append(
769            SumTree(Arc::new(Node::Leaf {
770                summary: summary.clone(),
771                items: ArrayVec::from_iter(Some(item)),
772                item_summaries: ArrayVec::from_iter(Some(summary)),
773            })),
774            cx,
775        );
776    }
777
778    pub fn append(&mut self, mut other: Self, cx: <T::Summary as Summary>::Context<'_>) {
779        if self.is_empty() {
780            *self = other;
781        } else if !other.0.is_leaf() || !other.0.items().is_empty() {
782            if self.0.height() < other.0.height() {
783                if let Some(tree) = Self::append_large(self.clone(), &mut other, cx) {
784                    *self = Self::from_child_trees(tree, other, cx);
785                } else {
786                    *self = other;
787                }
788            } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
789                *self = Self::from_child_trees(self.clone(), split_tree, cx);
790            }
791        }
792    }
793
794    fn push_tree_recursive(
795        &mut self,
796        other: SumTree<T>,
797        cx: <T::Summary as Summary>::Context<'_>,
798    ) -> Option<SumTree<T>> {
799        match Arc::make_mut(&mut self.0) {
800            Node::Internal {
801                height,
802                summary,
803                child_summaries,
804                child_trees,
805                ..
806            } => {
807                let other_node = other.0.clone();
808                <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
809
810                let height_delta = *height - other_node.height();
811                let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }, u8>::new();
812                let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }, u8>::new();
813                if height_delta == 0 {
814                    summaries_to_append.extend(other_node.child_summaries().iter().cloned());
815                    trees_to_append.extend(other_node.child_trees().iter().cloned());
816                } else if height_delta == 1 && !other_node.is_underflowing() {
817                    summaries_to_append
818                        .push(other_node.summary().clone())
819                        .unwrap_oob();
820                    trees_to_append.push(other).unwrap_oob();
821                } else {
822                    let tree_to_append = child_trees
823                        .last_mut()
824                        .unwrap()
825                        .push_tree_recursive(other, cx);
826                    *child_summaries.last_mut().unwrap() =
827                        child_trees.last().unwrap().0.summary().clone();
828
829                    if let Some(split_tree) = tree_to_append {
830                        summaries_to_append
831                            .push(split_tree.0.summary().clone())
832                            .unwrap_oob();
833                        trees_to_append.push(split_tree).unwrap_oob();
834                    }
835                }
836
837                let child_count = child_trees.len() + trees_to_append.len();
838                if child_count > 2 * TREE_BASE {
839                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8>;
840                    let right_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8>;
841                    let left_trees;
842                    let right_trees;
843
844                    let midpoint = (child_count + child_count % 2) / 2;
845                    {
846                        let mut all_summaries = child_summaries
847                            .iter()
848                            .chain(summaries_to_append.iter())
849                            .cloned();
850                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
851                        right_summaries = all_summaries.collect();
852                        let mut all_trees =
853                            child_trees.iter().chain(trees_to_append.iter()).cloned();
854                        left_trees = all_trees.by_ref().take(midpoint).collect();
855                        right_trees = all_trees.collect();
856                    }
857                    *summary = sum(left_summaries.iter(), cx);
858                    *child_summaries = left_summaries;
859                    *child_trees = left_trees;
860
861                    Some(SumTree(Arc::new(Node::Internal {
862                        height: *height,
863                        summary: sum(right_summaries.iter(), cx),
864                        child_summaries: right_summaries,
865                        child_trees: right_trees,
866                    })))
867                } else {
868                    child_summaries.extend(summaries_to_append);
869                    child_trees.extend(trees_to_append);
870                    None
871                }
872            }
873            Node::Leaf {
874                summary,
875                items,
876                item_summaries,
877            } => {
878                let other_node = other.0;
879
880                let child_count = items.len() + other_node.items().len();
881                if child_count > 2 * TREE_BASE {
882                    let left_items;
883                    let right_items;
884                    let left_summaries;
885                    let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8>;
886
887                    let midpoint = (child_count + child_count % 2) / 2;
888                    {
889                        let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
890                        left_items = all_items.by_ref().take(midpoint).collect();
891                        right_items = all_items.collect();
892
893                        let mut all_summaries = item_summaries
894                            .iter()
895                            .chain(other_node.child_summaries())
896                            .cloned();
897                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
898                        right_summaries = all_summaries.collect();
899                    }
900                    *items = left_items;
901                    *item_summaries = left_summaries;
902                    *summary = sum(item_summaries.iter(), cx);
903                    Some(SumTree(Arc::new(Node::Leaf {
904                        items: right_items,
905                        summary: sum(right_summaries.iter(), cx),
906                        item_summaries: right_summaries,
907                    })))
908                } else {
909                    <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
910                    items.extend(other_node.items().iter().cloned());
911                    item_summaries.extend(other_node.child_summaries().iter().cloned());
912                    None
913                }
914            }
915        }
916    }
917
918    // appends the `large` tree to a `small` tree, assumes small.height() <= large.height()
919    fn append_large(
920        small: Self,
921        large: &mut Self,
922        cx: <T::Summary as Summary>::Context<'_>,
923    ) -> Option<Self> {
924        if small.0.height() == large.0.height() {
925            if !small.0.is_underflowing() {
926                Some(small)
927            } else {
928                Self::merge_into_right(small, large, cx)
929            }
930        } else {
931            debug_assert!(small.0.height() < large.0.height());
932            let Node::Internal {
933                height,
934                summary,
935                child_summaries,
936                child_trees,
937            } = Arc::make_mut(&mut large.0)
938            else {
939                unreachable!();
940            };
941            let mut full_summary = small.summary().clone();
942            Summary::add_summary(&mut full_summary, summary, cx);
943            *summary = full_summary;
944
945            let first = child_trees.first_mut().unwrap();
946            let res = Self::append_large(small, first, cx);
947            *child_summaries.first_mut().unwrap() = first.summary().clone();
948            if let Some(tree) = res {
949                if child_trees.len() < 2 * TREE_BASE {
950                    child_summaries
951                        .insert(0, tree.summary().clone())
952                        .unwrap_oob();
953                    child_trees.insert(0, tree).unwrap_oob();
954                    None
955                } else {
956                    let new_child_summaries = {
957                        let mut res = ArrayVec::from_iter([tree.summary().clone()]);
958                        res.extend(child_summaries.drain(..TREE_BASE));
959                        res
960                    };
961                    let tree = SumTree(Arc::new(Node::Internal {
962                        height: *height,
963                        summary: sum(new_child_summaries.iter(), cx),
964                        child_summaries: new_child_summaries,
965                        child_trees: {
966                            let mut res = ArrayVec::from_iter([tree]);
967                            res.extend(child_trees.drain(..TREE_BASE));
968                            res
969                        },
970                    }));
971
972                    *summary = sum(child_summaries.iter(), cx);
973                    Some(tree)
974                }
975            } else {
976                None
977            }
978        }
979    }
980
981    // Merge two nodes into `large`.
982    //
983    // `large` will contain the contents of `small` followed by its own data.
984    // If the combined data exceed the node capacity, returns a new node that
985    // holds the first half of the merged items and `large` is left with the
986    // second half
987    //
988    // The nodes must be on the same height
989    // It only makes sense to call this when `small` is underflowing
990    fn merge_into_right(
991        small: Self,
992        large: &mut Self,
993        cx: <<T as Item>::Summary as Summary>::Context<'_>,
994    ) -> Option<SumTree<T>> {
995        debug_assert_eq!(small.0.height(), large.0.height());
996        match (small.0.as_ref(), Arc::make_mut(&mut large.0)) {
997            (
998                Node::Internal {
999                    summary: small_summary,
1000                    child_summaries: small_child_summaries,
1001                    child_trees: small_child_trees,
1002                    ..
1003                },
1004                Node::Internal {
1005                    summary,
1006                    child_summaries,
1007                    child_trees,
1008                    height,
1009                },
1010            ) => {
1011                let total_child_count = child_trees.len() + small_child_trees.len();
1012                if total_child_count <= 2 * TREE_BASE {
1013                    let mut all_trees = small_child_trees.clone();
1014                    all_trees.extend(child_trees.drain(..));
1015                    *child_trees = all_trees;
1016
1017                    let mut all_summaries = small_child_summaries.clone();
1018                    all_summaries.extend(child_summaries.drain(..));
1019                    *child_summaries = all_summaries;
1020
1021                    let mut full_summary = small_summary.clone();
1022                    Summary::add_summary(&mut full_summary, summary, cx);
1023                    *summary = full_summary;
1024                    None
1025                } else {
1026                    let midpoint = total_child_count.div_ceil(2);
1027                    let mut all_trees = small_child_trees.iter().chain(child_trees.iter()).cloned();
1028                    let left_trees = all_trees.by_ref().take(midpoint).collect();
1029                    *child_trees = all_trees.collect();
1030
1031                    let mut all_summaries = small_child_summaries
1032                        .iter()
1033                        .chain(child_summaries.iter())
1034                        .cloned();
1035                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8> =
1036                        all_summaries.by_ref().take(midpoint).collect();
1037                    *child_summaries = all_summaries.collect();
1038
1039                    *summary = sum(child_summaries.iter(), cx);
1040                    Some(SumTree(Arc::new(Node::Internal {
1041                        height: *height,
1042                        summary: sum(left_summaries.iter(), cx),
1043                        child_summaries: left_summaries,
1044                        child_trees: left_trees,
1045                    })))
1046                }
1047            }
1048            (
1049                Node::Leaf {
1050                    summary: small_summary,
1051                    items: small_items,
1052                    item_summaries: small_item_summaries,
1053                },
1054                Node::Leaf {
1055                    summary,
1056                    items,
1057                    item_summaries,
1058                },
1059            ) => {
1060                let total_child_count = small_items.len() + items.len();
1061                if total_child_count <= 2 * TREE_BASE {
1062                    let mut all_items = small_items.clone();
1063                    all_items.extend(items.drain(..));
1064                    *items = all_items;
1065
1066                    let mut all_summaries = small_item_summaries.clone();
1067                    all_summaries.extend(item_summaries.drain(..));
1068                    *item_summaries = all_summaries;
1069
1070                    let mut full_summary = small_summary.clone();
1071                    Summary::add_summary(&mut full_summary, summary, cx);
1072                    *summary = full_summary;
1073                    None
1074                } else {
1075                    let midpoint = total_child_count.div_ceil(2);
1076                    let mut all_items = small_items.iter().chain(items.iter()).cloned();
1077                    let left_items = all_items.by_ref().take(midpoint).collect();
1078                    *items = all_items.collect();
1079
1080                    let mut all_summaries = small_item_summaries
1081                        .iter()
1082                        .chain(item_summaries.iter())
1083                        .cloned();
1084                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8> =
1085                        all_summaries.by_ref().take(midpoint).collect();
1086                    *item_summaries = all_summaries.collect();
1087
1088                    *summary = sum(item_summaries.iter(), cx);
1089                    Some(SumTree(Arc::new(Node::Leaf {
1090                        items: left_items,
1091                        summary: sum(left_summaries.iter(), cx),
1092                        item_summaries: left_summaries,
1093                    })))
1094                }
1095            }
1096            _ => unreachable!(),
1097        }
1098    }
1099
1100    fn from_child_trees(
1101        left: SumTree<T>,
1102        right: SumTree<T>,
1103        cx: <T::Summary as Summary>::Context<'_>,
1104    ) -> Self {
1105        let height = left.0.height() + 1;
1106        let mut child_summaries = ArrayVec::new();
1107        child_summaries.push(left.0.summary().clone()).unwrap_oob();
1108        child_summaries.push(right.0.summary().clone()).unwrap_oob();
1109        let mut child_trees = ArrayVec::new();
1110        child_trees.push(left).unwrap_oob();
1111        child_trees.push(right).unwrap_oob();
1112        SumTree(Arc::new(Node::Internal {
1113            height,
1114            summary: sum(child_summaries.iter(), cx),
1115            child_summaries,
1116            child_trees,
1117        }))
1118    }
1119
1120    fn leftmost_leaf(&self) -> &Self {
1121        match *self.0 {
1122            Node::Leaf { .. } => self,
1123            Node::Internal {
1124                ref child_trees, ..
1125            } => child_trees.first().unwrap().leftmost_leaf(),
1126        }
1127    }
1128
1129    fn rightmost_leaf(&self) -> &Self {
1130        match *self.0 {
1131            Node::Leaf { .. } => self,
1132            Node::Internal {
1133                ref child_trees, ..
1134            } => child_trees.last().unwrap().rightmost_leaf(),
1135        }
1136    }
1137}
1138
1139impl<T: Item + PartialEq> PartialEq for SumTree<T> {
1140    fn eq(&self, other: &Self) -> bool {
1141        self.iter().eq(other.iter())
1142    }
1143}
1144
1145impl<T: Item + Eq> Eq for SumTree<T> {}
1146
1147impl<T: KeyedItem> SumTree<T> {
1148    pub fn insert_or_replace<'a, 'b>(
1149        &'a mut self,
1150        item: T,
1151        cx: <T::Summary as Summary>::Context<'b>,
1152    ) -> Option<T> {
1153        self.insert_sorted(std::iter::once(item), cx).pop()
1154    }
1155
1156    pub fn remove(&mut self, key: &T::Key, cx: <T::Summary as Summary>::Context<'_>) -> Option<T> {
1157        let mut removed = None;
1158        *self = {
1159            let mut cursor = self.cursor::<T::Key>(cx);
1160            let mut new_tree = cursor.slice(key, Bias::Left);
1161            if let Some(item) = cursor.item()
1162                && item.key() == *key
1163            {
1164                removed = Some(item.clone());
1165                cursor.next();
1166            }
1167            new_tree.append(cursor.suffix(), cx);
1168            new_tree
1169        };
1170        removed
1171    }
1172
1173    pub fn edit(
1174        &mut self,
1175        mut edits: Vec<Edit<T>>,
1176        cx: <T::Summary as Summary>::Context<'_>,
1177    ) -> Vec<T> {
1178        if edits.is_empty() {
1179            return Vec::new();
1180        }
1181
1182        let mut removed = Vec::new();
1183        edits.sort_unstable_by_key(|item| item.key());
1184
1185        if self.is_empty() {
1186            *self = Self::from_iter(
1187                edits.into_iter().filter_map(|edit| match edit {
1188                    Edit::Insert(item) => Some(item),
1189                    Edit::Remove(_) => None,
1190                }),
1191                cx,
1192            );
1193            return Vec::new();
1194        }
1195
1196        // A repeated key can replace items in more than one leaf, which only the slicing below
1197        // handles.
1198        if edits.iter().all(|edit| matches!(edit, Edit::Insert(_)))
1199            && edits.is_sorted_by(|left, right| left.key() < right.key())
1200        {
1201            let items = edits.into_iter().filter_map(|edit| match edit {
1202                Edit::Insert(item) => Some(item),
1203                Edit::Remove(_) => None,
1204            });
1205            return self.insert_sorted(items, cx);
1206        }
1207
1208        *self = {
1209            let mut cursor = self.cursor::<T::Key>(cx);
1210            let mut new_tree = SumTree::new(cx);
1211            let mut buffered_items = Vec::new();
1212
1213            cursor.seek(&T::Key::zero(cx), Bias::Left);
1214            for edit in edits {
1215                let new_key = edit.key();
1216                let mut old_item = cursor.item();
1217
1218                if old_item
1219                    .as_ref()
1220                    .is_some_and(|old_item| old_item.key() < new_key)
1221                {
1222                    new_tree.extend(buffered_items.drain(..), cx);
1223                    let slice = cursor.slice(&new_key, Bias::Left);
1224                    new_tree.append(slice, cx);
1225                    old_item = cursor.item();
1226                }
1227
1228                if let Some(old_item) = old_item
1229                    && old_item.key() == new_key
1230                {
1231                    removed.push(old_item.clone());
1232                    cursor.next();
1233                }
1234
1235                match edit {
1236                    Edit::Insert(item) => {
1237                        buffered_items.push(item);
1238                    }
1239                    Edit::Remove(_) => {}
1240                }
1241            }
1242
1243            new_tree.extend(buffered_items, cx);
1244            new_tree.append(cursor.suffix(), cx);
1245            new_tree
1246        };
1247
1248        removed
1249    }
1250
1251    /// Inserts `items`, which are in key order with distinct keys, and returns the items they
1252    /// replace. Changes the tree in place, cloning only the nodes that other trees share.
1253    fn insert_sorted(
1254        &mut self,
1255        items: impl Iterator<Item = T>,
1256        cx: <T::Summary as Summary>::Context<'_>,
1257    ) -> Vec<T> {
1258        let mut removed = Vec::new();
1259        let mut items = items.map(|item| (item.key(), item)).peekable();
1260        let siblings = self.insert_recursive(&mut items, T::Key::zero(cx), None, &mut removed, cx);
1261        if !siblings.is_empty() {
1262            let mut height = self.0.height();
1263            let mut nodes = vec![self.clone()];
1264            nodes.extend(siblings);
1265            while nodes.len() > 1 {
1266                height += 1;
1267                nodes = Self::group_children(nodes, height, cx).collect();
1268            }
1269            if let Some(root) = nodes.pop() {
1270                *self = root;
1271            }
1272        }
1273        removed
1274    }
1275
1276    /// Inserts the leading `items` with keys up to `bound` into this subtree, which starts at
1277    /// `position`. Returns the siblings that the subtree splits off, in order.
1278    fn insert_recursive<I: Iterator<Item = (T::Key, T)>>(
1279        &mut self,
1280        items: &mut std::iter::Peekable<I>,
1281        mut position: T::Key,
1282        bound: Option<&T::Key>,
1283        removed: &mut Vec<T>,
1284        cx: <T::Summary as Summary>::Context<'_>,
1285    ) -> Vec<SumTree<T>> {
1286        let node = Arc::make_mut(&mut self.0);
1287        let (height, children) = match node {
1288            Node::Internal {
1289                height,
1290                summary,
1291                child_summaries,
1292                child_trees,
1293            } => {
1294                let mut splits = Vec::new();
1295                let child_count = child_trees.len();
1296                let children = child_trees.iter_mut().zip(child_summaries.iter_mut());
1297                for (index, (child_tree, child_summary)) in children.enumerate() {
1298                    let Some((key, _)) = items.peek() else {
1299                        break;
1300                    };
1301                    let mut child_end = position.clone();
1302                    child_end.add_summary(child_summary, cx);
1303                    // Keys past the end of the tree go to the last child.
1304                    let child_bound = if index + 1 == child_count {
1305                        bound
1306                    } else {
1307                        Some(&child_end)
1308                    };
1309                    if child_bound.is_none_or(|bound| key <= bound) {
1310                        let siblings =
1311                            child_tree.insert_recursive(items, position, child_bound, removed, cx);
1312                        *child_summary = child_tree.summary().clone();
1313                        if !siblings.is_empty() {
1314                            splits.push((index, siblings));
1315                        }
1316                    }
1317                    position = child_end;
1318                }
1319                if splits.is_empty() {
1320                    *summary = sum(child_summaries.iter(), cx);
1321                    return Vec::new();
1322                }
1323
1324                let mut children = Vec::new();
1325                let mut splits = splits.into_iter().peekable();
1326                for (index, child_tree) in mem::take(child_trees).into_iter().enumerate() {
1327                    children.push(child_tree);
1328                    if let Some((_, siblings)) = splits.next_if(|split| split.0 == index) {
1329                        children.extend(siblings);
1330                    }
1331                }
1332                (*height, children)
1333            }
1334            Node::Leaf {
1335                items: old_items, ..
1336            } => {
1337                let mut old_items = mem::take(old_items).into_iter().peekable();
1338                let mut old_key = old_items.peek().map(T::key);
1339                let mut merged = Vec::new();
1340                while let Some((key, item)) =
1341                    items.next_if(|(key, _)| bound.is_none_or(|bound| key <= bound))
1342                {
1343                    while old_key.as_ref().is_some_and(|old_key| *old_key < key) {
1344                        merged.extend(old_items.next());
1345                        old_key = old_items.peek().map(T::key);
1346                    }
1347                    if old_key.as_ref() == Some(&key) {
1348                        removed.extend(old_items.next());
1349                        old_key = old_items.peek().map(T::key);
1350                    }
1351                    merged.push(item);
1352                }
1353                merged.extend(old_items);
1354
1355                let mut merged = merged.into_iter();
1356                let mut leaves = node_sizes(merged.len()).map(|size| {
1357                    let items: ArrayVec<T, _, _> = merged.by_ref().take(size).collect();
1358                    let item_summaries: ArrayVec<_, _, _> =
1359                        items.iter().map(|item| item.summary(cx)).collect();
1360                    Node::Leaf {
1361                        summary: sum(item_summaries.iter(), cx),
1362                        items,
1363                        item_summaries,
1364                    }
1365                });
1366                if let Some(first) = leaves.next() {
1367                    *node = first;
1368                }
1369                return leaves.map(|leaf| SumTree(Arc::new(leaf))).collect();
1370            }
1371        };
1372
1373        let mut parents = Self::group_children(children, height, cx);
1374        if let Some(first) = parents.next() {
1375            *self = first;
1376        }
1377        parents.collect()
1378    }
1379
1380    /// Groups nodes of one height under the fewest parents of the given height.
1381    fn group_children(
1382        children: Vec<SumTree<T>>,
1383        height: u8,
1384        cx: <T::Summary as Summary>::Context<'_>,
1385    ) -> impl Iterator<Item = SumTree<T>> {
1386        let mut children = children.into_iter();
1387        node_sizes(children.len()).map(move |size| {
1388            let child_trees: ArrayVec<SumTree<T>, _, _> = children.by_ref().take(size).collect();
1389            let child_summaries: ArrayVec<_, _, _> = child_trees
1390                .iter()
1391                .map(|tree| tree.summary().clone())
1392                .collect();
1393            SumTree(Arc::new(Node::Internal {
1394                height,
1395                summary: sum(child_summaries.iter(), cx),
1396                child_summaries,
1397                child_trees,
1398            }))
1399        })
1400    }
1401
1402    pub fn get<'a>(
1403        &'a self,
1404        key: &T::Key,
1405        cx: <T::Summary as Summary>::Context<'a>,
1406    ) -> Option<&'a T> {
1407        if let (_, _, Some(item)) = self.find_exact::<T::Key, _>(cx, key, Bias::Left) {
1408            Some(item)
1409        } else {
1410            None
1411        }
1412    }
1413}
1414
1415impl<T, S> Default for SumTree<T>
1416where
1417    T: Item<Summary = S>,
1418    S: for<'a> Summary<Context<'a> = ()>,
1419{
1420    fn default() -> Self {
1421        Self::new(())
1422    }
1423}
1424
1425#[derive(Clone)]
1426pub enum Node<T: Item> {
1427    Internal {
1428        height: u8,
1429        summary: T::Summary,
1430        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8>,
1431        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }, u8>,
1432    },
1433    Leaf {
1434        summary: T::Summary,
1435        items: ArrayVec<T, { 2 * TREE_BASE }, u8>,
1436        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8>,
1437    },
1438}
1439
1440impl<T> fmt::Debug for Node<T>
1441where
1442    T: Item + fmt::Debug,
1443    T::Summary: fmt::Debug,
1444{
1445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1446        match self {
1447            Node::Internal {
1448                height,
1449                summary,
1450                child_summaries,
1451                child_trees,
1452            } => f
1453                .debug_struct("Internal")
1454                .field("height", height)
1455                .field("summary", summary)
1456                .field("child_summaries", child_summaries)
1457                .field("child_trees", child_trees)
1458                .finish(),
1459            Node::Leaf {
1460                summary,
1461                items,
1462                item_summaries,
1463            } => f
1464                .debug_struct("Leaf")
1465                .field("summary", summary)
1466                .field("items", items)
1467                .field("item_summaries", item_summaries)
1468                .finish(),
1469        }
1470    }
1471}
1472
1473impl<T: Item> Node<T> {
1474    fn is_leaf(&self) -> bool {
1475        matches!(self, Node::Leaf { .. })
1476    }
1477
1478    fn height(&self) -> u8 {
1479        match self {
1480            Node::Internal { height, .. } => *height,
1481            Node::Leaf { .. } => 0,
1482        }
1483    }
1484
1485    fn summary(&self) -> &T::Summary {
1486        match self {
1487            Node::Internal { summary, .. } => summary,
1488            Node::Leaf { summary, .. } => summary,
1489        }
1490    }
1491
1492    fn child_summaries(&self) -> &[T::Summary] {
1493        match self {
1494            Node::Internal {
1495                child_summaries, ..
1496            } => child_summaries.as_slice(),
1497            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
1498        }
1499    }
1500
1501    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }, u8> {
1502        match self {
1503            Node::Internal { child_trees, .. } => child_trees,
1504            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
1505        }
1506    }
1507
1508    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }, u8> {
1509        match self {
1510            Node::Leaf { items, .. } => items,
1511            Node::Internal { .. } => panic!("Internal nodes have no items"),
1512        }
1513    }
1514
1515    fn is_underflowing(&self) -> bool {
1516        match self {
1517            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
1518            Node::Leaf { items, .. } => items.len() < TREE_BASE,
1519        }
1520    }
1521}
1522
1523#[derive(Debug)]
1524pub enum Edit<T: KeyedItem> {
1525    Insert(T),
1526    Remove(T::Key),
1527}
1528
1529impl<T: KeyedItem> Edit<T> {
1530    fn key(&self) -> T::Key {
1531        match self {
1532            Edit::Insert(item) => item.key(),
1533            Edit::Remove(key) => key.clone(),
1534        }
1535    }
1536}
1537
1538fn sum<'a, T, I>(iter: I, cx: T::Context<'_>) -> T
1539where
1540    T: 'a + Summary,
1541    I: Iterator<Item = &'a T>,
1542{
1543    let mut sum = T::zero(cx);
1544    for value in iter {
1545        sum.add_summary(value, cx);
1546    }
1547    sum
1548}
1549
1550/// Returns the sizes of the fewest nodes that hold `count` children, spread evenly so that none
1551/// underflows.
1552fn node_sizes(count: usize) -> impl Iterator<Item = usize> {
1553    let node_count = count.div_ceil(2 * TREE_BASE);
1554    (0..node_count).map(move |index| count / node_count + usize::from(index < count % node_count))
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559    use super::*;
1560    use rand::{distr::StandardUniform, prelude::*};
1561    use std::cmp;
1562
1563    #[ctor::ctor(unsafe)]
1564    fn init_logger() {
1565        zlog::init_test();
1566    }
1567
1568    #[test]
1569    fn test_extend_and_push_tree() {
1570        let mut tree1 = SumTree::default();
1571        tree1.extend(0..20, ());
1572
1573        let mut tree2 = SumTree::default();
1574        tree2.extend(50..100, ());
1575
1576        tree1.append(tree2, ());
1577        assert_eq!(tree1.items(()), (0..20).chain(50..100).collect::<Vec<u8>>());
1578    }
1579
1580    #[test]
1581    fn test_random() {
1582        let mut starting_seed = 0;
1583        if let Ok(value) = std::env::var("SEED") {
1584            starting_seed = value.parse().expect("invalid SEED variable");
1585        }
1586        let mut num_iterations = 100;
1587        if let Ok(value) = std::env::var("ITERATIONS") {
1588            num_iterations = value.parse().expect("invalid ITERATIONS variable");
1589        }
1590        let num_operations = std::env::var("OPERATIONS")
1591            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
1592
1593        for seed in starting_seed..(starting_seed + num_iterations) {
1594            eprintln!("seed = {}", seed);
1595            let mut rng = StdRng::seed_from_u64(seed);
1596
1597            let rng = &mut rng;
1598            let mut tree = SumTree::<u8>::default();
1599            let count = rng.random_range(0..10);
1600            if rng.random() {
1601                tree.extend(rng.sample_iter(StandardUniform).take(count), ());
1602            } else {
1603                let items = rng
1604                    .sample_iter(StandardUniform)
1605                    .take(count)
1606                    .collect::<Vec<_>>();
1607                tree.par_extend(items, ());
1608            }
1609
1610            for _ in 0..num_operations {
1611                let splice_end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1612                let splice_start = rng.random_range(0..splice_end + 1);
1613                let count = rng.random_range(0..10);
1614                let tree_end = tree.extent::<Count>(());
1615                let new_items = rng
1616                    .sample_iter(StandardUniform)
1617                    .take(count)
1618                    .collect::<Vec<u8>>();
1619
1620                let mut reference_items = tree.items(());
1621                reference_items.splice(splice_start..splice_end, new_items.clone());
1622
1623                tree = {
1624                    let mut cursor = tree.cursor::<Count>(());
1625                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
1626                    if rng.random() {
1627                        new_tree.extend(new_items, ());
1628                    } else {
1629                        new_tree.par_extend(new_items, ());
1630                    }
1631                    cursor.seek(&Count(splice_end), Bias::Right);
1632                    new_tree.append(cursor.slice(&tree_end, Bias::Right), ());
1633                    new_tree
1634                };
1635
1636                assert_eq!(tree.items(()), reference_items);
1637                assert_eq!(
1638                    tree.iter().collect::<Vec<_>>(),
1639                    tree.cursor::<()>(()).collect::<Vec<_>>()
1640                );
1641
1642                log::info!("tree items: {:?}", tree.items(()));
1643
1644                let mut filter_cursor =
1645                    tree.filter::<_, Count>((), |summary| summary.contains_even);
1646                let expected_filtered_items = tree
1647                    .items(())
1648                    .into_iter()
1649                    .enumerate()
1650                    .filter(|(_, item)| (item & 1) == 0)
1651                    .collect::<Vec<_>>();
1652
1653                let mut item_ix = if rng.random() {
1654                    filter_cursor.next();
1655                    0
1656                } else {
1657                    filter_cursor.prev();
1658                    expected_filtered_items.len().saturating_sub(1)
1659                };
1660                while item_ix < expected_filtered_items.len() {
1661                    log::info!("filter_cursor, item_ix: {}", item_ix);
1662                    let actual_item = filter_cursor.item().unwrap();
1663                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
1664                    assert_eq!(actual_item, &reference_item);
1665                    assert_eq!(filter_cursor.start().0, reference_index);
1666                    log::info!("next");
1667                    filter_cursor.next();
1668                    item_ix += 1;
1669
1670                    while item_ix > 0 && rng.random_bool(0.2) {
1671                        log::info!("prev");
1672                        filter_cursor.prev();
1673                        item_ix -= 1;
1674
1675                        if item_ix == 0 && rng.random_bool(0.2) {
1676                            filter_cursor.prev();
1677                            assert_eq!(filter_cursor.item(), None);
1678                            assert_eq!(filter_cursor.start().0, 0);
1679                            filter_cursor.next();
1680                        }
1681                    }
1682                }
1683                assert_eq!(filter_cursor.item(), None);
1684
1685                let mut before_start = false;
1686                let mut cursor = tree.cursor::<Count>(());
1687                let start_pos = rng.random_range(0..=reference_items.len());
1688                cursor.seek(&Count(start_pos), Bias::Right);
1689                let mut pos = rng.random_range(start_pos..=reference_items.len());
1690                cursor.seek_forward(&Count(pos), Bias::Right);
1691
1692                for i in 0..10 {
1693                    assert_eq!(cursor.start().0, pos);
1694
1695                    if pos > 0 {
1696                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1697                    } else {
1698                        assert_eq!(cursor.prev_item(), None);
1699                    }
1700
1701                    if pos < reference_items.len() && !before_start {
1702                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1703                    } else {
1704                        assert_eq!(cursor.item(), None);
1705                    }
1706
1707                    if before_start {
1708                        assert_eq!(cursor.next_item(), reference_items.first());
1709                    } else if pos + 1 < reference_items.len() {
1710                        assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1711                    } else {
1712                        assert_eq!(cursor.next_item(), None);
1713                    }
1714
1715                    if i < 5 {
1716                        cursor.next();
1717                        if pos < reference_items.len() {
1718                            pos += 1;
1719                            before_start = false;
1720                        }
1721                    } else {
1722                        cursor.prev();
1723                        if pos == 0 {
1724                            before_start = true;
1725                        }
1726                        pos = pos.saturating_sub(1);
1727                    }
1728                }
1729            }
1730
1731            for _ in 0..10 {
1732                let end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1733                let start = rng.random_range(0..end + 1);
1734                let start_bias = if rng.random() {
1735                    Bias::Left
1736                } else {
1737                    Bias::Right
1738                };
1739                let end_bias = if rng.random() {
1740                    Bias::Left
1741                } else {
1742                    Bias::Right
1743                };
1744
1745                let mut cursor = tree.cursor::<Count>(());
1746                cursor.seek(&Count(start), start_bias);
1747                let slice = cursor.slice(&Count(end), end_bias);
1748
1749                cursor.seek(&Count(start), start_bias);
1750                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1751
1752                assert_eq!(summary.0, slice.summary().sum);
1753            }
1754        }
1755    }
1756
1757    #[test]
1758    fn test_cursor() {
1759        // Empty tree
1760        let tree = SumTree::<u8>::default();
1761        let mut cursor = tree.cursor::<IntegersSummary>(());
1762        assert_eq!(
1763            cursor.slice(&Count(0), Bias::Right).items(()),
1764            Vec::<u8>::new()
1765        );
1766        assert_eq!(cursor.item(), None);
1767        assert_eq!(cursor.prev_item(), None);
1768        assert_eq!(cursor.next_item(), None);
1769        assert_eq!(cursor.start().sum, 0);
1770        cursor.prev();
1771        assert_eq!(cursor.item(), None);
1772        assert_eq!(cursor.prev_item(), None);
1773        assert_eq!(cursor.next_item(), None);
1774        assert_eq!(cursor.start().sum, 0);
1775        cursor.next();
1776        assert_eq!(cursor.item(), None);
1777        assert_eq!(cursor.prev_item(), None);
1778        assert_eq!(cursor.next_item(), None);
1779        assert_eq!(cursor.start().sum, 0);
1780
1781        // Single-element tree
1782        let mut tree = SumTree::<u8>::default();
1783        tree.extend(vec![1], ());
1784        let mut cursor = tree.cursor::<IntegersSummary>(());
1785        assert_eq!(
1786            cursor.slice(&Count(0), Bias::Right).items(()),
1787            Vec::<u8>::new()
1788        );
1789        assert_eq!(cursor.item(), Some(&1));
1790        assert_eq!(cursor.prev_item(), None);
1791        assert_eq!(cursor.next_item(), None);
1792        assert_eq!(cursor.start().sum, 0);
1793
1794        cursor.next();
1795        assert_eq!(cursor.item(), None);
1796        assert_eq!(cursor.prev_item(), Some(&1));
1797        assert_eq!(cursor.next_item(), None);
1798        assert_eq!(cursor.start().sum, 1);
1799
1800        cursor.prev();
1801        assert_eq!(cursor.item(), Some(&1));
1802        assert_eq!(cursor.prev_item(), None);
1803        assert_eq!(cursor.next_item(), None);
1804        assert_eq!(cursor.start().sum, 0);
1805
1806        let mut cursor = tree.cursor::<IntegersSummary>(());
1807        assert_eq!(cursor.slice(&Count(1), Bias::Right).items(()), [1]);
1808        assert_eq!(cursor.item(), None);
1809        assert_eq!(cursor.prev_item(), Some(&1));
1810        assert_eq!(cursor.next_item(), None);
1811        assert_eq!(cursor.start().sum, 1);
1812
1813        cursor.seek(&Count(0), Bias::Right);
1814        assert_eq!(
1815            cursor
1816                .slice(&tree.extent::<Count>(()), Bias::Right)
1817                .items(()),
1818            [1]
1819        );
1820        assert_eq!(cursor.item(), None);
1821        assert_eq!(cursor.prev_item(), Some(&1));
1822        assert_eq!(cursor.next_item(), None);
1823        assert_eq!(cursor.start().sum, 1);
1824
1825        // Multiple-element tree
1826        let mut tree = SumTree::default();
1827        tree.extend(vec![1, 2, 3, 4, 5, 6], ());
1828        let mut cursor = tree.cursor::<IntegersSummary>(());
1829
1830        assert_eq!(cursor.slice(&Count(2), Bias::Right).items(()), [1, 2]);
1831        assert_eq!(cursor.item(), Some(&3));
1832        assert_eq!(cursor.prev_item(), Some(&2));
1833        assert_eq!(cursor.next_item(), Some(&4));
1834        assert_eq!(cursor.start().sum, 3);
1835
1836        cursor.next();
1837        assert_eq!(cursor.item(), Some(&4));
1838        assert_eq!(cursor.prev_item(), Some(&3));
1839        assert_eq!(cursor.next_item(), Some(&5));
1840        assert_eq!(cursor.start().sum, 6);
1841
1842        cursor.next();
1843        assert_eq!(cursor.item(), Some(&5));
1844        assert_eq!(cursor.prev_item(), Some(&4));
1845        assert_eq!(cursor.next_item(), Some(&6));
1846        assert_eq!(cursor.start().sum, 10);
1847
1848        cursor.next();
1849        assert_eq!(cursor.item(), Some(&6));
1850        assert_eq!(cursor.prev_item(), Some(&5));
1851        assert_eq!(cursor.next_item(), None);
1852        assert_eq!(cursor.start().sum, 15);
1853
1854        cursor.next();
1855        cursor.next();
1856        assert_eq!(cursor.item(), None);
1857        assert_eq!(cursor.prev_item(), Some(&6));
1858        assert_eq!(cursor.next_item(), None);
1859        assert_eq!(cursor.start().sum, 21);
1860
1861        cursor.prev();
1862        assert_eq!(cursor.item(), Some(&6));
1863        assert_eq!(cursor.prev_item(), Some(&5));
1864        assert_eq!(cursor.next_item(), None);
1865        assert_eq!(cursor.start().sum, 15);
1866
1867        cursor.prev();
1868        assert_eq!(cursor.item(), Some(&5));
1869        assert_eq!(cursor.prev_item(), Some(&4));
1870        assert_eq!(cursor.next_item(), Some(&6));
1871        assert_eq!(cursor.start().sum, 10);
1872
1873        cursor.prev();
1874        assert_eq!(cursor.item(), Some(&4));
1875        assert_eq!(cursor.prev_item(), Some(&3));
1876        assert_eq!(cursor.next_item(), Some(&5));
1877        assert_eq!(cursor.start().sum, 6);
1878
1879        cursor.prev();
1880        assert_eq!(cursor.item(), Some(&3));
1881        assert_eq!(cursor.prev_item(), Some(&2));
1882        assert_eq!(cursor.next_item(), Some(&4));
1883        assert_eq!(cursor.start().sum, 3);
1884
1885        cursor.prev();
1886        assert_eq!(cursor.item(), Some(&2));
1887        assert_eq!(cursor.prev_item(), Some(&1));
1888        assert_eq!(cursor.next_item(), Some(&3));
1889        assert_eq!(cursor.start().sum, 1);
1890
1891        cursor.prev();
1892        assert_eq!(cursor.item(), Some(&1));
1893        assert_eq!(cursor.prev_item(), None);
1894        assert_eq!(cursor.next_item(), Some(&2));
1895        assert_eq!(cursor.start().sum, 0);
1896
1897        cursor.prev();
1898        assert_eq!(cursor.item(), None);
1899        assert_eq!(cursor.prev_item(), None);
1900        assert_eq!(cursor.next_item(), Some(&1));
1901        assert_eq!(cursor.start().sum, 0);
1902
1903        cursor.next();
1904        assert_eq!(cursor.item(), Some(&1));
1905        assert_eq!(cursor.prev_item(), None);
1906        assert_eq!(cursor.next_item(), Some(&2));
1907        assert_eq!(cursor.start().sum, 0);
1908
1909        let mut cursor = tree.cursor::<IntegersSummary>(());
1910        assert_eq!(
1911            cursor
1912                .slice(&tree.extent::<Count>(()), Bias::Right)
1913                .items(()),
1914            tree.items(())
1915        );
1916        assert_eq!(cursor.item(), None);
1917        assert_eq!(cursor.prev_item(), Some(&6));
1918        assert_eq!(cursor.next_item(), None);
1919        assert_eq!(cursor.start().sum, 21);
1920
1921        cursor.seek(&Count(3), Bias::Right);
1922        assert_eq!(
1923            cursor
1924                .slice(&tree.extent::<Count>(()), Bias::Right)
1925                .items(()),
1926            [4, 5, 6]
1927        );
1928        assert_eq!(cursor.item(), None);
1929        assert_eq!(cursor.prev_item(), Some(&6));
1930        assert_eq!(cursor.next_item(), None);
1931        assert_eq!(cursor.start().sum, 21);
1932
1933        // Seeking can bias left or right
1934        cursor.seek(&Count(1), Bias::Left);
1935        assert_eq!(cursor.item(), Some(&1));
1936        cursor.seek(&Count(1), Bias::Right);
1937        assert_eq!(cursor.item(), Some(&2));
1938
1939        // Slicing without resetting starts from where the cursor is parked at.
1940        cursor.seek(&Count(1), Bias::Right);
1941        assert_eq!(cursor.slice(&Count(3), Bias::Right).items(()), vec![2, 3]);
1942        assert_eq!(cursor.slice(&Count(6), Bias::Left).items(()), vec![4, 5]);
1943        assert_eq!(cursor.slice(&Count(6), Bias::Right).items(()), vec![6]);
1944    }
1945
1946    #[test]
1947    fn test_edit() {
1948        let mut tree = SumTree::<u8>::default();
1949
1950        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], ());
1951        assert_eq!(tree.items(()), vec![0, 1, 2]);
1952        assert_eq!(removed, Vec::<u8>::new());
1953        assert_eq!(tree.get(&0, ()), Some(&0));
1954        assert_eq!(tree.get(&1, ()), Some(&1));
1955        assert_eq!(tree.get(&2, ()), Some(&2));
1956        assert_eq!(tree.get(&4, ()), None);
1957
1958        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], ());
1959        assert_eq!(tree.items(()), vec![1, 2, 4]);
1960        assert_eq!(removed, vec![0, 2]);
1961        assert_eq!(tree.get(&0, ()), None);
1962        assert_eq!(tree.get(&1, ()), Some(&1));
1963        assert_eq!(tree.get(&2, ()), Some(&2));
1964        assert_eq!(tree.get(&4, ()), Some(&4));
1965
1966        // An edit of an empty tree packs its leaves as `from_iter` does.
1967        let mut tree = SumTree::<u8>::default();
1968        tree.edit((0..5).map(Edit::Insert).collect(), ());
1969        let packed = SumTree::<u8>::from_iter(0..5, ());
1970        assert_eq!(tree.0.child_summaries(), packed.0.child_summaries());
1971
1972        // Each insert of a repeated key replaces one item, here in two different leaves.
1973        let mut tree = SumTree::from_iter([1u8, 2, 3, 5, 5, 6, 7, 8], ());
1974        let removed = tree.edit(vec![Edit::Insert(5), Edit::Insert(5)], ());
1975        assert_eq!(removed, vec![5, 5]);
1976        assert_eq!(tree.items(()), vec![1, 2, 3, 5, 5, 6, 7, 8]);
1977    }
1978
1979    #[test]
1980    fn test_inserts_in_place() {
1981        use std::collections::BTreeSet;
1982
1983        fn check(tree: &SumTree<u8>, is_root: bool, may_underflow: bool) -> u8 {
1984            let node = tree.0.as_ref();
1985            let child_summaries = node.child_summaries();
1986            assert!(is_root || may_underflow || !node.is_underflowing());
1987            assert_eq!(node.summary(), &sum(child_summaries.iter(), ()));
1988            match node {
1989                Node::Leaf { items, .. } => {
1990                    let item_summaries = items.iter().map(|item| item.summary(()));
1991                    assert!(item_summaries.eq(child_summaries.iter().cloned()));
1992                    0
1993                }
1994                Node::Internal {
1995                    height,
1996                    child_trees,
1997                    ..
1998                } => {
1999                    for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
2000                        assert_eq!(child_tree.summary(), child_summary);
2001                        assert_eq!(check(child_tree, false, may_underflow) + 1, *height);
2002                    }
2003                    *height
2004                }
2005            }
2006        }
2007
2008        let mut rng = StdRng::seed_from_u64(0);
2009        for _ in 0..1000 {
2010            // `edit` builds an empty tree with `from_iter`, so start with one item.
2011            let first = rng.random::<u8>();
2012            let mut tree = SumTree::from_item(first, ());
2013            let mut expected = BTreeSet::from([first]);
2014            let mut snapshots = Vec::new();
2015            // Removals slice the tree, which leaves nodes that underflow.
2016            let with_removals = rng.random();
2017            for _ in 0..rng.random_range(1..10) {
2018                // A narrow range puts a whole batch in a few leaves.
2019                let (start, width) = (rng.random::<u8>(), if rng.random() { 8 } else { 255 });
2020                let batch = (0..rng.random_range(1..40))
2021                    .map(|_| start.wrapping_add(rng.random_range(0..=width)))
2022                    .collect::<BTreeSet<u8>>();
2023                let remove = with_removals && rng.random();
2024                let edit: fn(u8) -> Edit<u8> = if remove { Edit::Remove } else { Edit::Insert };
2025                let mut edits = batch.iter().copied().map(edit).collect::<Vec<_>>();
2026                edits.shuffle(&mut rng);
2027
2028                let replaced = match edits.as_slice() {
2029                    [Edit::Insert(item)] => tree.insert_or_replace(*item, ()).into_iter().collect(),
2030                    _ => tree.edit(edits, ()),
2031                };
2032                assert!(replaced.iter().eq(batch.intersection(&expected)));
2033                if remove {
2034                    expected.retain(|item| !batch.contains(item));
2035                } else {
2036                    expected.extend(batch);
2037                }
2038                check(&tree, true, with_removals);
2039                assert!(tree.iter().eq(&expected));
2040                if rng.random() {
2041                    snapshots.push((tree.clone(), expected.clone()));
2042                }
2043                for (snapshot, expected) in &snapshots {
2044                    assert!(snapshot.iter().eq(expected));
2045                }
2046            }
2047        }
2048    }
2049
2050    #[test]
2051    fn test_from_iter() {
2052        assert_eq!(
2053            SumTree::from_iter(0..100, ()).items(()),
2054            (0..100).collect::<Vec<_>>()
2055        );
2056
2057        // Ensure `from_iter` works correctly when the given iterator restarts
2058        // after calling `next` if `None` was already returned.
2059        let mut ix = 0;
2060        let iterator = std::iter::from_fn(|| {
2061            ix = (ix + 1) % 2;
2062            if ix == 1 { Some(1) } else { None }
2063        });
2064        assert_eq!(SumTree::from_iter(iterator, ()).items(()), vec![1]);
2065    }
2066
2067    #[derive(Clone, Default, Debug, PartialEq)]
2068    pub struct IntegersSummary {
2069        count: usize,
2070        sum: usize,
2071        contains_even: bool,
2072        max: u8,
2073    }
2074
2075    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
2076    struct Count(usize);
2077
2078    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
2079    struct Sum(usize);
2080
2081    impl Item for u8 {
2082        type Summary = IntegersSummary;
2083
2084        fn summary(&self, _cx: ()) -> Self::Summary {
2085            IntegersSummary {
2086                count: 1,
2087                sum: *self as usize,
2088                contains_even: (*self & 1) == 0,
2089                max: *self,
2090            }
2091        }
2092    }
2093
2094    impl KeyedItem for u8 {
2095        type Key = u8;
2096
2097        fn key(&self) -> Self::Key {
2098            *self
2099        }
2100    }
2101
2102    impl ContextLessSummary for IntegersSummary {
2103        fn zero() -> Self {
2104            Default::default()
2105        }
2106
2107        fn add_summary(&mut self, other: &Self) {
2108            self.count += other.count;
2109            self.sum += other.sum;
2110            self.contains_even |= other.contains_even;
2111            self.max = cmp::max(self.max, other.max);
2112        }
2113    }
2114
2115    impl Dimension<'_, IntegersSummary> for u8 {
2116        fn zero(_cx: ()) -> Self {
2117            Default::default()
2118        }
2119
2120        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
2121            *self = summary.max;
2122        }
2123    }
2124
2125    impl Dimension<'_, IntegersSummary> for Count {
2126        fn zero(_cx: ()) -> Self {
2127            Default::default()
2128        }
2129
2130        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
2131            self.0 += summary.count;
2132        }
2133    }
2134
2135    impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
2136        fn cmp(&self, cursor_location: &IntegersSummary, _: ()) -> Ordering {
2137            self.0.cmp(&cursor_location.count)
2138        }
2139    }
2140
2141    impl Dimension<'_, IntegersSummary> for Sum {
2142        fn zero(_cx: ()) -> Self {
2143            Default::default()
2144        }
2145
2146        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
2147            self.0 += summary.sum;
2148        }
2149    }
2150}