sum_tree.rs

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