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