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::{MapSeekTarget, TreeMap, TreeSet};
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, PartialOrd, Ord, Debug, Hash, Default)]
99pub enum Bias {
100 #[default]
101 Left,
102 Right,
103}
104
105impl Bias {
106 pub fn invert(self) -> Self {
107 match self {
108 Self::Left => Self::Right,
109 Self::Right => Self::Left,
110 }
111 }
112}
113
114#[derive(Debug, Clone)]
115pub struct SumTree<T: Item>(Arc<Node<T>>);
116
117impl<T: Item> SumTree<T> {
118 pub fn new() -> Self {
119 SumTree(Arc::new(Node::Leaf {
120 summary: T::Summary::default(),
121 items: ArrayVec::new(),
122 item_summaries: ArrayVec::new(),
123 }))
124 }
125
126 pub fn from_item(item: T, cx: &<T::Summary as Summary>::Context) -> Self {
127 let mut tree = Self::new();
128 tree.push(item, cx);
129 tree
130 }
131
132 pub fn from_iter<I: IntoIterator<Item = T>>(
133 iter: I,
134 cx: &<T::Summary as Summary>::Context,
135 ) -> Self {
136 let mut tree = Self::new();
137 tree.extend(iter, cx);
138 tree
139 }
140
141 #[allow(unused)]
142 pub fn items(&self, cx: &<T::Summary as Summary>::Context) -> Vec<T> {
143 let mut items = Vec::new();
144 let mut cursor = self.cursor::<()>();
145 cursor.next(cx);
146 while let Some(item) = cursor.item() {
147 items.push(item.clone());
148 cursor.next(cx);
149 }
150 items
151 }
152
153 pub fn iter(&self) -> Iter<T> {
154 Iter::new(self)
155 }
156
157 pub fn cursor<'a, S>(&'a self) -> Cursor<T, S>
158 where
159 S: Dimension<'a, T::Summary>,
160 {
161 Cursor::new(self)
162 }
163
164 /// Note: If the summary type requires a non `()` context, then the filter cursor
165 /// that is returned cannot be used with Rust's iterators.
166 pub fn filter<'a, F, U>(&'a self, filter_node: F) -> FilterCursor<F, T, U>
167 where
168 F: FnMut(&T::Summary) -> bool,
169 U: Dimension<'a, T::Summary>,
170 {
171 FilterCursor::new(self, filter_node)
172 }
173
174 #[allow(dead_code)]
175 pub fn first(&self) -> Option<&T> {
176 self.leftmost_leaf().0.items().first()
177 }
178
179 pub fn last(&self) -> Option<&T> {
180 self.rightmost_leaf().0.items().last()
181 }
182
183 pub fn update_last(&mut self, f: impl FnOnce(&mut T), cx: &<T::Summary as Summary>::Context) {
184 self.update_last_recursive(f, cx);
185 }
186
187 fn update_last_recursive(
188 &mut self,
189 f: impl FnOnce(&mut T),
190 cx: &<T::Summary as Summary>::Context,
191 ) -> Option<T::Summary> {
192 match Arc::make_mut(&mut self.0) {
193 Node::Internal {
194 summary,
195 child_summaries,
196 child_trees,
197 ..
198 } => {
199 let last_summary = child_summaries.last_mut().unwrap();
200 let last_child = child_trees.last_mut().unwrap();
201 *last_summary = last_child.update_last_recursive(f, cx).unwrap();
202 *summary = sum(child_summaries.iter(), cx);
203 Some(summary.clone())
204 }
205 Node::Leaf {
206 summary,
207 items,
208 item_summaries,
209 } => {
210 if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
211 {
212 (f)(item);
213 *item_summary = item.summary();
214 *summary = sum(item_summaries.iter(), cx);
215 Some(summary.clone())
216 } else {
217 None
218 }
219 }
220 }
221 }
222
223 pub fn extent<'a, D: Dimension<'a, T::Summary>>(
224 &'a self,
225 cx: &<T::Summary as Summary>::Context,
226 ) -> D {
227 let mut extent = D::default();
228 match self.0.as_ref() {
229 Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
230 extent.add_summary(summary, cx);
231 }
232 }
233 extent
234 }
235
236 pub fn summary(&self) -> &T::Summary {
237 match self.0.as_ref() {
238 Node::Internal { summary, .. } => summary,
239 Node::Leaf { summary, .. } => summary,
240 }
241 }
242
243 pub fn is_empty(&self) -> bool {
244 match self.0.as_ref() {
245 Node::Internal { .. } => false,
246 Node::Leaf { items, .. } => items.is_empty(),
247 }
248 }
249
250 pub fn extend<I>(&mut self, iter: I, cx: &<T::Summary as Summary>::Context)
251 where
252 I: IntoIterator<Item = T>,
253 {
254 let mut leaf: Option<Node<T>> = None;
255
256 for item in iter {
257 if leaf.is_some() && leaf.as_ref().unwrap().items().len() == 2 * TREE_BASE {
258 self.append(SumTree(Arc::new(leaf.take().unwrap())), cx);
259 }
260
261 if leaf.is_none() {
262 leaf = Some(Node::Leaf::<T> {
263 summary: T::Summary::default(),
264 items: ArrayVec::new(),
265 item_summaries: ArrayVec::new(),
266 });
267 }
268
269 if let Some(Node::Leaf {
270 summary,
271 items,
272 item_summaries,
273 }) = leaf.as_mut()
274 {
275 let item_summary = item.summary();
276 <T::Summary as Summary>::add_summary(summary, &item_summary, cx);
277 items.push(item);
278 item_summaries.push(item_summary);
279 } else {
280 unreachable!()
281 }
282 }
283
284 if leaf.is_some() {
285 self.append(SumTree(Arc::new(leaf.take().unwrap())), cx);
286 }
287 }
288
289 pub fn push(&mut self, item: T, cx: &<T::Summary as Summary>::Context) {
290 let summary = item.summary();
291 self.append(
292 SumTree(Arc::new(Node::Leaf {
293 summary: summary.clone(),
294 items: ArrayVec::from_iter(Some(item)),
295 item_summaries: ArrayVec::from_iter(Some(summary)),
296 })),
297 cx,
298 );
299 }
300
301 pub fn append(&mut self, other: Self, cx: &<T::Summary as Summary>::Context) {
302 if !other.0.is_leaf() || !other.0.items().is_empty() {
303 if self.0.height() < other.0.height() {
304 for tree in other.0.child_trees() {
305 self.append(tree.clone(), cx);
306 }
307 } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
308 *self = Self::from_child_trees(self.clone(), split_tree, cx);
309 }
310 }
311 }
312
313 fn push_tree_recursive(
314 &mut self,
315 other: SumTree<T>,
316 cx: &<T::Summary as Summary>::Context,
317 ) -> Option<SumTree<T>> {
318 match Arc::make_mut(&mut self.0) {
319 Node::Internal {
320 height,
321 summary,
322 child_summaries,
323 child_trees,
324 ..
325 } => {
326 let other_node = other.0.clone();
327 <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
328
329 let height_delta = *height - other_node.height();
330 let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
331 let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
332 if height_delta == 0 {
333 summaries_to_append.extend(other_node.child_summaries().iter().cloned());
334 trees_to_append.extend(other_node.child_trees().iter().cloned());
335 } else if height_delta == 1 && !other_node.is_underflowing() {
336 summaries_to_append.push(other_node.summary().clone());
337 trees_to_append.push(other)
338 } else {
339 let tree_to_append = child_trees
340 .last_mut()
341 .unwrap()
342 .push_tree_recursive(other, cx);
343 *child_summaries.last_mut().unwrap() =
344 child_trees.last().unwrap().0.summary().clone();
345
346 if let Some(split_tree) = tree_to_append {
347 summaries_to_append.push(split_tree.0.summary().clone());
348 trees_to_append.push(split_tree);
349 }
350 }
351
352 let child_count = child_trees.len() + trees_to_append.len();
353 if child_count > 2 * TREE_BASE {
354 let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
355 let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
356 let left_trees;
357 let right_trees;
358
359 let midpoint = (child_count + child_count % 2) / 2;
360 {
361 let mut all_summaries = child_summaries
362 .iter()
363 .chain(summaries_to_append.iter())
364 .cloned();
365 left_summaries = all_summaries.by_ref().take(midpoint).collect();
366 right_summaries = all_summaries.collect();
367 let mut all_trees =
368 child_trees.iter().chain(trees_to_append.iter()).cloned();
369 left_trees = all_trees.by_ref().take(midpoint).collect();
370 right_trees = all_trees.collect();
371 }
372 *summary = sum(left_summaries.iter(), cx);
373 *child_summaries = left_summaries;
374 *child_trees = left_trees;
375
376 Some(SumTree(Arc::new(Node::Internal {
377 height: *height,
378 summary: sum(right_summaries.iter(), cx),
379 child_summaries: right_summaries,
380 child_trees: right_trees,
381 })))
382 } else {
383 child_summaries.extend(summaries_to_append);
384 child_trees.extend(trees_to_append);
385 None
386 }
387 }
388 Node::Leaf {
389 summary,
390 items,
391 item_summaries,
392 } => {
393 let other_node = other.0;
394
395 let child_count = items.len() + other_node.items().len();
396 if child_count > 2 * TREE_BASE {
397 let left_items;
398 let right_items;
399 let left_summaries;
400 let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
401
402 let midpoint = (child_count + child_count % 2) / 2;
403 {
404 let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
405 left_items = all_items.by_ref().take(midpoint).collect();
406 right_items = all_items.collect();
407
408 let mut all_summaries = item_summaries
409 .iter()
410 .chain(other_node.child_summaries())
411 .cloned();
412 left_summaries = all_summaries.by_ref().take(midpoint).collect();
413 right_summaries = all_summaries.collect();
414 }
415 *items = left_items;
416 *item_summaries = left_summaries;
417 *summary = sum(item_summaries.iter(), cx);
418 Some(SumTree(Arc::new(Node::Leaf {
419 items: right_items,
420 summary: sum(right_summaries.iter(), cx),
421 item_summaries: right_summaries,
422 })))
423 } else {
424 <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
425 items.extend(other_node.items().iter().cloned());
426 item_summaries.extend(other_node.child_summaries().iter().cloned());
427 None
428 }
429 }
430 }
431 }
432
433 fn from_child_trees(
434 left: SumTree<T>,
435 right: SumTree<T>,
436 cx: &<T::Summary as Summary>::Context,
437 ) -> Self {
438 let height = left.0.height() + 1;
439 let mut child_summaries = ArrayVec::new();
440 child_summaries.push(left.0.summary().clone());
441 child_summaries.push(right.0.summary().clone());
442 let mut child_trees = ArrayVec::new();
443 child_trees.push(left);
444 child_trees.push(right);
445 SumTree(Arc::new(Node::Internal {
446 height,
447 summary: sum(child_summaries.iter(), cx),
448 child_summaries,
449 child_trees,
450 }))
451 }
452
453 fn leftmost_leaf(&self) -> &Self {
454 match *self.0 {
455 Node::Leaf { .. } => self,
456 Node::Internal {
457 ref child_trees, ..
458 } => child_trees.first().unwrap().leftmost_leaf(),
459 }
460 }
461
462 fn rightmost_leaf(&self) -> &Self {
463 match *self.0 {
464 Node::Leaf { .. } => self,
465 Node::Internal {
466 ref child_trees, ..
467 } => child_trees.last().unwrap().rightmost_leaf(),
468 }
469 }
470
471 #[cfg(debug_assertions)]
472 pub fn _debug_entries(&self) -> Vec<&T> {
473 self.iter().collect::<Vec<_>>()
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.append(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.append(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.append(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.append(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 matches!(self, Node::Leaf { .. })
614 }
615
616 fn height(&self) -> u8 {
617 match self {
618 Node::Internal { height, .. } => *height,
619 Node::Leaf { .. } => 0,
620 }
621 }
622
623 fn summary(&self) -> &T::Summary {
624 match self {
625 Node::Internal { summary, .. } => summary,
626 Node::Leaf { summary, .. } => summary,
627 }
628 }
629
630 fn child_summaries(&self) -> &[T::Summary] {
631 match self {
632 Node::Internal {
633 child_summaries, ..
634 } => child_summaries.as_slice(),
635 Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
636 }
637 }
638
639 fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
640 match self {
641 Node::Internal { child_trees, .. } => child_trees,
642 Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
643 }
644 }
645
646 fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
647 match self {
648 Node::Leaf { items, .. } => items,
649 Node::Internal { .. } => panic!("Internal nodes have no items"),
650 }
651 }
652
653 fn is_underflowing(&self) -> bool {
654 match self {
655 Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
656 Node::Leaf { items, .. } => items.len() < TREE_BASE,
657 }
658 }
659}
660
661#[derive(Debug)]
662pub enum Edit<T: KeyedItem> {
663 Insert(T),
664 Remove(T::Key),
665}
666
667impl<T: KeyedItem> Edit<T> {
668 fn key(&self) -> T::Key {
669 match self {
670 Edit::Insert(item) => item.key(),
671 Edit::Remove(key) => key.clone(),
672 }
673 }
674}
675
676fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
677where
678 T: 'a + Summary,
679 I: Iterator<Item = &'a T>,
680{
681 let mut sum = T::default();
682 for value in iter {
683 sum.add_summary(value, cx);
684 }
685 sum
686}
687
688#[cfg(test)]
689mod tests {
690 use super::*;
691 use rand::{distributions, prelude::*};
692 use std::cmp;
693
694 #[ctor::ctor]
695 fn init_logger() {
696 if std::env::var("RUST_LOG").is_ok() {
697 env_logger::init();
698 }
699 }
700
701 #[test]
702 fn test_extend_and_push_tree() {
703 let mut tree1 = SumTree::new();
704 tree1.extend(0..20, &());
705
706 let mut tree2 = SumTree::new();
707 tree2.extend(50..100, &());
708
709 tree1.append(tree2, &());
710 assert_eq!(
711 tree1.items(&()),
712 (0..20).chain(50..100).collect::<Vec<u8>>()
713 );
714 }
715
716 #[test]
717 fn test_random() {
718 let mut starting_seed = 0;
719 if let Ok(value) = std::env::var("SEED") {
720 starting_seed = value.parse().expect("invalid SEED variable");
721 }
722 let mut num_iterations = 100;
723 if let Ok(value) = std::env::var("ITERATIONS") {
724 num_iterations = value.parse().expect("invalid ITERATIONS variable");
725 }
726 let num_operations = std::env::var("OPERATIONS")
727 .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
728
729 for seed in starting_seed..(starting_seed + num_iterations) {
730 eprintln!("seed = {}", seed);
731 let mut rng = StdRng::seed_from_u64(seed);
732
733 let rng = &mut rng;
734 let mut tree = SumTree::<u8>::new();
735 let count = rng.gen_range(0..10);
736 tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
737
738 for _ in 0..num_operations {
739 let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
740 let splice_start = rng.gen_range(0..splice_end + 1);
741 let count = rng.gen_range(0..10);
742 let tree_end = tree.extent::<Count>(&());
743 let new_items = rng
744 .sample_iter(distributions::Standard)
745 .take(count)
746 .collect::<Vec<u8>>();
747
748 let mut reference_items = tree.items(&());
749 reference_items.splice(splice_start..splice_end, new_items.clone());
750
751 tree = {
752 let mut cursor = tree.cursor::<Count>();
753 let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
754 new_tree.extend(new_items, &());
755 cursor.seek(&Count(splice_end), Bias::Right, &());
756 new_tree.append(cursor.slice(&tree_end, Bias::Right, &()), &());
757 new_tree
758 };
759
760 assert_eq!(tree.items(&()), reference_items);
761 assert_eq!(
762 tree.iter().collect::<Vec<_>>(),
763 tree.cursor::<()>().collect::<Vec<_>>()
764 );
765
766 log::info!("tree items: {:?}", tree.items(&()));
767
768 let mut filter_cursor = tree.filter::<_, Count>(|summary| summary.contains_even);
769 let expected_filtered_items = tree
770 .items(&())
771 .into_iter()
772 .enumerate()
773 .filter(|(_, item)| (item & 1) == 0)
774 .collect::<Vec<_>>();
775
776 let mut item_ix = if rng.gen() {
777 filter_cursor.next(&());
778 0
779 } else {
780 filter_cursor.prev(&());
781 expected_filtered_items.len().saturating_sub(1)
782 };
783 while item_ix < expected_filtered_items.len() {
784 log::info!("filter_cursor, item_ix: {}", item_ix);
785 let actual_item = filter_cursor.item().unwrap();
786 let (reference_index, reference_item) = expected_filtered_items[item_ix];
787 assert_eq!(actual_item, &reference_item);
788 assert_eq!(filter_cursor.start().0, reference_index);
789 log::info!("next");
790 filter_cursor.next(&());
791 item_ix += 1;
792
793 while item_ix > 0 && rng.gen_bool(0.2) {
794 log::info!("prev");
795 filter_cursor.prev(&());
796 item_ix -= 1;
797
798 if item_ix == 0 && rng.gen_bool(0.2) {
799 filter_cursor.prev(&());
800 assert_eq!(filter_cursor.item(), None);
801 assert_eq!(filter_cursor.start().0, 0);
802 filter_cursor.next(&());
803 }
804 }
805 }
806 assert_eq!(filter_cursor.item(), None);
807
808 let mut before_start = false;
809 let mut cursor = tree.cursor::<Count>();
810 let start_pos = rng.gen_range(0..=reference_items.len());
811 cursor.seek(&Count(start_pos), Bias::Right, &());
812 let mut pos = rng.gen_range(start_pos..=reference_items.len());
813 cursor.seek_forward(&Count(pos), Bias::Right, &());
814
815 for i in 0..10 {
816 assert_eq!(cursor.start().0, pos);
817
818 if pos > 0 {
819 assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
820 } else {
821 assert_eq!(cursor.prev_item(), None);
822 }
823
824 if pos < reference_items.len() && !before_start {
825 assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
826 } else {
827 assert_eq!(cursor.item(), None);
828 }
829
830 if before_start {
831 assert_eq!(cursor.next_item(), reference_items.get(0));
832 } else if pos + 1 < reference_items.len() {
833 assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
834 } else {
835 assert_eq!(cursor.next_item(), None);
836 }
837
838 if i < 5 {
839 cursor.next(&());
840 if pos < reference_items.len() {
841 pos += 1;
842 before_start = false;
843 }
844 } else {
845 cursor.prev(&());
846 if pos == 0 {
847 before_start = true;
848 }
849 pos = pos.saturating_sub(1);
850 }
851 }
852 }
853
854 for _ in 0..10 {
855 let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
856 let start = rng.gen_range(0..end + 1);
857 let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
858 let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
859
860 let mut cursor = tree.cursor::<Count>();
861 cursor.seek(&Count(start), start_bias, &());
862 let slice = cursor.slice(&Count(end), end_bias, &());
863
864 cursor.seek(&Count(start), start_bias, &());
865 let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
866
867 assert_eq!(summary.0, slice.summary().sum);
868 }
869 }
870 }
871
872 #[test]
873 fn test_cursor() {
874 // Empty tree
875 let tree = SumTree::<u8>::new();
876 let mut cursor = tree.cursor::<IntegersSummary>();
877 assert_eq!(
878 cursor.slice(&Count(0), Bias::Right, &()).items(&()),
879 Vec::<u8>::new()
880 );
881 assert_eq!(cursor.item(), None);
882 assert_eq!(cursor.prev_item(), None);
883 assert_eq!(cursor.next_item(), None);
884 assert_eq!(cursor.start().sum, 0);
885 cursor.prev(&());
886 assert_eq!(cursor.item(), None);
887 assert_eq!(cursor.prev_item(), None);
888 assert_eq!(cursor.next_item(), None);
889 assert_eq!(cursor.start().sum, 0);
890 cursor.next(&());
891 assert_eq!(cursor.item(), None);
892 assert_eq!(cursor.prev_item(), None);
893 assert_eq!(cursor.next_item(), None);
894 assert_eq!(cursor.start().sum, 0);
895
896 // Single-element tree
897 let mut tree = SumTree::<u8>::new();
898 tree.extend(vec![1], &());
899 let mut cursor = tree.cursor::<IntegersSummary>();
900 assert_eq!(
901 cursor.slice(&Count(0), Bias::Right, &()).items(&()),
902 Vec::<u8>::new()
903 );
904 assert_eq!(cursor.item(), Some(&1));
905 assert_eq!(cursor.prev_item(), None);
906 assert_eq!(cursor.next_item(), None);
907 assert_eq!(cursor.start().sum, 0);
908
909 cursor.next(&());
910 assert_eq!(cursor.item(), None);
911 assert_eq!(cursor.prev_item(), Some(&1));
912 assert_eq!(cursor.next_item(), None);
913 assert_eq!(cursor.start().sum, 1);
914
915 cursor.prev(&());
916 assert_eq!(cursor.item(), Some(&1));
917 assert_eq!(cursor.prev_item(), None);
918 assert_eq!(cursor.next_item(), None);
919 assert_eq!(cursor.start().sum, 0);
920
921 let mut cursor = tree.cursor::<IntegersSummary>();
922 assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
923 assert_eq!(cursor.item(), None);
924 assert_eq!(cursor.prev_item(), Some(&1));
925 assert_eq!(cursor.next_item(), None);
926 assert_eq!(cursor.start().sum, 1);
927
928 cursor.seek(&Count(0), Bias::Right, &());
929 assert_eq!(
930 cursor
931 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
932 .items(&()),
933 [1]
934 );
935 assert_eq!(cursor.item(), None);
936 assert_eq!(cursor.prev_item(), Some(&1));
937 assert_eq!(cursor.next_item(), None);
938 assert_eq!(cursor.start().sum, 1);
939
940 // Multiple-element tree
941 let mut tree = SumTree::new();
942 tree.extend(vec![1, 2, 3, 4, 5, 6], &());
943 let mut cursor = tree.cursor::<IntegersSummary>();
944
945 assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
946 assert_eq!(cursor.item(), Some(&3));
947 assert_eq!(cursor.prev_item(), Some(&2));
948 assert_eq!(cursor.next_item(), Some(&4));
949 assert_eq!(cursor.start().sum, 3);
950
951 cursor.next(&());
952 assert_eq!(cursor.item(), Some(&4));
953 assert_eq!(cursor.prev_item(), Some(&3));
954 assert_eq!(cursor.next_item(), Some(&5));
955 assert_eq!(cursor.start().sum, 6);
956
957 cursor.next(&());
958 assert_eq!(cursor.item(), Some(&5));
959 assert_eq!(cursor.prev_item(), Some(&4));
960 assert_eq!(cursor.next_item(), Some(&6));
961 assert_eq!(cursor.start().sum, 10);
962
963 cursor.next(&());
964 assert_eq!(cursor.item(), Some(&6));
965 assert_eq!(cursor.prev_item(), Some(&5));
966 assert_eq!(cursor.next_item(), None);
967 assert_eq!(cursor.start().sum, 15);
968
969 cursor.next(&());
970 cursor.next(&());
971 assert_eq!(cursor.item(), None);
972 assert_eq!(cursor.prev_item(), Some(&6));
973 assert_eq!(cursor.next_item(), None);
974 assert_eq!(cursor.start().sum, 21);
975
976 cursor.prev(&());
977 assert_eq!(cursor.item(), Some(&6));
978 assert_eq!(cursor.prev_item(), Some(&5));
979 assert_eq!(cursor.next_item(), None);
980 assert_eq!(cursor.start().sum, 15);
981
982 cursor.prev(&());
983 assert_eq!(cursor.item(), Some(&5));
984 assert_eq!(cursor.prev_item(), Some(&4));
985 assert_eq!(cursor.next_item(), Some(&6));
986 assert_eq!(cursor.start().sum, 10);
987
988 cursor.prev(&());
989 assert_eq!(cursor.item(), Some(&4));
990 assert_eq!(cursor.prev_item(), Some(&3));
991 assert_eq!(cursor.next_item(), Some(&5));
992 assert_eq!(cursor.start().sum, 6);
993
994 cursor.prev(&());
995 assert_eq!(cursor.item(), Some(&3));
996 assert_eq!(cursor.prev_item(), Some(&2));
997 assert_eq!(cursor.next_item(), Some(&4));
998 assert_eq!(cursor.start().sum, 3);
999
1000 cursor.prev(&());
1001 assert_eq!(cursor.item(), Some(&2));
1002 assert_eq!(cursor.prev_item(), Some(&1));
1003 assert_eq!(cursor.next_item(), Some(&3));
1004 assert_eq!(cursor.start().sum, 1);
1005
1006 cursor.prev(&());
1007 assert_eq!(cursor.item(), Some(&1));
1008 assert_eq!(cursor.prev_item(), None);
1009 assert_eq!(cursor.next_item(), Some(&2));
1010 assert_eq!(cursor.start().sum, 0);
1011
1012 cursor.prev(&());
1013 assert_eq!(cursor.item(), None);
1014 assert_eq!(cursor.prev_item(), None);
1015 assert_eq!(cursor.next_item(), Some(&1));
1016 assert_eq!(cursor.start().sum, 0);
1017
1018 cursor.next(&());
1019 assert_eq!(cursor.item(), Some(&1));
1020 assert_eq!(cursor.prev_item(), None);
1021 assert_eq!(cursor.next_item(), Some(&2));
1022 assert_eq!(cursor.start().sum, 0);
1023
1024 let mut cursor = tree.cursor::<IntegersSummary>();
1025 assert_eq!(
1026 cursor
1027 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
1028 .items(&()),
1029 tree.items(&())
1030 );
1031 assert_eq!(cursor.item(), None);
1032 assert_eq!(cursor.prev_item(), Some(&6));
1033 assert_eq!(cursor.next_item(), None);
1034 assert_eq!(cursor.start().sum, 21);
1035
1036 cursor.seek(&Count(3), Bias::Right, &());
1037 assert_eq!(
1038 cursor
1039 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
1040 .items(&()),
1041 [4, 5, 6]
1042 );
1043 assert_eq!(cursor.item(), None);
1044 assert_eq!(cursor.prev_item(), Some(&6));
1045 assert_eq!(cursor.next_item(), None);
1046 assert_eq!(cursor.start().sum, 21);
1047
1048 // Seeking can bias left or right
1049 cursor.seek(&Count(1), Bias::Left, &());
1050 assert_eq!(cursor.item(), Some(&1));
1051 cursor.seek(&Count(1), Bias::Right, &());
1052 assert_eq!(cursor.item(), Some(&2));
1053
1054 // Slicing without resetting starts from where the cursor is parked at.
1055 cursor.seek(&Count(1), Bias::Right, &());
1056 assert_eq!(
1057 cursor.slice(&Count(3), Bias::Right, &()).items(&()),
1058 vec![2, 3]
1059 );
1060 assert_eq!(
1061 cursor.slice(&Count(6), Bias::Left, &()).items(&()),
1062 vec![4, 5]
1063 );
1064 assert_eq!(
1065 cursor.slice(&Count(6), Bias::Right, &()).items(&()),
1066 vec![6]
1067 );
1068 }
1069
1070 #[test]
1071 fn test_edit() {
1072 let mut tree = SumTree::<u8>::new();
1073
1074 let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1075 assert_eq!(tree.items(&()), vec![0, 1, 2]);
1076 assert_eq!(removed, Vec::<u8>::new());
1077 assert_eq!(tree.get(&0, &()), Some(&0));
1078 assert_eq!(tree.get(&1, &()), Some(&1));
1079 assert_eq!(tree.get(&2, &()), Some(&2));
1080 assert_eq!(tree.get(&4, &()), None);
1081
1082 let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1083 assert_eq!(tree.items(&()), vec![1, 2, 4]);
1084 assert_eq!(removed, vec![0, 2]);
1085 assert_eq!(tree.get(&0, &()), None);
1086 assert_eq!(tree.get(&1, &()), Some(&1));
1087 assert_eq!(tree.get(&2, &()), Some(&2));
1088 assert_eq!(tree.get(&4, &()), Some(&4));
1089 }
1090
1091 #[derive(Clone, Default, Debug)]
1092 pub struct IntegersSummary {
1093 count: usize,
1094 sum: usize,
1095 contains_even: bool,
1096 max: u8,
1097 }
1098
1099 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1100 struct Count(usize);
1101
1102 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1103 struct Sum(usize);
1104
1105 impl Item for u8 {
1106 type Summary = IntegersSummary;
1107
1108 fn summary(&self) -> Self::Summary {
1109 IntegersSummary {
1110 count: 1,
1111 sum: *self as usize,
1112 contains_even: (*self & 1) == 0,
1113 max: *self,
1114 }
1115 }
1116 }
1117
1118 impl KeyedItem for u8 {
1119 type Key = u8;
1120
1121 fn key(&self) -> Self::Key {
1122 *self
1123 }
1124 }
1125
1126 impl Summary for IntegersSummary {
1127 type Context = ();
1128
1129 fn add_summary(&mut self, other: &Self, _: &()) {
1130 self.count += other.count;
1131 self.sum += other.sum;
1132 self.contains_even |= other.contains_even;
1133 self.max = cmp::max(self.max, other.max);
1134 }
1135 }
1136
1137 impl<'a> Dimension<'a, IntegersSummary> for u8 {
1138 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1139 *self = summary.max;
1140 }
1141 }
1142
1143 impl<'a> Dimension<'a, IntegersSummary> for Count {
1144 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1145 self.0 += summary.count;
1146 }
1147 }
1148
1149 impl<'a> SeekTarget<'a, IntegersSummary, IntegersSummary> for Count {
1150 fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1151 self.0.cmp(&cursor_location.count)
1152 }
1153 }
1154
1155 impl<'a> Dimension<'a, IntegersSummary> for Sum {
1156 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1157 self.0 += summary.sum;
1158 }
1159 }
1160}