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