sum_tree.rs

  1mod cursor;
  2
  3use arrayvec::ArrayVec;
  4pub use cursor::Cursor;
  5pub use cursor::FilterCursor;
  6use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
  7
  8#[cfg(test)]
  9const TREE_BASE: usize = 2;
 10#[cfg(not(test))]
 11const TREE_BASE: usize = 6;
 12
 13pub trait Item: Clone + fmt::Debug {
 14    type Summary: Summary;
 15
 16    fn summary(&self) -> Self::Summary;
 17}
 18
 19pub trait KeyedItem: Item {
 20    type Key: for<'a> Dimension<'a, Self::Summary> + Ord;
 21
 22    fn key(&self) -> Self::Key;
 23}
 24
 25pub trait Summary: Default + Clone + fmt::Debug {
 26    type Context;
 27
 28    fn add_summary(&mut self, summary: &Self, cx: &Self::Context);
 29}
 30
 31pub trait Dimension<'a, S: Summary>: Clone + fmt::Debug + Default {
 32    fn add_summary(&mut self, _summary: &'a S, _: &S::Context);
 33}
 34
 35impl<'a, T: Summary> Dimension<'a, T> for () {
 36    fn add_summary(&mut self, _: &'a T, _: &T::Context) {}
 37}
 38
 39pub trait SeekDimension<'a, T: Summary>: Dimension<'a, T> {
 40    fn cmp(&self, other: &Self, cx: &T::Context) -> Ordering;
 41}
 42
 43impl<'a, S: Summary, T: Dimension<'a, S> + Ord> SeekDimension<'a, S> for T {
 44    fn cmp(&self, other: &Self, _ctx: &S::Context) -> Ordering {
 45        Ord::cmp(self, other)
 46    }
 47}
 48
 49#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
 50pub enum Bias {
 51    Left,
 52    Right,
 53}
 54
 55impl PartialOrd for Bias {
 56    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 57        Some(self.cmp(other))
 58    }
 59}
 60
 61impl Ord for Bias {
 62    fn cmp(&self, other: &Self) -> Ordering {
 63        match (self, other) {
 64            (Self::Left, Self::Left) => Ordering::Equal,
 65            (Self::Left, Self::Right) => Ordering::Less,
 66            (Self::Right, Self::Right) => Ordering::Equal,
 67            (Self::Right, Self::Left) => Ordering::Greater,
 68        }
 69    }
 70}
 71
 72#[derive(Debug, Clone)]
 73pub struct SumTree<T: Item>(Arc<Node<T>>);
 74
 75impl<T: Item> SumTree<T> {
 76    pub fn new() -> Self {
 77        SumTree(Arc::new(Node::Leaf {
 78            summary: T::Summary::default(),
 79            items: ArrayVec::new(),
 80            item_summaries: ArrayVec::new(),
 81        }))
 82    }
 83
 84    pub fn from_item(item: T, cx: &<T::Summary as Summary>::Context) -> Self {
 85        let mut tree = Self::new();
 86        tree.push(item, cx);
 87        tree
 88    }
 89
 90    #[allow(unused)]
 91    pub fn items(&self, cx: &<T::Summary as Summary>::Context) -> Vec<T> {
 92        let mut items = Vec::new();
 93        let mut cursor = self.cursor::<(), ()>();
 94        cursor.next(cx);
 95        while let Some(item) = cursor.item() {
 96            items.push(item.clone());
 97            cursor.next(cx);
 98        }
 99        items
100    }
101
102    pub fn cursor<'a, S, U>(&'a self) -> Cursor<T, S, U>
103    where
104        S: Dimension<'a, T::Summary>,
105        U: Dimension<'a, T::Summary>,
106    {
107        Cursor::new(self)
108    }
109
110    pub fn filter<'a, F, U>(
111        &'a self,
112        filter_node: F,
113        cx: &<T::Summary as Summary>::Context,
114    ) -> FilterCursor<F, T, U>
115    where
116        F: Fn(&T::Summary) -> bool,
117        U: Dimension<'a, T::Summary>,
118    {
119        FilterCursor::new(self, filter_node, cx)
120    }
121
122    #[allow(dead_code)]
123    pub fn first(&self) -> Option<&T> {
124        self.leftmost_leaf().0.items().first()
125    }
126
127    pub fn last(&self) -> Option<&T> {
128        self.rightmost_leaf().0.items().last()
129    }
130
131    pub fn update_last(&mut self, f: impl FnOnce(&mut T), cx: &<T::Summary as Summary>::Context) {
132        self.update_last_recursive(f, cx);
133    }
134
135    fn update_last_recursive(
136        &mut self,
137        f: impl FnOnce(&mut T),
138        cx: &<T::Summary as Summary>::Context,
139    ) -> Option<T::Summary> {
140        match Arc::make_mut(&mut self.0) {
141            Node::Internal {
142                summary,
143                child_summaries,
144                child_trees,
145                ..
146            } => {
147                let last_summary = child_summaries.last_mut().unwrap();
148                let last_child = child_trees.last_mut().unwrap();
149                *last_summary = last_child.update_last_recursive(f, cx).unwrap();
150                *summary = sum(child_summaries.iter(), cx);
151                Some(summary.clone())
152            }
153            Node::Leaf {
154                summary,
155                items,
156                item_summaries,
157            } => {
158                if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
159                {
160                    (f)(item);
161                    *item_summary = item.summary();
162                    *summary = sum(item_summaries.iter(), cx);
163                    Some(summary.clone())
164                } else {
165                    None
166                }
167            }
168        }
169    }
170
171    pub fn extent<'a, D: Dimension<'a, T::Summary>>(
172        &'a self,
173        cx: &<T::Summary as Summary>::Context,
174    ) -> D {
175        let mut extent = D::default();
176        match self.0.as_ref() {
177            Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
178                extent.add_summary(summary, cx);
179            }
180        }
181        extent
182    }
183
184    pub fn summary(&self) -> T::Summary {
185        match self.0.as_ref() {
186            Node::Internal { summary, .. } => summary.clone(),
187            Node::Leaf { summary, .. } => summary.clone(),
188        }
189    }
190
191    pub fn is_empty(&self) -> bool {
192        match self.0.as_ref() {
193            Node::Internal { .. } => false,
194            Node::Leaf { items, .. } => items.is_empty(),
195        }
196    }
197
198    pub fn extend<I>(&mut self, iter: I, cx: &<T::Summary as Summary>::Context)
199    where
200        I: IntoIterator<Item = T>,
201    {
202        let mut leaf: Option<Node<T>> = None;
203
204        for item in iter {
205            if leaf.is_some() && leaf.as_ref().unwrap().items().len() == 2 * TREE_BASE {
206                self.push_tree(SumTree(Arc::new(leaf.take().unwrap())), cx);
207            }
208
209            if leaf.is_none() {
210                leaf = Some(Node::Leaf::<T> {
211                    summary: T::Summary::default(),
212                    items: ArrayVec::new(),
213                    item_summaries: ArrayVec::new(),
214                });
215            }
216
217            if let Some(Node::Leaf {
218                summary,
219                items,
220                item_summaries,
221            }) = leaf.as_mut()
222            {
223                let item_summary = item.summary();
224                summary.add_summary(&item_summary, cx);
225                items.push(item);
226                item_summaries.push(item_summary);
227            } else {
228                unreachable!()
229            }
230        }
231
232        if leaf.is_some() {
233            self.push_tree(SumTree(Arc::new(leaf.take().unwrap())), cx);
234        }
235    }
236
237    pub fn push(&mut self, item: T, cx: &<T::Summary as Summary>::Context) {
238        let summary = item.summary();
239        self.push_tree(
240            SumTree(Arc::new(Node::Leaf {
241                summary: summary.clone(),
242                items: ArrayVec::from_iter(Some(item)),
243                item_summaries: ArrayVec::from_iter(Some(summary)),
244            })),
245            cx,
246        );
247    }
248
249    pub fn push_tree(&mut self, other: Self, cx: &<T::Summary as Summary>::Context) {
250        if !other.0.is_leaf() || other.0.items().len() > 0 {
251            if self.0.height() < other.0.height() {
252                for tree in other.0.child_trees() {
253                    self.push_tree(tree.clone(), cx);
254                }
255            } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
256                *self = Self::from_child_trees(self.clone(), split_tree, cx);
257            }
258        }
259    }
260
261    fn push_tree_recursive(
262        &mut self,
263        other: SumTree<T>,
264        cx: &<T::Summary as Summary>::Context,
265    ) -> Option<SumTree<T>> {
266        match Arc::make_mut(&mut self.0) {
267            Node::Internal {
268                height,
269                summary,
270                child_summaries,
271                child_trees,
272                ..
273            } => {
274                let other_node = other.0.clone();
275                summary.add_summary(other_node.summary(), cx);
276
277                let height_delta = *height - other_node.height();
278                let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
279                let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
280                if height_delta == 0 {
281                    summaries_to_append.extend(other_node.child_summaries().iter().cloned());
282                    trees_to_append.extend(other_node.child_trees().iter().cloned());
283                } else if height_delta == 1 && !other_node.is_underflowing() {
284                    summaries_to_append.push(other_node.summary().clone());
285                    trees_to_append.push(other)
286                } else {
287                    let tree_to_append = child_trees
288                        .last_mut()
289                        .unwrap()
290                        .push_tree_recursive(other, cx);
291                    *child_summaries.last_mut().unwrap() =
292                        child_trees.last().unwrap().0.summary().clone();
293
294                    if let Some(split_tree) = tree_to_append {
295                        summaries_to_append.push(split_tree.0.summary().clone());
296                        trees_to_append.push(split_tree);
297                    }
298                }
299
300                let child_count = child_trees.len() + trees_to_append.len();
301                if child_count > 2 * TREE_BASE {
302                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
303                    let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
304                    let left_trees;
305                    let right_trees;
306
307                    let midpoint = (child_count + child_count % 2) / 2;
308                    {
309                        let mut all_summaries = child_summaries
310                            .iter()
311                            .chain(summaries_to_append.iter())
312                            .cloned();
313                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
314                        right_summaries = all_summaries.collect();
315                        let mut all_trees =
316                            child_trees.iter().chain(trees_to_append.iter()).cloned();
317                        left_trees = all_trees.by_ref().take(midpoint).collect();
318                        right_trees = all_trees.collect();
319                    }
320                    *summary = sum(left_summaries.iter(), cx);
321                    *child_summaries = left_summaries;
322                    *child_trees = left_trees;
323
324                    Some(SumTree(Arc::new(Node::Internal {
325                        height: *height,
326                        summary: sum(right_summaries.iter(), cx),
327                        child_summaries: right_summaries,
328                        child_trees: right_trees,
329                    })))
330                } else {
331                    child_summaries.extend(summaries_to_append);
332                    child_trees.extend(trees_to_append);
333                    None
334                }
335            }
336            Node::Leaf {
337                summary,
338                items,
339                item_summaries,
340            } => {
341                let other_node = other.0;
342
343                let child_count = items.len() + other_node.items().len();
344                if child_count > 2 * TREE_BASE {
345                    let left_items;
346                    let right_items;
347                    let left_summaries;
348                    let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
349
350                    let midpoint = (child_count + child_count % 2) / 2;
351                    {
352                        let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
353                        left_items = all_items.by_ref().take(midpoint).collect();
354                        right_items = all_items.collect();
355
356                        let mut all_summaries = item_summaries
357                            .iter()
358                            .chain(other_node.child_summaries())
359                            .cloned();
360                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
361                        right_summaries = all_summaries.collect();
362                    }
363                    *items = left_items;
364                    *item_summaries = left_summaries;
365                    *summary = sum(item_summaries.iter(), cx);
366                    Some(SumTree(Arc::new(Node::Leaf {
367                        items: right_items,
368                        summary: sum(right_summaries.iter(), cx),
369                        item_summaries: right_summaries,
370                    })))
371                } else {
372                    summary.add_summary(other_node.summary(), cx);
373                    items.extend(other_node.items().iter().cloned());
374                    item_summaries.extend(other_node.child_summaries().iter().cloned());
375                    None
376                }
377            }
378        }
379    }
380
381    fn from_child_trees(
382        left: SumTree<T>,
383        right: SumTree<T>,
384        cx: &<T::Summary as Summary>::Context,
385    ) -> Self {
386        let height = left.0.height() + 1;
387        let mut child_summaries = ArrayVec::new();
388        child_summaries.push(left.0.summary().clone());
389        child_summaries.push(right.0.summary().clone());
390        let mut child_trees = ArrayVec::new();
391        child_trees.push(left);
392        child_trees.push(right);
393        SumTree(Arc::new(Node::Internal {
394            height,
395            summary: sum(child_summaries.iter(), cx),
396            child_summaries,
397            child_trees,
398        }))
399    }
400
401    fn leftmost_leaf(&self) -> &Self {
402        match *self.0 {
403            Node::Leaf { .. } => self,
404            Node::Internal {
405                ref child_trees, ..
406            } => child_trees.first().unwrap().leftmost_leaf(),
407        }
408    }
409
410    fn rightmost_leaf(&self) -> &Self {
411        match *self.0 {
412            Node::Leaf { .. } => self,
413            Node::Internal {
414                ref child_trees, ..
415            } => child_trees.last().unwrap().rightmost_leaf(),
416        }
417    }
418}
419
420impl<T: KeyedItem> SumTree<T> {
421    pub fn insert_or_replace(&mut self, item: T, cx: &<T::Summary as Summary>::Context) -> bool {
422        let mut replaced = false;
423        *self = {
424            let mut cursor = self.cursor::<T::Key, ()>();
425            let mut new_tree = cursor.slice(&item.key(), Bias::Left, cx);
426            if cursor
427                .item()
428                .map_or(false, |cursor_item| cursor_item.key() == item.key())
429            {
430                cursor.next(cx);
431                replaced = true;
432            }
433            new_tree.push(item, cx);
434            new_tree.push_tree(cursor.suffix(cx), cx);
435            new_tree
436        };
437        replaced
438    }
439
440    pub fn edit(
441        &mut self,
442        mut edits: Vec<Edit<T>>,
443        cx: &<T::Summary as Summary>::Context,
444    ) -> Vec<T> {
445        if edits.is_empty() {
446            return Vec::new();
447        }
448
449        let mut removed = Vec::new();
450        edits.sort_unstable_by_key(|item| item.key());
451
452        *self = {
453            let mut cursor = self.cursor::<T::Key, ()>();
454            let mut new_tree = SumTree::new();
455            let mut buffered_items = Vec::new();
456
457            cursor.seek(&T::Key::default(), Bias::Left, cx);
458            for edit in edits {
459                let new_key = edit.key();
460                let mut old_item = cursor.item();
461
462                if old_item
463                    .as_ref()
464                    .map_or(false, |old_item| old_item.key() < new_key)
465                {
466                    new_tree.extend(buffered_items.drain(..), cx);
467                    let slice = cursor.slice(&new_key, Bias::Left, cx);
468                    new_tree.push_tree(slice, cx);
469                    old_item = cursor.item();
470                }
471
472                if let Some(old_item) = old_item {
473                    if old_item.key() == new_key {
474                        removed.push(old_item.clone());
475                        cursor.next(cx);
476                    }
477                }
478
479                match edit {
480                    Edit::Insert(item) => {
481                        buffered_items.push(item);
482                    }
483                    Edit::Remove(_) => {}
484                }
485            }
486
487            new_tree.extend(buffered_items, cx);
488            new_tree.push_tree(cursor.suffix(cx), cx);
489            new_tree
490        };
491
492        removed
493    }
494
495    pub fn get(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<&T> {
496        let mut cursor = self.cursor::<T::Key, ()>();
497        if cursor.seek(key, Bias::Left, cx) {
498            cursor.item()
499        } else {
500            None
501        }
502    }
503}
504
505impl<T: Item> Default for SumTree<T> {
506    fn default() -> Self {
507        Self::new()
508    }
509}
510
511#[derive(Clone, Debug)]
512pub enum Node<T: Item> {
513    Internal {
514        height: u8,
515        summary: T::Summary,
516        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
517        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
518    },
519    Leaf {
520        summary: T::Summary,
521        items: ArrayVec<T, { 2 * TREE_BASE }>,
522        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
523    },
524}
525
526impl<T: Item> Node<T> {
527    fn is_leaf(&self) -> bool {
528        match self {
529            Node::Leaf { .. } => true,
530            _ => false,
531        }
532    }
533
534    fn height(&self) -> u8 {
535        match self {
536            Node::Internal { height, .. } => *height,
537            Node::Leaf { .. } => 0,
538        }
539    }
540
541    fn summary(&self) -> &T::Summary {
542        match self {
543            Node::Internal { summary, .. } => summary,
544            Node::Leaf { summary, .. } => summary,
545        }
546    }
547
548    fn child_summaries(&self) -> &[T::Summary] {
549        match self {
550            Node::Internal {
551                child_summaries, ..
552            } => child_summaries.as_slice(),
553            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
554        }
555    }
556
557    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
558        match self {
559            Node::Internal { child_trees, .. } => child_trees,
560            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
561        }
562    }
563
564    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
565        match self {
566            Node::Leaf { items, .. } => items,
567            Node::Internal { .. } => panic!("Internal nodes have no items"),
568        }
569    }
570
571    fn is_underflowing(&self) -> bool {
572        match self {
573            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
574            Node::Leaf { items, .. } => items.len() < TREE_BASE,
575        }
576    }
577}
578
579#[derive(Debug)]
580pub enum Edit<T: KeyedItem> {
581    Insert(T),
582    Remove(T::Key),
583}
584
585impl<T: KeyedItem> Edit<T> {
586    fn key(&self) -> T::Key {
587        match self {
588            Edit::Insert(item) => item.key(),
589            Edit::Remove(key) => key.clone(),
590        }
591    }
592}
593
594fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
595where
596    T: 'a + Summary,
597    I: Iterator<Item = &'a T>,
598{
599    let mut sum = T::default();
600    for value in iter {
601        sum.add_summary(value, cx);
602    }
603    sum
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use rand::{distributions, prelude::*};
610    use std::cmp;
611    use std::ops::Add;
612
613    #[test]
614    fn test_extend_and_push_tree() {
615        let mut tree1 = SumTree::new();
616        tree1.extend(0..20, &());
617
618        let mut tree2 = SumTree::new();
619        tree2.extend(50..100, &());
620
621        tree1.push_tree(tree2, &());
622        assert_eq!(
623            tree1.items(&()),
624            (0..20).chain(50..100).collect::<Vec<u8>>()
625        );
626    }
627
628    #[crate::test(self, iterations = 100)]
629    fn test_random(mut rng: StdRng) {
630        let rng = &mut rng;
631        let mut tree = SumTree::<u8>::new();
632        let count = rng.gen_range(0..10);
633        tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
634
635        for _ in 0..5 {
636            let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
637            let splice_start = rng.gen_range(0..splice_end + 1);
638            let count = rng.gen_range(0..3);
639            let tree_end = tree.extent::<Count>(&());
640            let new_items = rng
641                .sample_iter(distributions::Standard)
642                .take(count)
643                .collect::<Vec<u8>>();
644
645            let mut reference_items = tree.items(&());
646            reference_items.splice(splice_start..splice_end, new_items.clone());
647
648            tree = {
649                let mut cursor = tree.cursor::<Count, ()>();
650                let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
651                new_tree.extend(new_items, &());
652                cursor.seek(&Count(splice_end), Bias::Right, &());
653                new_tree.push_tree(cursor.slice(&tree_end, Bias::Right, &()), &());
654                new_tree
655            };
656
657            assert_eq!(tree.items(&()), reference_items);
658
659            let mut filter_cursor = tree.filter::<_, Count>(|summary| summary.contains_even, &());
660            let mut reference_filter = tree
661                .items(&())
662                .into_iter()
663                .enumerate()
664                .filter(|(_, item)| (item & 1) == 0);
665            while let Some(actual_item) = filter_cursor.item() {
666                let (reference_index, reference_item) = reference_filter.next().unwrap();
667                assert_eq!(actual_item, &reference_item);
668                assert_eq!(filter_cursor.start().0, reference_index);
669                filter_cursor.next(&());
670            }
671            assert!(reference_filter.next().is_none());
672
673            let mut pos = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
674            let mut before_start = false;
675            let mut cursor = tree.cursor::<Count, Count>();
676            cursor.seek(&Count(pos), Bias::Right, &());
677
678            for i in 0..10 {
679                assert_eq!(cursor.sum_start().0, pos);
680
681                if pos > 0 {
682                    assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
683                } else {
684                    assert_eq!(cursor.prev_item(), None);
685                }
686
687                if pos < reference_items.len() && !before_start {
688                    assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
689                } else {
690                    assert_eq!(cursor.item(), None);
691                }
692
693                if i < 5 {
694                    cursor.next(&());
695                    if pos < reference_items.len() {
696                        pos += 1;
697                        before_start = false;
698                    }
699                } else {
700                    cursor.prev(&());
701                    if pos == 0 {
702                        before_start = true;
703                    }
704                    pos = pos.saturating_sub(1);
705                }
706            }
707        }
708
709        for _ in 0..10 {
710            let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
711            let start = rng.gen_range(0..end + 1);
712            let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
713            let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
714
715            let mut cursor = tree.cursor::<Count, ()>();
716            cursor.seek(&Count(start), start_bias, &());
717            let slice = cursor.slice(&Count(end), end_bias, &());
718
719            cursor.seek(&Count(start), start_bias, &());
720            let summary = cursor.summary::<Sum>(&Count(end), end_bias, &());
721
722            assert_eq!(summary, slice.summary().sum);
723        }
724    }
725
726    #[test]
727    fn test_cursor() {
728        // Empty tree
729        let tree = SumTree::<u8>::new();
730        let mut cursor = tree.cursor::<Count, Sum>();
731        assert_eq!(
732            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
733            Vec::<u8>::new()
734        );
735        assert_eq!(cursor.item(), None);
736        assert_eq!(cursor.prev_item(), None);
737        assert_eq!(cursor.sum_start(), &Sum(0));
738
739        // Single-element tree
740        let mut tree = SumTree::<u8>::new();
741        tree.extend(vec![1], &());
742        let mut cursor = tree.cursor::<Count, Sum>();
743        assert_eq!(
744            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
745            Vec::<u8>::new()
746        );
747        assert_eq!(cursor.item(), Some(&1));
748        assert_eq!(cursor.prev_item(), None);
749        assert_eq!(cursor.sum_start(), &Sum(0));
750
751        cursor.next(&());
752        assert_eq!(cursor.item(), None);
753        assert_eq!(cursor.prev_item(), Some(&1));
754        assert_eq!(cursor.sum_start(), &Sum(1));
755
756        cursor.prev(&());
757        assert_eq!(cursor.item(), Some(&1));
758        assert_eq!(cursor.prev_item(), None);
759        assert_eq!(cursor.sum_start(), &Sum(0));
760
761        let mut cursor = tree.cursor::<Count, Sum>();
762        assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
763        assert_eq!(cursor.item(), None);
764        assert_eq!(cursor.prev_item(), Some(&1));
765        assert_eq!(cursor.sum_start(), &Sum(1));
766
767        cursor.seek(&Count(0), Bias::Right, &());
768        assert_eq!(
769            cursor
770                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
771                .items(&()),
772            [1]
773        );
774        assert_eq!(cursor.item(), None);
775        assert_eq!(cursor.prev_item(), Some(&1));
776        assert_eq!(cursor.sum_start(), &Sum(1));
777
778        // Multiple-element tree
779        let mut tree = SumTree::new();
780        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
781        let mut cursor = tree.cursor::<Count, Sum>();
782
783        assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
784        assert_eq!(cursor.item(), Some(&3));
785        assert_eq!(cursor.prev_item(), Some(&2));
786        assert_eq!(cursor.sum_start(), &Sum(3));
787
788        cursor.next(&());
789        assert_eq!(cursor.item(), Some(&4));
790        assert_eq!(cursor.prev_item(), Some(&3));
791        assert_eq!(cursor.sum_start(), &Sum(6));
792
793        cursor.next(&());
794        assert_eq!(cursor.item(), Some(&5));
795        assert_eq!(cursor.prev_item(), Some(&4));
796        assert_eq!(cursor.sum_start(), &Sum(10));
797
798        cursor.next(&());
799        assert_eq!(cursor.item(), Some(&6));
800        assert_eq!(cursor.prev_item(), Some(&5));
801        assert_eq!(cursor.sum_start(), &Sum(15));
802
803        cursor.next(&());
804        cursor.next(&());
805        assert_eq!(cursor.item(), None);
806        assert_eq!(cursor.prev_item(), Some(&6));
807        assert_eq!(cursor.sum_start(), &Sum(21));
808
809        cursor.prev(&());
810        assert_eq!(cursor.item(), Some(&6));
811        assert_eq!(cursor.prev_item(), Some(&5));
812        assert_eq!(cursor.sum_start(), &Sum(15));
813
814        cursor.prev(&());
815        assert_eq!(cursor.item(), Some(&5));
816        assert_eq!(cursor.prev_item(), Some(&4));
817        assert_eq!(cursor.sum_start(), &Sum(10));
818
819        cursor.prev(&());
820        assert_eq!(cursor.item(), Some(&4));
821        assert_eq!(cursor.prev_item(), Some(&3));
822        assert_eq!(cursor.sum_start(), &Sum(6));
823
824        cursor.prev(&());
825        assert_eq!(cursor.item(), Some(&3));
826        assert_eq!(cursor.prev_item(), Some(&2));
827        assert_eq!(cursor.sum_start(), &Sum(3));
828
829        cursor.prev(&());
830        assert_eq!(cursor.item(), Some(&2));
831        assert_eq!(cursor.prev_item(), Some(&1));
832        assert_eq!(cursor.sum_start(), &Sum(1));
833
834        cursor.prev(&());
835        assert_eq!(cursor.item(), Some(&1));
836        assert_eq!(cursor.prev_item(), None);
837        assert_eq!(cursor.sum_start(), &Sum(0));
838
839        cursor.prev(&());
840        assert_eq!(cursor.item(), None);
841        assert_eq!(cursor.prev_item(), None);
842        assert_eq!(cursor.sum_start(), &Sum(0));
843
844        cursor.next(&());
845        assert_eq!(cursor.item(), Some(&1));
846        assert_eq!(cursor.prev_item(), None);
847        assert_eq!(cursor.sum_start(), &Sum(0));
848
849        let mut cursor = tree.cursor::<Count, Sum>();
850        assert_eq!(
851            cursor
852                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
853                .items(&()),
854            tree.items(&())
855        );
856        assert_eq!(cursor.item(), None);
857        assert_eq!(cursor.prev_item(), Some(&6));
858        assert_eq!(cursor.sum_start(), &Sum(21));
859
860        cursor.seek(&Count(3), Bias::Right, &());
861        assert_eq!(
862            cursor
863                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
864                .items(&()),
865            [4, 5, 6]
866        );
867        assert_eq!(cursor.item(), None);
868        assert_eq!(cursor.prev_item(), Some(&6));
869        assert_eq!(cursor.sum_start(), &Sum(21));
870
871        // Seeking can bias left or right
872        cursor.seek(&Count(1), Bias::Left, &());
873        assert_eq!(cursor.item(), Some(&1));
874        cursor.seek(&Count(1), Bias::Right, &());
875        assert_eq!(cursor.item(), Some(&2));
876
877        // Slicing without resetting starts from where the cursor is parked at.
878        cursor.seek(&Count(1), Bias::Right, &());
879        assert_eq!(
880            cursor.slice(&Count(3), Bias::Right, &()).items(&()),
881            vec![2, 3]
882        );
883        assert_eq!(
884            cursor.slice(&Count(6), Bias::Left, &()).items(&()),
885            vec![4, 5]
886        );
887        assert_eq!(
888            cursor.slice(&Count(6), Bias::Right, &()).items(&()),
889            vec![6]
890        );
891    }
892
893    #[test]
894    fn test_edit() {
895        let mut tree = SumTree::<u8>::new();
896
897        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
898        assert_eq!(tree.items(&()), vec![0, 1, 2]);
899        assert_eq!(removed, Vec::<u8>::new());
900        assert_eq!(tree.get(&0, &()), Some(&0));
901        assert_eq!(tree.get(&1, &()), Some(&1));
902        assert_eq!(tree.get(&2, &()), Some(&2));
903        assert_eq!(tree.get(&4, &()), None);
904
905        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
906        assert_eq!(tree.items(&()), vec![1, 2, 4]);
907        assert_eq!(removed, vec![0, 2]);
908        assert_eq!(tree.get(&0, &()), None);
909        assert_eq!(tree.get(&1, &()), Some(&1));
910        assert_eq!(tree.get(&2, &()), Some(&2));
911        assert_eq!(tree.get(&4, &()), Some(&4));
912    }
913
914    #[derive(Clone, Default, Debug)]
915    pub struct IntegersSummary {
916        count: Count,
917        sum: Sum,
918        contains_even: bool,
919        max: u8,
920    }
921
922    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
923    struct Count(usize);
924
925    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
926    struct Sum(usize);
927
928    impl Item for u8 {
929        type Summary = IntegersSummary;
930
931        fn summary(&self) -> Self::Summary {
932            IntegersSummary {
933                count: Count(1),
934                sum: Sum(*self as usize),
935                contains_even: (*self & 1) == 0,
936                max: *self,
937            }
938        }
939    }
940
941    impl KeyedItem for u8 {
942        type Key = u8;
943
944        fn key(&self) -> Self::Key {
945            *self
946        }
947    }
948
949    impl Summary for IntegersSummary {
950        type Context = ();
951
952        fn add_summary(&mut self, other: &Self, _: &()) {
953            self.count.0 += &other.count.0;
954            self.sum.0 += &other.sum.0;
955            self.contains_even |= other.contains_even;
956            self.max = cmp::max(self.max, other.max);
957        }
958    }
959
960    impl<'a> Dimension<'a, IntegersSummary> for u8 {
961        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
962            *self = summary.max;
963        }
964    }
965
966    impl<'a> Dimension<'a, IntegersSummary> for Count {
967        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
968            self.0 += summary.count.0;
969        }
970    }
971
972    impl<'a> Dimension<'a, IntegersSummary> for Sum {
973        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
974            self.0 += summary.sum.0;
975        }
976    }
977
978    impl<'a> Add<&'a Self> for Sum {
979        type Output = Self;
980
981        fn add(mut self, other: &Self) -> Self {
982            self.0 += other.0;
983            self
984        }
985    }
986}