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