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(&mut self, item: T, cx: &<T::Summary as Summary>::Context) -> bool {
487 let mut replaced = false;
488 *self = {
489 let mut cursor = self.cursor::<T::Key>();
490 let mut new_tree = cursor.slice(&item.key(), Bias::Left, cx);
491 if cursor
492 .item()
493 .map_or(false, |cursor_item| cursor_item.key() == item.key())
494 {
495 cursor.next(cx);
496 replaced = true;
497 }
498 new_tree.push(item, cx);
499 new_tree.push_tree(cursor.suffix(cx), cx);
500 new_tree
501 };
502 replaced
503 }
504
505 pub fn edit(
506 &mut self,
507 mut edits: Vec<Edit<T>>,
508 cx: &<T::Summary as Summary>::Context,
509 ) -> Vec<T> {
510 if edits.is_empty() {
511 return Vec::new();
512 }
513
514 let mut removed = Vec::new();
515 edits.sort_unstable_by_key(|item| item.key());
516
517 *self = {
518 let mut cursor = self.cursor::<T::Key>();
519 let mut new_tree = SumTree::new();
520 let mut buffered_items = Vec::new();
521
522 cursor.seek(&T::Key::default(), Bias::Left, cx);
523 for edit in edits {
524 let new_key = edit.key();
525 let mut old_item = cursor.item();
526
527 if old_item
528 .as_ref()
529 .map_or(false, |old_item| old_item.key() < new_key)
530 {
531 new_tree.extend(buffered_items.drain(..), cx);
532 let slice = cursor.slice(&new_key, Bias::Left, cx);
533 new_tree.push_tree(slice, cx);
534 old_item = cursor.item();
535 }
536
537 if let Some(old_item) = old_item {
538 if old_item.key() == new_key {
539 removed.push(old_item.clone());
540 cursor.next(cx);
541 }
542 }
543
544 match edit {
545 Edit::Insert(item) => {
546 buffered_items.push(item);
547 }
548 Edit::Remove(_) => {}
549 }
550 }
551
552 new_tree.extend(buffered_items, cx);
553 new_tree.push_tree(cursor.suffix(cx), cx);
554 new_tree
555 };
556
557 removed
558 }
559
560 pub fn get(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<&T> {
561 let mut cursor = self.cursor::<T::Key>();
562 if cursor.seek(key, Bias::Left, cx) {
563 cursor.item()
564 } else {
565 None
566 }
567 }
568}
569
570impl<T: Item> Default for SumTree<T> {
571 fn default() -> Self {
572 Self::new()
573 }
574}
575
576#[derive(Clone, Debug)]
577pub enum Node<T: Item> {
578 Internal {
579 height: u8,
580 summary: T::Summary,
581 child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
582 child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
583 },
584 Leaf {
585 summary: T::Summary,
586 items: ArrayVec<T, { 2 * TREE_BASE }>,
587 item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
588 },
589}
590
591impl<T: Item> Node<T> {
592 fn is_leaf(&self) -> bool {
593 match self {
594 Node::Leaf { .. } => true,
595 _ => false,
596 }
597 }
598
599 fn height(&self) -> u8 {
600 match self {
601 Node::Internal { height, .. } => *height,
602 Node::Leaf { .. } => 0,
603 }
604 }
605
606 fn summary(&self) -> &T::Summary {
607 match self {
608 Node::Internal { summary, .. } => summary,
609 Node::Leaf { summary, .. } => summary,
610 }
611 }
612
613 fn child_summaries(&self) -> &[T::Summary] {
614 match self {
615 Node::Internal {
616 child_summaries, ..
617 } => child_summaries.as_slice(),
618 Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
619 }
620 }
621
622 fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
623 match self {
624 Node::Internal { child_trees, .. } => child_trees,
625 Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
626 }
627 }
628
629 fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
630 match self {
631 Node::Leaf { items, .. } => items,
632 Node::Internal { .. } => panic!("Internal nodes have no items"),
633 }
634 }
635
636 fn is_underflowing(&self) -> bool {
637 match self {
638 Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
639 Node::Leaf { items, .. } => items.len() < TREE_BASE,
640 }
641 }
642}
643
644#[derive(Debug)]
645pub enum Edit<T: KeyedItem> {
646 Insert(T),
647 Remove(T::Key),
648}
649
650impl<T: KeyedItem> Edit<T> {
651 fn key(&self) -> T::Key {
652 match self {
653 Edit::Insert(item) => item.key(),
654 Edit::Remove(key) => key.clone(),
655 }
656 }
657}
658
659fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
660where
661 T: 'a + Summary,
662 I: Iterator<Item = &'a T>,
663{
664 let mut sum = T::default();
665 for value in iter {
666 sum.add_summary(value, cx);
667 }
668 sum
669}
670
671#[cfg(test)]
672mod tests {
673 use super::*;
674 use rand::{distributions, prelude::*};
675 use std::cmp;
676
677 #[ctor::ctor]
678 fn init_logger() {
679 if std::env::var("RUST_LOG").is_ok() {
680 env_logger::init();
681 }
682 }
683
684 #[test]
685 fn test_extend_and_push_tree() {
686 let mut tree1 = SumTree::new();
687 tree1.extend(0..20, &());
688
689 let mut tree2 = SumTree::new();
690 tree2.extend(50..100, &());
691
692 tree1.push_tree(tree2, &());
693 assert_eq!(
694 tree1.items(&()),
695 (0..20).chain(50..100).collect::<Vec<u8>>()
696 );
697 }
698
699 #[test]
700 fn test_random() {
701 let mut starting_seed = 0;
702 if let Ok(value) = std::env::var("SEED") {
703 starting_seed = value.parse().expect("invalid SEED variable");
704 }
705 let mut num_iterations = 100;
706 if let Ok(value) = std::env::var("ITERATIONS") {
707 num_iterations = value.parse().expect("invalid ITERATIONS variable");
708 }
709 let num_operations = std::env::var("OPERATIONS")
710 .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
711
712 for seed in starting_seed..(starting_seed + num_iterations) {
713 dbg!(seed);
714 let mut rng = StdRng::seed_from_u64(seed);
715
716 let rng = &mut rng;
717 let mut tree = SumTree::<u8>::new();
718 let count = rng.gen_range(0..10);
719 tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
720
721 for _ in 0..num_operations {
722 let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
723 let splice_start = rng.gen_range(0..splice_end + 1);
724 let count = rng.gen_range(0..3);
725 let tree_end = tree.extent::<Count>(&());
726 let new_items = rng
727 .sample_iter(distributions::Standard)
728 .take(count)
729 .collect::<Vec<u8>>();
730
731 let mut reference_items = tree.items(&());
732 reference_items.splice(splice_start..splice_end, new_items.clone());
733
734 tree = {
735 let mut cursor = tree.cursor::<Count>();
736 let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
737 new_tree.extend(new_items, &());
738 cursor.seek(&Count(splice_end), Bias::Right, &());
739 new_tree.push_tree(cursor.slice(&tree_end, Bias::Right, &()), &());
740 new_tree
741 };
742
743 assert_eq!(tree.items(&()), reference_items);
744 assert_eq!(
745 tree.iter().collect::<Vec<_>>(),
746 tree.cursor::<()>().collect::<Vec<_>>()
747 );
748
749 log::info!("tree items: {:?}", tree.items(&()));
750
751 let mut filter_cursor = tree.filter::<_, Count>(|summary| summary.contains_even);
752 let expected_filtered_items = tree
753 .items(&())
754 .into_iter()
755 .enumerate()
756 .filter(|(_, item)| (item & 1) == 0)
757 .collect::<Vec<_>>();
758
759 let mut item_ix = if rng.gen() {
760 filter_cursor.next(&());
761 0
762 } else {
763 filter_cursor.prev(&());
764 expected_filtered_items.len().saturating_sub(1)
765 };
766 while item_ix < expected_filtered_items.len() {
767 log::info!("filter_cursor, item_ix: {}", item_ix);
768 let actual_item = filter_cursor.item().unwrap();
769 let (reference_index, reference_item) =
770 expected_filtered_items[item_ix].clone();
771 assert_eq!(actual_item, &reference_item);
772 assert_eq!(filter_cursor.start().0, reference_index);
773 log::info!("next");
774 filter_cursor.next(&());
775 item_ix += 1;
776
777 while item_ix > 0 && rng.gen_bool(0.2) {
778 log::info!("prev");
779 filter_cursor.prev(&());
780 item_ix -= 1;
781
782 if item_ix == 0 && rng.gen_bool(0.2) {
783 filter_cursor.prev(&());
784 assert_eq!(filter_cursor.item(), None);
785 assert_eq!(filter_cursor.start().0, 0);
786 filter_cursor.next(&());
787 }
788 }
789 }
790 assert_eq!(filter_cursor.item(), None);
791
792 let mut pos = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
793 let mut before_start = false;
794 let mut cursor = tree.cursor::<Count>();
795 cursor.seek(&Count(pos), Bias::Right, &());
796
797 for i in 0..10 {
798 assert_eq!(cursor.start().0, pos);
799
800 if pos > 0 {
801 assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
802 } else {
803 assert_eq!(cursor.prev_item(), None);
804 }
805
806 if pos < reference_items.len() && !before_start {
807 assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
808 } else {
809 assert_eq!(cursor.item(), None);
810 }
811
812 if i < 5 {
813 cursor.next(&());
814 if pos < reference_items.len() {
815 pos += 1;
816 before_start = false;
817 }
818 } else {
819 cursor.prev(&());
820 if pos == 0 {
821 before_start = true;
822 }
823 pos = pos.saturating_sub(1);
824 }
825 }
826 }
827
828 for _ in 0..10 {
829 let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
830 let start = rng.gen_range(0..end + 1);
831 let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
832 let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
833
834 let mut cursor = tree.cursor::<Count>();
835 cursor.seek(&Count(start), start_bias, &());
836 let slice = cursor.slice(&Count(end), end_bias, &());
837
838 cursor.seek(&Count(start), start_bias, &());
839 let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
840
841 assert_eq!(summary.0, slice.summary().sum);
842 }
843 }
844 }
845
846 #[test]
847 fn test_cursor() {
848 // Empty tree
849 let tree = SumTree::<u8>::new();
850 let mut cursor = tree.cursor::<IntegersSummary>();
851 assert_eq!(
852 cursor.slice(&Count(0), Bias::Right, &()).items(&()),
853 Vec::<u8>::new()
854 );
855 assert_eq!(cursor.item(), None);
856 assert_eq!(cursor.prev_item(), None);
857 assert_eq!(cursor.start().sum, 0);
858 cursor.prev(&());
859 assert_eq!(cursor.item(), None);
860 assert_eq!(cursor.prev_item(), None);
861 assert_eq!(cursor.start().sum, 0);
862 cursor.next(&());
863 assert_eq!(cursor.item(), None);
864 assert_eq!(cursor.prev_item(), None);
865 assert_eq!(cursor.start().sum, 0);
866
867 // Single-element tree
868 let mut tree = SumTree::<u8>::new();
869 tree.extend(vec![1], &());
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(), Some(&1));
876 assert_eq!(cursor.prev_item(), None);
877 assert_eq!(cursor.start().sum, 0);
878
879 cursor.next(&());
880 assert_eq!(cursor.item(), None);
881 assert_eq!(cursor.prev_item(), Some(&1));
882 assert_eq!(cursor.start().sum, 1);
883
884 cursor.prev(&());
885 assert_eq!(cursor.item(), Some(&1));
886 assert_eq!(cursor.prev_item(), None);
887 assert_eq!(cursor.start().sum, 0);
888
889 let mut cursor = tree.cursor::<IntegersSummary>();
890 assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
891 assert_eq!(cursor.item(), None);
892 assert_eq!(cursor.prev_item(), Some(&1));
893 assert_eq!(cursor.start().sum, 1);
894
895 cursor.seek(&Count(0), Bias::Right, &());
896 assert_eq!(
897 cursor
898 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
899 .items(&()),
900 [1]
901 );
902 assert_eq!(cursor.item(), None);
903 assert_eq!(cursor.prev_item(), Some(&1));
904 assert_eq!(cursor.start().sum, 1);
905
906 // Multiple-element tree
907 let mut tree = SumTree::new();
908 tree.extend(vec![1, 2, 3, 4, 5, 6], &());
909 let mut cursor = tree.cursor::<IntegersSummary>();
910
911 assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
912 assert_eq!(cursor.item(), Some(&3));
913 assert_eq!(cursor.prev_item(), Some(&2));
914 assert_eq!(cursor.start().sum, 3);
915
916 cursor.next(&());
917 assert_eq!(cursor.item(), Some(&4));
918 assert_eq!(cursor.prev_item(), Some(&3));
919 assert_eq!(cursor.start().sum, 6);
920
921 cursor.next(&());
922 assert_eq!(cursor.item(), Some(&5));
923 assert_eq!(cursor.prev_item(), Some(&4));
924 assert_eq!(cursor.start().sum, 10);
925
926 cursor.next(&());
927 assert_eq!(cursor.item(), Some(&6));
928 assert_eq!(cursor.prev_item(), Some(&5));
929 assert_eq!(cursor.start().sum, 15);
930
931 cursor.next(&());
932 cursor.next(&());
933 assert_eq!(cursor.item(), None);
934 assert_eq!(cursor.prev_item(), Some(&6));
935 assert_eq!(cursor.start().sum, 21);
936
937 cursor.prev(&());
938 assert_eq!(cursor.item(), Some(&6));
939 assert_eq!(cursor.prev_item(), Some(&5));
940 assert_eq!(cursor.start().sum, 15);
941
942 cursor.prev(&());
943 assert_eq!(cursor.item(), Some(&5));
944 assert_eq!(cursor.prev_item(), Some(&4));
945 assert_eq!(cursor.start().sum, 10);
946
947 cursor.prev(&());
948 assert_eq!(cursor.item(), Some(&4));
949 assert_eq!(cursor.prev_item(), Some(&3));
950 assert_eq!(cursor.start().sum, 6);
951
952 cursor.prev(&());
953 assert_eq!(cursor.item(), Some(&3));
954 assert_eq!(cursor.prev_item(), Some(&2));
955 assert_eq!(cursor.start().sum, 3);
956
957 cursor.prev(&());
958 assert_eq!(cursor.item(), Some(&2));
959 assert_eq!(cursor.prev_item(), Some(&1));
960 assert_eq!(cursor.start().sum, 1);
961
962 cursor.prev(&());
963 assert_eq!(cursor.item(), Some(&1));
964 assert_eq!(cursor.prev_item(), None);
965 assert_eq!(cursor.start().sum, 0);
966
967 cursor.prev(&());
968 assert_eq!(cursor.item(), None);
969 assert_eq!(cursor.prev_item(), None);
970 assert_eq!(cursor.start().sum, 0);
971
972 cursor.next(&());
973 assert_eq!(cursor.item(), Some(&1));
974 assert_eq!(cursor.prev_item(), None);
975 assert_eq!(cursor.start().sum, 0);
976
977 let mut cursor = tree.cursor::<IntegersSummary>();
978 assert_eq!(
979 cursor
980 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
981 .items(&()),
982 tree.items(&())
983 );
984 assert_eq!(cursor.item(), None);
985 assert_eq!(cursor.prev_item(), Some(&6));
986 assert_eq!(cursor.start().sum, 21);
987
988 cursor.seek(&Count(3), Bias::Right, &());
989 assert_eq!(
990 cursor
991 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
992 .items(&()),
993 [4, 5, 6]
994 );
995 assert_eq!(cursor.item(), None);
996 assert_eq!(cursor.prev_item(), Some(&6));
997 assert_eq!(cursor.start().sum, 21);
998
999 // Seeking can bias left or right
1000 cursor.seek(&Count(1), Bias::Left, &());
1001 assert_eq!(cursor.item(), Some(&1));
1002 cursor.seek(&Count(1), Bias::Right, &());
1003 assert_eq!(cursor.item(), Some(&2));
1004
1005 // Slicing without resetting starts from where the cursor is parked at.
1006 cursor.seek(&Count(1), Bias::Right, &());
1007 assert_eq!(
1008 cursor.slice(&Count(3), Bias::Right, &()).items(&()),
1009 vec![2, 3]
1010 );
1011 assert_eq!(
1012 cursor.slice(&Count(6), Bias::Left, &()).items(&()),
1013 vec![4, 5]
1014 );
1015 assert_eq!(
1016 cursor.slice(&Count(6), Bias::Right, &()).items(&()),
1017 vec![6]
1018 );
1019 }
1020
1021 #[test]
1022 fn test_edit() {
1023 let mut tree = SumTree::<u8>::new();
1024
1025 let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1026 assert_eq!(tree.items(&()), vec![0, 1, 2]);
1027 assert_eq!(removed, Vec::<u8>::new());
1028 assert_eq!(tree.get(&0, &()), Some(&0));
1029 assert_eq!(tree.get(&1, &()), Some(&1));
1030 assert_eq!(tree.get(&2, &()), Some(&2));
1031 assert_eq!(tree.get(&4, &()), None);
1032
1033 let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1034 assert_eq!(tree.items(&()), vec![1, 2, 4]);
1035 assert_eq!(removed, vec![0, 2]);
1036 assert_eq!(tree.get(&0, &()), None);
1037 assert_eq!(tree.get(&1, &()), Some(&1));
1038 assert_eq!(tree.get(&2, &()), Some(&2));
1039 assert_eq!(tree.get(&4, &()), Some(&4));
1040 }
1041
1042 #[derive(Clone, Default, Debug)]
1043 pub struct IntegersSummary {
1044 count: usize,
1045 sum: usize,
1046 contains_even: bool,
1047 max: u8,
1048 }
1049
1050 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1051 struct Count(usize);
1052
1053 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1054 struct Sum(usize);
1055
1056 impl Item for u8 {
1057 type Summary = IntegersSummary;
1058
1059 fn summary(&self) -> Self::Summary {
1060 IntegersSummary {
1061 count: 1,
1062 sum: *self as usize,
1063 contains_even: (*self & 1) == 0,
1064 max: *self,
1065 }
1066 }
1067 }
1068
1069 impl KeyedItem for u8 {
1070 type Key = u8;
1071
1072 fn key(&self) -> Self::Key {
1073 *self
1074 }
1075 }
1076
1077 impl Summary for IntegersSummary {
1078 type Context = ();
1079
1080 fn add_summary(&mut self, other: &Self, _: &()) {
1081 self.count += other.count;
1082 self.sum += other.sum;
1083 self.contains_even |= other.contains_even;
1084 self.max = cmp::max(self.max, other.max);
1085 }
1086 }
1087
1088 impl<'a> Dimension<'a, IntegersSummary> for u8 {
1089 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1090 *self = summary.max;
1091 }
1092 }
1093
1094 impl<'a> Dimension<'a, IntegersSummary> for Count {
1095 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1096 self.0 += summary.count;
1097 }
1098 }
1099
1100 impl<'a> SeekTarget<'a, IntegersSummary, IntegersSummary> for Count {
1101 fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1102 self.0.cmp(&cursor_location.count)
1103 }
1104 }
1105
1106 impl<'a> Dimension<'a, IntegersSummary> for Sum {
1107 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1108 self.0 += summary.sum;
1109 }
1110 }
1111}