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 remove(&mut self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<T> {
506 let mut removed = None;
507 *self = {
508 let mut cursor = self.cursor::<T::Key>();
509 let mut new_tree = cursor.slice(key, Bias::Left, cx);
510 if let Some(item) = cursor.item() {
511 if item.key() == *key {
512 removed = Some(item.clone());
513 cursor.next(cx);
514 }
515 }
516 new_tree.push_tree(cursor.suffix(cx), cx);
517 new_tree
518 };
519 removed
520 }
521
522 pub fn edit(
523 &mut self,
524 mut edits: Vec<Edit<T>>,
525 cx: &<T::Summary as Summary>::Context,
526 ) -> Vec<T> {
527 if edits.is_empty() {
528 return Vec::new();
529 }
530
531 let mut removed = Vec::new();
532 edits.sort_unstable_by_key(|item| item.key());
533
534 *self = {
535 let mut cursor = self.cursor::<T::Key>();
536 let mut new_tree = SumTree::new();
537 let mut buffered_items = Vec::new();
538
539 cursor.seek(&T::Key::default(), Bias::Left, cx);
540 for edit in edits {
541 let new_key = edit.key();
542 let mut old_item = cursor.item();
543
544 if old_item
545 .as_ref()
546 .map_or(false, |old_item| old_item.key() < new_key)
547 {
548 new_tree.extend(buffered_items.drain(..), cx);
549 let slice = cursor.slice(&new_key, Bias::Left, cx);
550 new_tree.push_tree(slice, cx);
551 old_item = cursor.item();
552 }
553
554 if let Some(old_item) = old_item {
555 if old_item.key() == new_key {
556 removed.push(old_item.clone());
557 cursor.next(cx);
558 }
559 }
560
561 match edit {
562 Edit::Insert(item) => {
563 buffered_items.push(item);
564 }
565 Edit::Remove(_) => {}
566 }
567 }
568
569 new_tree.extend(buffered_items, cx);
570 new_tree.push_tree(cursor.suffix(cx), cx);
571 new_tree
572 };
573
574 removed
575 }
576
577 pub fn get(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<&T> {
578 let mut cursor = self.cursor::<T::Key>();
579 if cursor.seek(key, Bias::Left, cx) {
580 cursor.item()
581 } else {
582 None
583 }
584 }
585}
586
587impl<T: Item> Default for SumTree<T> {
588 fn default() -> Self {
589 Self::new()
590 }
591}
592
593#[derive(Clone, Debug)]
594pub enum Node<T: Item> {
595 Internal {
596 height: u8,
597 summary: T::Summary,
598 child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
599 child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
600 },
601 Leaf {
602 summary: T::Summary,
603 items: ArrayVec<T, { 2 * TREE_BASE }>,
604 item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
605 },
606}
607
608impl<T: Item> Node<T> {
609 fn is_leaf(&self) -> bool {
610 match self {
611 Node::Leaf { .. } => true,
612 _ => false,
613 }
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.push_tree(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 dbg!(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..3);
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.push_tree(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) =
787 expected_filtered_items[item_ix].clone();
788 assert_eq!(actual_item, &reference_item);
789 assert_eq!(filter_cursor.start().0, reference_index);
790 log::info!("next");
791 filter_cursor.next(&());
792 item_ix += 1;
793
794 while item_ix > 0 && rng.gen_bool(0.2) {
795 log::info!("prev");
796 filter_cursor.prev(&());
797 item_ix -= 1;
798
799 if item_ix == 0 && rng.gen_bool(0.2) {
800 filter_cursor.prev(&());
801 assert_eq!(filter_cursor.item(), None);
802 assert_eq!(filter_cursor.start().0, 0);
803 filter_cursor.next(&());
804 }
805 }
806 }
807 assert_eq!(filter_cursor.item(), None);
808
809 let mut pos = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
810 let mut before_start = false;
811 let mut cursor = tree.cursor::<Count>();
812 cursor.seek(&Count(pos), Bias::Right, &());
813
814 for i in 0..10 {
815 assert_eq!(cursor.start().0, pos);
816
817 if pos > 0 {
818 assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
819 } else {
820 assert_eq!(cursor.prev_item(), None);
821 }
822
823 if pos < reference_items.len() && !before_start {
824 assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
825 } else {
826 assert_eq!(cursor.item(), None);
827 }
828
829 if i < 5 {
830 cursor.next(&());
831 if pos < reference_items.len() {
832 pos += 1;
833 before_start = false;
834 }
835 } else {
836 cursor.prev(&());
837 if pos == 0 {
838 before_start = true;
839 }
840 pos = pos.saturating_sub(1);
841 }
842 }
843 }
844
845 for _ in 0..10 {
846 let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
847 let start = rng.gen_range(0..end + 1);
848 let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
849 let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
850
851 let mut cursor = tree.cursor::<Count>();
852 cursor.seek(&Count(start), start_bias, &());
853 let slice = cursor.slice(&Count(end), end_bias, &());
854
855 cursor.seek(&Count(start), start_bias, &());
856 let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
857
858 assert_eq!(summary.0, slice.summary().sum);
859 }
860 }
861 }
862
863 #[test]
864 fn test_cursor() {
865 // Empty tree
866 let tree = SumTree::<u8>::new();
867 let mut cursor = tree.cursor::<IntegersSummary>();
868 assert_eq!(
869 cursor.slice(&Count(0), Bias::Right, &()).items(&()),
870 Vec::<u8>::new()
871 );
872 assert_eq!(cursor.item(), None);
873 assert_eq!(cursor.prev_item(), None);
874 assert_eq!(cursor.start().sum, 0);
875 cursor.prev(&());
876 assert_eq!(cursor.item(), None);
877 assert_eq!(cursor.prev_item(), None);
878 assert_eq!(cursor.start().sum, 0);
879 cursor.next(&());
880 assert_eq!(cursor.item(), None);
881 assert_eq!(cursor.prev_item(), None);
882 assert_eq!(cursor.start().sum, 0);
883
884 // Single-element tree
885 let mut tree = SumTree::<u8>::new();
886 tree.extend(vec![1], &());
887 let mut cursor = tree.cursor::<IntegersSummary>();
888 assert_eq!(
889 cursor.slice(&Count(0), Bias::Right, &()).items(&()),
890 Vec::<u8>::new()
891 );
892 assert_eq!(cursor.item(), Some(&1));
893 assert_eq!(cursor.prev_item(), None);
894 assert_eq!(cursor.start().sum, 0);
895
896 cursor.next(&());
897 assert_eq!(cursor.item(), None);
898 assert_eq!(cursor.prev_item(), Some(&1));
899 assert_eq!(cursor.start().sum, 1);
900
901 cursor.prev(&());
902 assert_eq!(cursor.item(), Some(&1));
903 assert_eq!(cursor.prev_item(), None);
904 assert_eq!(cursor.start().sum, 0);
905
906 let mut cursor = tree.cursor::<IntegersSummary>();
907 assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
908 assert_eq!(cursor.item(), None);
909 assert_eq!(cursor.prev_item(), Some(&1));
910 assert_eq!(cursor.start().sum, 1);
911
912 cursor.seek(&Count(0), Bias::Right, &());
913 assert_eq!(
914 cursor
915 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
916 .items(&()),
917 [1]
918 );
919 assert_eq!(cursor.item(), None);
920 assert_eq!(cursor.prev_item(), Some(&1));
921 assert_eq!(cursor.start().sum, 1);
922
923 // Multiple-element tree
924 let mut tree = SumTree::new();
925 tree.extend(vec![1, 2, 3, 4, 5, 6], &());
926 let mut cursor = tree.cursor::<IntegersSummary>();
927
928 assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
929 assert_eq!(cursor.item(), Some(&3));
930 assert_eq!(cursor.prev_item(), Some(&2));
931 assert_eq!(cursor.start().sum, 3);
932
933 cursor.next(&());
934 assert_eq!(cursor.item(), Some(&4));
935 assert_eq!(cursor.prev_item(), Some(&3));
936 assert_eq!(cursor.start().sum, 6);
937
938 cursor.next(&());
939 assert_eq!(cursor.item(), Some(&5));
940 assert_eq!(cursor.prev_item(), Some(&4));
941 assert_eq!(cursor.start().sum, 10);
942
943 cursor.next(&());
944 assert_eq!(cursor.item(), Some(&6));
945 assert_eq!(cursor.prev_item(), Some(&5));
946 assert_eq!(cursor.start().sum, 15);
947
948 cursor.next(&());
949 cursor.next(&());
950 assert_eq!(cursor.item(), None);
951 assert_eq!(cursor.prev_item(), Some(&6));
952 assert_eq!(cursor.start().sum, 21);
953
954 cursor.prev(&());
955 assert_eq!(cursor.item(), Some(&6));
956 assert_eq!(cursor.prev_item(), Some(&5));
957 assert_eq!(cursor.start().sum, 15);
958
959 cursor.prev(&());
960 assert_eq!(cursor.item(), Some(&5));
961 assert_eq!(cursor.prev_item(), Some(&4));
962 assert_eq!(cursor.start().sum, 10);
963
964 cursor.prev(&());
965 assert_eq!(cursor.item(), Some(&4));
966 assert_eq!(cursor.prev_item(), Some(&3));
967 assert_eq!(cursor.start().sum, 6);
968
969 cursor.prev(&());
970 assert_eq!(cursor.item(), Some(&3));
971 assert_eq!(cursor.prev_item(), Some(&2));
972 assert_eq!(cursor.start().sum, 3);
973
974 cursor.prev(&());
975 assert_eq!(cursor.item(), Some(&2));
976 assert_eq!(cursor.prev_item(), Some(&1));
977 assert_eq!(cursor.start().sum, 1);
978
979 cursor.prev(&());
980 assert_eq!(cursor.item(), Some(&1));
981 assert_eq!(cursor.prev_item(), None);
982 assert_eq!(cursor.start().sum, 0);
983
984 cursor.prev(&());
985 assert_eq!(cursor.item(), None);
986 assert_eq!(cursor.prev_item(), None);
987 assert_eq!(cursor.start().sum, 0);
988
989 cursor.next(&());
990 assert_eq!(cursor.item(), Some(&1));
991 assert_eq!(cursor.prev_item(), None);
992 assert_eq!(cursor.start().sum, 0);
993
994 let mut cursor = tree.cursor::<IntegersSummary>();
995 assert_eq!(
996 cursor
997 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
998 .items(&()),
999 tree.items(&())
1000 );
1001 assert_eq!(cursor.item(), None);
1002 assert_eq!(cursor.prev_item(), Some(&6));
1003 assert_eq!(cursor.start().sum, 21);
1004
1005 cursor.seek(&Count(3), Bias::Right, &());
1006 assert_eq!(
1007 cursor
1008 .slice(&tree.extent::<Count>(&()), Bias::Right, &())
1009 .items(&()),
1010 [4, 5, 6]
1011 );
1012 assert_eq!(cursor.item(), None);
1013 assert_eq!(cursor.prev_item(), Some(&6));
1014 assert_eq!(cursor.start().sum, 21);
1015
1016 // Seeking can bias left or right
1017 cursor.seek(&Count(1), Bias::Left, &());
1018 assert_eq!(cursor.item(), Some(&1));
1019 cursor.seek(&Count(1), Bias::Right, &());
1020 assert_eq!(cursor.item(), Some(&2));
1021
1022 // Slicing without resetting starts from where the cursor is parked at.
1023 cursor.seek(&Count(1), Bias::Right, &());
1024 assert_eq!(
1025 cursor.slice(&Count(3), Bias::Right, &()).items(&()),
1026 vec![2, 3]
1027 );
1028 assert_eq!(
1029 cursor.slice(&Count(6), Bias::Left, &()).items(&()),
1030 vec![4, 5]
1031 );
1032 assert_eq!(
1033 cursor.slice(&Count(6), Bias::Right, &()).items(&()),
1034 vec![6]
1035 );
1036 }
1037
1038 #[test]
1039 fn test_edit() {
1040 let mut tree = SumTree::<u8>::new();
1041
1042 let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1043 assert_eq!(tree.items(&()), vec![0, 1, 2]);
1044 assert_eq!(removed, Vec::<u8>::new());
1045 assert_eq!(tree.get(&0, &()), Some(&0));
1046 assert_eq!(tree.get(&1, &()), Some(&1));
1047 assert_eq!(tree.get(&2, &()), Some(&2));
1048 assert_eq!(tree.get(&4, &()), None);
1049
1050 let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1051 assert_eq!(tree.items(&()), vec![1, 2, 4]);
1052 assert_eq!(removed, vec![0, 2]);
1053 assert_eq!(tree.get(&0, &()), None);
1054 assert_eq!(tree.get(&1, &()), Some(&1));
1055 assert_eq!(tree.get(&2, &()), Some(&2));
1056 assert_eq!(tree.get(&4, &()), Some(&4));
1057 }
1058
1059 #[derive(Clone, Default, Debug)]
1060 pub struct IntegersSummary {
1061 count: usize,
1062 sum: usize,
1063 contains_even: bool,
1064 max: u8,
1065 }
1066
1067 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1068 struct Count(usize);
1069
1070 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1071 struct Sum(usize);
1072
1073 impl Item for u8 {
1074 type Summary = IntegersSummary;
1075
1076 fn summary(&self) -> Self::Summary {
1077 IntegersSummary {
1078 count: 1,
1079 sum: *self as usize,
1080 contains_even: (*self & 1) == 0,
1081 max: *self,
1082 }
1083 }
1084 }
1085
1086 impl KeyedItem for u8 {
1087 type Key = u8;
1088
1089 fn key(&self) -> Self::Key {
1090 *self
1091 }
1092 }
1093
1094 impl Summary for IntegersSummary {
1095 type Context = ();
1096
1097 fn add_summary(&mut self, other: &Self, _: &()) {
1098 self.count += other.count;
1099 self.sum += other.sum;
1100 self.contains_even |= other.contains_even;
1101 self.max = cmp::max(self.max, other.max);
1102 }
1103 }
1104
1105 impl<'a> Dimension<'a, IntegersSummary> for u8 {
1106 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1107 *self = summary.max;
1108 }
1109 }
1110
1111 impl<'a> Dimension<'a, IntegersSummary> for Count {
1112 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1113 self.0 += summary.count;
1114 }
1115 }
1116
1117 impl<'a> SeekTarget<'a, IntegersSummary, IntegersSummary> for Count {
1118 fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1119 self.0.cmp(&cursor_location.count)
1120 }
1121 }
1122
1123 impl<'a> Dimension<'a, IntegersSummary> for Sum {
1124 fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1125 self.0 += summary.sum;
1126 }
1127 }
1128}