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