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