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        let mut replaced = None;
1154        {
1155            let mut cursor = self.cursor::<T::Key>(cx);
1156            let mut new_tree = cursor.slice(&item.key(), Bias::Left);
1157            if let Some(cursor_item) = cursor.item()
1158                && cursor_item.key() == item.key()
1159            {
1160                replaced = Some(cursor_item.clone());
1161                cursor.next();
1162            }
1163            new_tree.push(item, cx);
1164            new_tree.append(cursor.suffix(), cx);
1165            drop(cursor);
1166            *self = new_tree
1167        };
1168        replaced
1169    }
1170
1171    pub fn remove(&mut self, key: &T::Key, cx: <T::Summary as Summary>::Context<'_>) -> Option<T> {
1172        let mut removed = None;
1173        *self = {
1174            let mut cursor = self.cursor::<T::Key>(cx);
1175            let mut new_tree = cursor.slice(key, Bias::Left);
1176            if let Some(item) = cursor.item()
1177                && item.key() == *key
1178            {
1179                removed = Some(item.clone());
1180                cursor.next();
1181            }
1182            new_tree.append(cursor.suffix(), cx);
1183            new_tree
1184        };
1185        removed
1186    }
1187
1188    pub fn edit(
1189        &mut self,
1190        mut edits: Vec<Edit<T>>,
1191        cx: <T::Summary as Summary>::Context<'_>,
1192    ) -> Vec<T> {
1193        if edits.is_empty() {
1194            return Vec::new();
1195        }
1196
1197        let mut removed = Vec::new();
1198        edits.sort_unstable_by_key(|item| item.key());
1199
1200        *self = {
1201            let mut cursor = self.cursor::<T::Key>(cx);
1202            let mut new_tree = SumTree::new(cx);
1203            let mut buffered_items = Vec::new();
1204
1205            cursor.seek(&T::Key::zero(cx), Bias::Left);
1206            for edit in edits {
1207                let new_key = edit.key();
1208                let mut old_item = cursor.item();
1209
1210                if old_item
1211                    .as_ref()
1212                    .is_some_and(|old_item| old_item.key() < new_key)
1213                {
1214                    new_tree.extend(buffered_items.drain(..), cx);
1215                    let slice = cursor.slice(&new_key, Bias::Left);
1216                    new_tree.append(slice, cx);
1217                    old_item = cursor.item();
1218                }
1219
1220                if let Some(old_item) = old_item
1221                    && old_item.key() == new_key
1222                {
1223                    removed.push(old_item.clone());
1224                    cursor.next();
1225                }
1226
1227                match edit {
1228                    Edit::Insert(item) => {
1229                        buffered_items.push(item);
1230                    }
1231                    Edit::Remove(_) => {}
1232                }
1233            }
1234
1235            new_tree.extend(buffered_items, cx);
1236            new_tree.append(cursor.suffix(), cx);
1237            new_tree
1238        };
1239
1240        removed
1241    }
1242
1243    pub fn get<'a>(
1244        &'a self,
1245        key: &T::Key,
1246        cx: <T::Summary as Summary>::Context<'a>,
1247    ) -> Option<&'a T> {
1248        if let (_, _, Some(item)) = self.find_exact::<T::Key, _>(cx, key, Bias::Left) {
1249            Some(item)
1250        } else {
1251            None
1252        }
1253    }
1254}
1255
1256impl<T, S> Default for SumTree<T>
1257where
1258    T: Item<Summary = S>,
1259    S: for<'a> Summary<Context<'a> = ()>,
1260{
1261    fn default() -> Self {
1262        Self::new(())
1263    }
1264}
1265
1266#[derive(Clone)]
1267pub enum Node<T: Item> {
1268    Internal {
1269        height: u8,
1270        summary: T::Summary,
1271        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8>,
1272        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }, u8>,
1273    },
1274    Leaf {
1275        summary: T::Summary,
1276        items: ArrayVec<T, { 2 * TREE_BASE }, u8>,
1277        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }, u8>,
1278    },
1279}
1280
1281impl<T> fmt::Debug for Node<T>
1282where
1283    T: Item + fmt::Debug,
1284    T::Summary: fmt::Debug,
1285{
1286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1287        match self {
1288            Node::Internal {
1289                height,
1290                summary,
1291                child_summaries,
1292                child_trees,
1293            } => f
1294                .debug_struct("Internal")
1295                .field("height", height)
1296                .field("summary", summary)
1297                .field("child_summaries", child_summaries)
1298                .field("child_trees", child_trees)
1299                .finish(),
1300            Node::Leaf {
1301                summary,
1302                items,
1303                item_summaries,
1304            } => f
1305                .debug_struct("Leaf")
1306                .field("summary", summary)
1307                .field("items", items)
1308                .field("item_summaries", item_summaries)
1309                .finish(),
1310        }
1311    }
1312}
1313
1314impl<T: Item> Node<T> {
1315    fn is_leaf(&self) -> bool {
1316        matches!(self, Node::Leaf { .. })
1317    }
1318
1319    fn height(&self) -> u8 {
1320        match self {
1321            Node::Internal { height, .. } => *height,
1322            Node::Leaf { .. } => 0,
1323        }
1324    }
1325
1326    fn summary(&self) -> &T::Summary {
1327        match self {
1328            Node::Internal { summary, .. } => summary,
1329            Node::Leaf { summary, .. } => summary,
1330        }
1331    }
1332
1333    fn child_summaries(&self) -> &[T::Summary] {
1334        match self {
1335            Node::Internal {
1336                child_summaries, ..
1337            } => child_summaries.as_slice(),
1338            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
1339        }
1340    }
1341
1342    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }, u8> {
1343        match self {
1344            Node::Internal { child_trees, .. } => child_trees,
1345            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
1346        }
1347    }
1348
1349    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }, u8> {
1350        match self {
1351            Node::Leaf { items, .. } => items,
1352            Node::Internal { .. } => panic!("Internal nodes have no items"),
1353        }
1354    }
1355
1356    fn is_underflowing(&self) -> bool {
1357        match self {
1358            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
1359            Node::Leaf { items, .. } => items.len() < TREE_BASE,
1360        }
1361    }
1362}
1363
1364#[derive(Debug)]
1365pub enum Edit<T: KeyedItem> {
1366    Insert(T),
1367    Remove(T::Key),
1368}
1369
1370impl<T: KeyedItem> Edit<T> {
1371    fn key(&self) -> T::Key {
1372        match self {
1373            Edit::Insert(item) => item.key(),
1374            Edit::Remove(key) => key.clone(),
1375        }
1376    }
1377}
1378
1379fn sum<'a, T, I>(iter: I, cx: T::Context<'_>) -> T
1380where
1381    T: 'a + Summary,
1382    I: Iterator<Item = &'a T>,
1383{
1384    let mut sum = T::zero(cx);
1385    for value in iter {
1386        sum.add_summary(value, cx);
1387    }
1388    sum
1389}
1390
1391#[cfg(test)]
1392mod tests {
1393    use super::*;
1394    use rand::{distr::StandardUniform, prelude::*};
1395    use std::cmp;
1396
1397    #[ctor::ctor(unsafe)]
1398    fn init_logger() {
1399        zlog::init_test();
1400    }
1401
1402    #[test]
1403    fn test_extend_and_push_tree() {
1404        let mut tree1 = SumTree::default();
1405        tree1.extend(0..20, ());
1406
1407        let mut tree2 = SumTree::default();
1408        tree2.extend(50..100, ());
1409
1410        tree1.append(tree2, ());
1411        assert_eq!(tree1.items(()), (0..20).chain(50..100).collect::<Vec<u8>>());
1412    }
1413
1414    #[test]
1415    fn test_random() {
1416        let mut starting_seed = 0;
1417        if let Ok(value) = std::env::var("SEED") {
1418            starting_seed = value.parse().expect("invalid SEED variable");
1419        }
1420        let mut num_iterations = 100;
1421        if let Ok(value) = std::env::var("ITERATIONS") {
1422            num_iterations = value.parse().expect("invalid ITERATIONS variable");
1423        }
1424        let num_operations = std::env::var("OPERATIONS")
1425            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
1426
1427        for seed in starting_seed..(starting_seed + num_iterations) {
1428            eprintln!("seed = {}", seed);
1429            let mut rng = StdRng::seed_from_u64(seed);
1430
1431            let rng = &mut rng;
1432            let mut tree = SumTree::<u8>::default();
1433            let count = rng.random_range(0..10);
1434            if rng.random() {
1435                tree.extend(rng.sample_iter(StandardUniform).take(count), ());
1436            } else {
1437                let items = rng
1438                    .sample_iter(StandardUniform)
1439                    .take(count)
1440                    .collect::<Vec<_>>();
1441                tree.par_extend(items, ());
1442            }
1443
1444            for _ in 0..num_operations {
1445                let splice_end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1446                let splice_start = rng.random_range(0..splice_end + 1);
1447                let count = rng.random_range(0..10);
1448                let tree_end = tree.extent::<Count>(());
1449                let new_items = rng
1450                    .sample_iter(StandardUniform)
1451                    .take(count)
1452                    .collect::<Vec<u8>>();
1453
1454                let mut reference_items = tree.items(());
1455                reference_items.splice(splice_start..splice_end, new_items.clone());
1456
1457                tree = {
1458                    let mut cursor = tree.cursor::<Count>(());
1459                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
1460                    if rng.random() {
1461                        new_tree.extend(new_items, ());
1462                    } else {
1463                        new_tree.par_extend(new_items, ());
1464                    }
1465                    cursor.seek(&Count(splice_end), Bias::Right);
1466                    new_tree.append(cursor.slice(&tree_end, Bias::Right), ());
1467                    new_tree
1468                };
1469
1470                assert_eq!(tree.items(()), reference_items);
1471                assert_eq!(
1472                    tree.iter().collect::<Vec<_>>(),
1473                    tree.cursor::<()>(()).collect::<Vec<_>>()
1474                );
1475
1476                log::info!("tree items: {:?}", tree.items(()));
1477
1478                let mut filter_cursor =
1479                    tree.filter::<_, Count>((), |summary| summary.contains_even);
1480                let expected_filtered_items = tree
1481                    .items(())
1482                    .into_iter()
1483                    .enumerate()
1484                    .filter(|(_, item)| (item & 1) == 0)
1485                    .collect::<Vec<_>>();
1486
1487                let mut item_ix = if rng.random() {
1488                    filter_cursor.next();
1489                    0
1490                } else {
1491                    filter_cursor.prev();
1492                    expected_filtered_items.len().saturating_sub(1)
1493                };
1494                while item_ix < expected_filtered_items.len() {
1495                    log::info!("filter_cursor, item_ix: {}", item_ix);
1496                    let actual_item = filter_cursor.item().unwrap();
1497                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
1498                    assert_eq!(actual_item, &reference_item);
1499                    assert_eq!(filter_cursor.start().0, reference_index);
1500                    log::info!("next");
1501                    filter_cursor.next();
1502                    item_ix += 1;
1503
1504                    while item_ix > 0 && rng.random_bool(0.2) {
1505                        log::info!("prev");
1506                        filter_cursor.prev();
1507                        item_ix -= 1;
1508
1509                        if item_ix == 0 && rng.random_bool(0.2) {
1510                            filter_cursor.prev();
1511                            assert_eq!(filter_cursor.item(), None);
1512                            assert_eq!(filter_cursor.start().0, 0);
1513                            filter_cursor.next();
1514                        }
1515                    }
1516                }
1517                assert_eq!(filter_cursor.item(), None);
1518
1519                let mut before_start = false;
1520                let mut cursor = tree.cursor::<Count>(());
1521                let start_pos = rng.random_range(0..=reference_items.len());
1522                cursor.seek(&Count(start_pos), Bias::Right);
1523                let mut pos = rng.random_range(start_pos..=reference_items.len());
1524                cursor.seek_forward(&Count(pos), Bias::Right);
1525
1526                for i in 0..10 {
1527                    assert_eq!(cursor.start().0, pos);
1528
1529                    if pos > 0 {
1530                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1531                    } else {
1532                        assert_eq!(cursor.prev_item(), None);
1533                    }
1534
1535                    if pos < reference_items.len() && !before_start {
1536                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1537                    } else {
1538                        assert_eq!(cursor.item(), None);
1539                    }
1540
1541                    if before_start {
1542                        assert_eq!(cursor.next_item(), reference_items.first());
1543                    } else if pos + 1 < reference_items.len() {
1544                        assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1545                    } else {
1546                        assert_eq!(cursor.next_item(), None);
1547                    }
1548
1549                    if i < 5 {
1550                        cursor.next();
1551                        if pos < reference_items.len() {
1552                            pos += 1;
1553                            before_start = false;
1554                        }
1555                    } else {
1556                        cursor.prev();
1557                        if pos == 0 {
1558                            before_start = true;
1559                        }
1560                        pos = pos.saturating_sub(1);
1561                    }
1562                }
1563            }
1564
1565            for _ in 0..10 {
1566                let end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1567                let start = rng.random_range(0..end + 1);
1568                let start_bias = if rng.random() {
1569                    Bias::Left
1570                } else {
1571                    Bias::Right
1572                };
1573                let end_bias = if rng.random() {
1574                    Bias::Left
1575                } else {
1576                    Bias::Right
1577                };
1578
1579                let mut cursor = tree.cursor::<Count>(());
1580                cursor.seek(&Count(start), start_bias);
1581                let slice = cursor.slice(&Count(end), end_bias);
1582
1583                cursor.seek(&Count(start), start_bias);
1584                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1585
1586                assert_eq!(summary.0, slice.summary().sum);
1587            }
1588        }
1589    }
1590
1591    #[test]
1592    fn test_cursor() {
1593        // Empty tree
1594        let tree = SumTree::<u8>::default();
1595        let mut cursor = tree.cursor::<IntegersSummary>(());
1596        assert_eq!(
1597            cursor.slice(&Count(0), Bias::Right).items(()),
1598            Vec::<u8>::new()
1599        );
1600        assert_eq!(cursor.item(), None);
1601        assert_eq!(cursor.prev_item(), None);
1602        assert_eq!(cursor.next_item(), None);
1603        assert_eq!(cursor.start().sum, 0);
1604        cursor.prev();
1605        assert_eq!(cursor.item(), None);
1606        assert_eq!(cursor.prev_item(), None);
1607        assert_eq!(cursor.next_item(), None);
1608        assert_eq!(cursor.start().sum, 0);
1609        cursor.next();
1610        assert_eq!(cursor.item(), None);
1611        assert_eq!(cursor.prev_item(), None);
1612        assert_eq!(cursor.next_item(), None);
1613        assert_eq!(cursor.start().sum, 0);
1614
1615        // Single-element tree
1616        let mut tree = SumTree::<u8>::default();
1617        tree.extend(vec![1], ());
1618        let mut cursor = tree.cursor::<IntegersSummary>(());
1619        assert_eq!(
1620            cursor.slice(&Count(0), Bias::Right).items(()),
1621            Vec::<u8>::new()
1622        );
1623        assert_eq!(cursor.item(), Some(&1));
1624        assert_eq!(cursor.prev_item(), None);
1625        assert_eq!(cursor.next_item(), None);
1626        assert_eq!(cursor.start().sum, 0);
1627
1628        cursor.next();
1629        assert_eq!(cursor.item(), None);
1630        assert_eq!(cursor.prev_item(), Some(&1));
1631        assert_eq!(cursor.next_item(), None);
1632        assert_eq!(cursor.start().sum, 1);
1633
1634        cursor.prev();
1635        assert_eq!(cursor.item(), Some(&1));
1636        assert_eq!(cursor.prev_item(), None);
1637        assert_eq!(cursor.next_item(), None);
1638        assert_eq!(cursor.start().sum, 0);
1639
1640        let mut cursor = tree.cursor::<IntegersSummary>(());
1641        assert_eq!(cursor.slice(&Count(1), Bias::Right).items(()), [1]);
1642        assert_eq!(cursor.item(), None);
1643        assert_eq!(cursor.prev_item(), Some(&1));
1644        assert_eq!(cursor.next_item(), None);
1645        assert_eq!(cursor.start().sum, 1);
1646
1647        cursor.seek(&Count(0), Bias::Right);
1648        assert_eq!(
1649            cursor
1650                .slice(&tree.extent::<Count>(()), Bias::Right)
1651                .items(()),
1652            [1]
1653        );
1654        assert_eq!(cursor.item(), None);
1655        assert_eq!(cursor.prev_item(), Some(&1));
1656        assert_eq!(cursor.next_item(), None);
1657        assert_eq!(cursor.start().sum, 1);
1658
1659        // Multiple-element tree
1660        let mut tree = SumTree::default();
1661        tree.extend(vec![1, 2, 3, 4, 5, 6], ());
1662        let mut cursor = tree.cursor::<IntegersSummary>(());
1663
1664        assert_eq!(cursor.slice(&Count(2), Bias::Right).items(()), [1, 2]);
1665        assert_eq!(cursor.item(), Some(&3));
1666        assert_eq!(cursor.prev_item(), Some(&2));
1667        assert_eq!(cursor.next_item(), Some(&4));
1668        assert_eq!(cursor.start().sum, 3);
1669
1670        cursor.next();
1671        assert_eq!(cursor.item(), Some(&4));
1672        assert_eq!(cursor.prev_item(), Some(&3));
1673        assert_eq!(cursor.next_item(), Some(&5));
1674        assert_eq!(cursor.start().sum, 6);
1675
1676        cursor.next();
1677        assert_eq!(cursor.item(), Some(&5));
1678        assert_eq!(cursor.prev_item(), Some(&4));
1679        assert_eq!(cursor.next_item(), Some(&6));
1680        assert_eq!(cursor.start().sum, 10);
1681
1682        cursor.next();
1683        assert_eq!(cursor.item(), Some(&6));
1684        assert_eq!(cursor.prev_item(), Some(&5));
1685        assert_eq!(cursor.next_item(), None);
1686        assert_eq!(cursor.start().sum, 15);
1687
1688        cursor.next();
1689        cursor.next();
1690        assert_eq!(cursor.item(), None);
1691        assert_eq!(cursor.prev_item(), Some(&6));
1692        assert_eq!(cursor.next_item(), None);
1693        assert_eq!(cursor.start().sum, 21);
1694
1695        cursor.prev();
1696        assert_eq!(cursor.item(), Some(&6));
1697        assert_eq!(cursor.prev_item(), Some(&5));
1698        assert_eq!(cursor.next_item(), None);
1699        assert_eq!(cursor.start().sum, 15);
1700
1701        cursor.prev();
1702        assert_eq!(cursor.item(), Some(&5));
1703        assert_eq!(cursor.prev_item(), Some(&4));
1704        assert_eq!(cursor.next_item(), Some(&6));
1705        assert_eq!(cursor.start().sum, 10);
1706
1707        cursor.prev();
1708        assert_eq!(cursor.item(), Some(&4));
1709        assert_eq!(cursor.prev_item(), Some(&3));
1710        assert_eq!(cursor.next_item(), Some(&5));
1711        assert_eq!(cursor.start().sum, 6);
1712
1713        cursor.prev();
1714        assert_eq!(cursor.item(), Some(&3));
1715        assert_eq!(cursor.prev_item(), Some(&2));
1716        assert_eq!(cursor.next_item(), Some(&4));
1717        assert_eq!(cursor.start().sum, 3);
1718
1719        cursor.prev();
1720        assert_eq!(cursor.item(), Some(&2));
1721        assert_eq!(cursor.prev_item(), Some(&1));
1722        assert_eq!(cursor.next_item(), Some(&3));
1723        assert_eq!(cursor.start().sum, 1);
1724
1725        cursor.prev();
1726        assert_eq!(cursor.item(), Some(&1));
1727        assert_eq!(cursor.prev_item(), None);
1728        assert_eq!(cursor.next_item(), Some(&2));
1729        assert_eq!(cursor.start().sum, 0);
1730
1731        cursor.prev();
1732        assert_eq!(cursor.item(), None);
1733        assert_eq!(cursor.prev_item(), None);
1734        assert_eq!(cursor.next_item(), Some(&1));
1735        assert_eq!(cursor.start().sum, 0);
1736
1737        cursor.next();
1738        assert_eq!(cursor.item(), Some(&1));
1739        assert_eq!(cursor.prev_item(), None);
1740        assert_eq!(cursor.next_item(), Some(&2));
1741        assert_eq!(cursor.start().sum, 0);
1742
1743        let mut cursor = tree.cursor::<IntegersSummary>(());
1744        assert_eq!(
1745            cursor
1746                .slice(&tree.extent::<Count>(()), Bias::Right)
1747                .items(()),
1748            tree.items(())
1749        );
1750        assert_eq!(cursor.item(), None);
1751        assert_eq!(cursor.prev_item(), Some(&6));
1752        assert_eq!(cursor.next_item(), None);
1753        assert_eq!(cursor.start().sum, 21);
1754
1755        cursor.seek(&Count(3), Bias::Right);
1756        assert_eq!(
1757            cursor
1758                .slice(&tree.extent::<Count>(()), Bias::Right)
1759                .items(()),
1760            [4, 5, 6]
1761        );
1762        assert_eq!(cursor.item(), None);
1763        assert_eq!(cursor.prev_item(), Some(&6));
1764        assert_eq!(cursor.next_item(), None);
1765        assert_eq!(cursor.start().sum, 21);
1766
1767        // Seeking can bias left or right
1768        cursor.seek(&Count(1), Bias::Left);
1769        assert_eq!(cursor.item(), Some(&1));
1770        cursor.seek(&Count(1), Bias::Right);
1771        assert_eq!(cursor.item(), Some(&2));
1772
1773        // Slicing without resetting starts from where the cursor is parked at.
1774        cursor.seek(&Count(1), Bias::Right);
1775        assert_eq!(cursor.slice(&Count(3), Bias::Right).items(()), vec![2, 3]);
1776        assert_eq!(cursor.slice(&Count(6), Bias::Left).items(()), vec![4, 5]);
1777        assert_eq!(cursor.slice(&Count(6), Bias::Right).items(()), vec![6]);
1778    }
1779
1780    #[test]
1781    fn test_edit() {
1782        let mut tree = SumTree::<u8>::default();
1783
1784        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], ());
1785        assert_eq!(tree.items(()), vec![0, 1, 2]);
1786        assert_eq!(removed, Vec::<u8>::new());
1787        assert_eq!(tree.get(&0, ()), Some(&0));
1788        assert_eq!(tree.get(&1, ()), Some(&1));
1789        assert_eq!(tree.get(&2, ()), Some(&2));
1790        assert_eq!(tree.get(&4, ()), None);
1791
1792        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], ());
1793        assert_eq!(tree.items(()), vec![1, 2, 4]);
1794        assert_eq!(removed, vec![0, 2]);
1795        assert_eq!(tree.get(&0, ()), None);
1796        assert_eq!(tree.get(&1, ()), Some(&1));
1797        assert_eq!(tree.get(&2, ()), Some(&2));
1798        assert_eq!(tree.get(&4, ()), Some(&4));
1799    }
1800
1801    #[test]
1802    fn test_from_iter() {
1803        assert_eq!(
1804            SumTree::from_iter(0..100, ()).items(()),
1805            (0..100).collect::<Vec<_>>()
1806        );
1807
1808        // Ensure `from_iter` works correctly when the given iterator restarts
1809        // after calling `next` if `None` was already returned.
1810        let mut ix = 0;
1811        let iterator = std::iter::from_fn(|| {
1812            ix = (ix + 1) % 2;
1813            if ix == 1 { Some(1) } else { None }
1814        });
1815        assert_eq!(SumTree::from_iter(iterator, ()).items(()), vec![1]);
1816    }
1817
1818    #[derive(Clone, Default, Debug)]
1819    pub struct IntegersSummary {
1820        count: usize,
1821        sum: usize,
1822        contains_even: bool,
1823        max: u8,
1824    }
1825
1826    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1827    struct Count(usize);
1828
1829    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1830    struct Sum(usize);
1831
1832    impl Item for u8 {
1833        type Summary = IntegersSummary;
1834
1835        fn summary(&self, _cx: ()) -> Self::Summary {
1836            IntegersSummary {
1837                count: 1,
1838                sum: *self as usize,
1839                contains_even: (*self & 1) == 0,
1840                max: *self,
1841            }
1842        }
1843    }
1844
1845    impl KeyedItem for u8 {
1846        type Key = u8;
1847
1848        fn key(&self) -> Self::Key {
1849            *self
1850        }
1851    }
1852
1853    impl ContextLessSummary for IntegersSummary {
1854        fn zero() -> Self {
1855            Default::default()
1856        }
1857
1858        fn add_summary(&mut self, other: &Self) {
1859            self.count += other.count;
1860            self.sum += other.sum;
1861            self.contains_even |= other.contains_even;
1862            self.max = cmp::max(self.max, other.max);
1863        }
1864    }
1865
1866    impl Dimension<'_, IntegersSummary> for u8 {
1867        fn zero(_cx: ()) -> Self {
1868            Default::default()
1869        }
1870
1871        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1872            *self = summary.max;
1873        }
1874    }
1875
1876    impl Dimension<'_, IntegersSummary> for Count {
1877        fn zero(_cx: ()) -> Self {
1878            Default::default()
1879        }
1880
1881        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1882            self.0 += summary.count;
1883        }
1884    }
1885
1886    impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1887        fn cmp(&self, cursor_location: &IntegersSummary, _: ()) -> Ordering {
1888            self.0.cmp(&cursor_location.count)
1889        }
1890    }
1891
1892    impl Dimension<'_, IntegersSummary> for Sum {
1893        fn zero(_cx: ()) -> Self {
1894            Default::default()
1895        }
1896
1897        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1898            self.0 += summary.sum;
1899        }
1900    }
1901}