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