1mod cursor;
2mod tree_map;
3
4use arrayvec::ArrayVec;
5pub use cursor::{Cursor, FilterCursor, Iter};
6use rayon::prelude::*;
7use std::marker::PhantomData;
8use std::mem;
9use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
10pub use tree_map::{MapSeekTarget, TreeMap, TreeSet};
11
12#[cfg(test)]
13pub const TREE_BASE: usize = 2;
14#[cfg(not(test))]
15pub const TREE_BASE: usize = 6;
16
17/// An item that can be stored in a [`SumTree`]
18///
19/// Must be summarized by a type that implements [`Summary`]
20pub trait Item: Clone {
21 type Summary: Summary;
22
23 fn summary(&self, cx: <Self::Summary as Summary>::Context<'_>) -> Self::Summary;
24}
25
26/// An [`Item`] whose summary has a specific key that can be used to identify it
27pub trait KeyedItem: Item {
28 type Key: for<'a> Dimension<'a, Self::Summary> + Ord;
29
30 fn key(&self) -> Self::Key;
31}
32
33/// A type that describes the Sum of all [`Item`]s in a subtree of the [`SumTree`]
34///
35/// Each Summary type can have multiple [`Dimension`]s that it measures,
36/// which can be used to navigate the tree
37pub trait Summary: Clone {
38 type Context<'a>: Copy;
39 fn zero<'a>(cx: Self::Context<'a>) -> Self;
40 fn add_summary<'a>(&mut self, summary: &Self, cx: Self::Context<'a>);
41}
42
43pub trait ContextLessSummary: Clone {
44 fn zero() -> Self;
45 fn add_summary(&mut self, summary: &Self);
46}
47
48impl<T: ContextLessSummary> Summary for T {
49 type Context<'a> = ();
50
51 fn zero<'a>((): ()) -> Self {
52 T::zero()
53 }
54
55 fn add_summary<'a>(&mut self, summary: &Self, (): ()) {
56 T::add_summary(self, summary)
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub struct NoSummary;
62
63/// Catch-all implementation for when you need something that implements [`Summary`] without a specific type.
64/// We implement it on a `NoSummary` instead of re-using `()`, as that avoids blanket impl collisions with `impl<T: Summary> Dimension for T`
65/// (as we also need unit type to be a fill-in dimension)
66impl ContextLessSummary for NoSummary {
67 fn zero() -> Self {
68 NoSummary
69 }
70
71 fn add_summary(&mut self, _: &Self) {}
72}
73
74/// Each [`Summary`] type can have more than one [`Dimension`] type that it measures.
75///
76/// You can use dimensions to seek to a specific location in the [`SumTree`]
77///
78/// # Example:
79/// Zed's rope has a `TextSummary` type that summarizes lines, characters, and bytes.
80/// Each of these are different dimensions we may want to seek to
81pub trait Dimension<'a, S: Summary>: Clone {
82 fn zero(cx: S::Context<'_>) -> Self;
83
84 fn add_summary(&mut self, summary: &'a S, cx: S::Context<'_>);
85 #[must_use]
86 fn with_added_summary(mut self, summary: &'a S, cx: S::Context<'_>) -> Self {
87 self.add_summary(summary, cx);
88 self
89 }
90
91 fn from_summary(summary: &'a S, cx: S::Context<'_>) -> Self {
92 let mut dimension = Self::zero(cx);
93 dimension.add_summary(summary, cx);
94 dimension
95 }
96}
97
98impl<'a, T: Summary> Dimension<'a, T> for T {
99 fn zero(cx: T::Context<'_>) -> Self {
100 Summary::zero(cx)
101 }
102
103 fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) {
104 Summary::add_summary(self, summary, cx);
105 }
106}
107
108pub trait SeekTarget<'a, S: Summary, D: Dimension<'a, S>> {
109 fn cmp(&self, cursor_location: &D, cx: S::Context<'_>) -> Ordering;
110}
111
112impl<'a, S: Summary, D: Dimension<'a, S> + Ord> SeekTarget<'a, S, D> for D {
113 fn cmp(&self, cursor_location: &Self, _: S::Context<'_>) -> Ordering {
114 Ord::cmp(self, cursor_location)
115 }
116}
117
118impl<'a, T: Summary> Dimension<'a, T> for () {
119 fn zero(_: T::Context<'_>) -> Self {}
120
121 fn add_summary(&mut self, _: &'a T, _: T::Context<'_>) {}
122}
123
124#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
125pub struct Dimensions<D1, D2, D3 = ()>(pub D1, pub D2, pub D3);
126
127impl<'a, T: Summary, D1: Dimension<'a, T>, D2: Dimension<'a, T>, D3: Dimension<'a, T>>
128 Dimension<'a, T> for Dimensions<D1, D2, D3>
129{
130 fn zero(cx: T::Context<'_>) -> Self {
131 Dimensions(D1::zero(cx), D2::zero(cx), D3::zero(cx))
132 }
133
134 fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) {
135 self.0.add_summary(summary, cx);
136 self.1.add_summary(summary, cx);
137 self.2.add_summary(summary, cx);
138 }
139}
140
141impl<'a, S, D1, D2, D3> SeekTarget<'a, S, Dimensions<D1, D2, D3>> for D1
142where
143 S: Summary,
144 D1: SeekTarget<'a, S, D1> + Dimension<'a, S>,
145 D2: Dimension<'a, S>,
146 D3: Dimension<'a, S>,
147{
148 fn cmp(&self, cursor_location: &Dimensions<D1, D2, D3>, cx: S::Context<'_>) -> Ordering {
149 self.cmp(&cursor_location.0, cx)
150 }
151}
152
153/// Bias is used to settle ambiguities when determining positions in an ordered sequence.
154///
155/// The primary use case is for text, where Bias influences
156/// which character an offset or anchor is associated with.
157///
158/// # Examples
159/// Given the buffer `AˇBCD`:
160/// - The offset of the cursor is 1
161/// - [Bias::Left] would attach the cursor to the character `A`
162/// - [Bias::Right] would attach the cursor to the character `B`
163///
164/// Given the buffer `A«BCˇ»D`:
165/// - The offset of the cursor is 3, and the selection is from 1 to 3
166/// - The left anchor of the selection has [Bias::Right], attaching it to the character `B`
167/// - The right anchor of the selection has [Bias::Left], attaching it to the character `C`
168///
169/// Given the buffer `{ˇ<...>`, where `<...>` is a folded region:
170/// - The display offset of the cursor is 1, but the offset in the buffer is determined by the bias
171/// - [Bias::Left] would attach the cursor to the character `{`, with a buffer offset of 1
172/// - [Bias::Right] would attach the cursor to the first character of the folded region,
173/// and the buffer offset would be the offset of the first character of the folded region
174#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Default)]
175pub enum Bias {
176 /// Attach to the character on the left
177 #[default]
178 Left,
179 /// Attach to the character on the right
180 Right,
181}
182
183impl Bias {
184 pub fn invert(self) -> Self {
185 match self {
186 Self::Left => Self::Right,
187 Self::Right => Self::Left,
188 }
189 }
190}
191
192/// A B+ tree in which each leaf node contains `Item`s of type `T` and a `Summary`s for each `Item`.
193/// Each internal node contains a `Summary` of the items in its subtree.
194///
195/// The maximum number of items per node is `TREE_BASE * 2`.
196///
197/// Any [`Dimension`] supported by the [`Summary`] type can be used to seek to a specific location in the tree.
198#[derive(Clone)]
199pub struct SumTree<T: Item>(Arc<Node<T>>);
200
201impl<T> fmt::Debug for SumTree<T>
202where
203 T: fmt::Debug + Item,
204 T::Summary: fmt::Debug,
205{
206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 f.debug_tuple("SumTree").field(&self.0).finish()
208 }
209}
210
211impl<T: Item> SumTree<T> {
212 pub fn new(cx: <T::Summary as Summary>::Context<'_>) -> Self {
213 SumTree(Arc::new(Node::Leaf {
214 summary: <T::Summary as Summary>::zero(cx),
215 items: ArrayVec::new(),
216 item_summaries: ArrayVec::new(),
217 }))
218 }
219
220 /// Useful in cases where the item type has a non-trivial context type, but the zero value of the summary type doesn't depend on that context.
221 pub fn from_summary(summary: T::Summary) -> Self {
222 SumTree(Arc::new(Node::Leaf {
223 summary,
224 items: ArrayVec::new(),
225 item_summaries: ArrayVec::new(),
226 }))
227 }
228
229 pub fn from_item(item: T, cx: <T::Summary as Summary>::Context<'_>) -> Self {
230 let mut tree = Self::new(cx);
231 tree.push(item, cx);
232 tree
233 }
234
235 pub fn from_iter<I: IntoIterator<Item = T>>(
236 iter: I,
237 cx: <T::Summary as Summary>::Context<'_>,
238 ) -> Self {
239 let mut nodes = Vec::new();
240
241 let mut iter = iter.into_iter().fuse().peekable();
242 while iter.peek().is_some() {
243 let items: ArrayVec<T, { 2 * TREE_BASE }> = iter.by_ref().take(2 * TREE_BASE).collect();
244 let item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }> =
245 items.iter().map(|item| item.summary(cx)).collect();
246
247 let mut summary = item_summaries[0].clone();
248 for item_summary in &item_summaries[1..] {
249 <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
250 }
251
252 nodes.push(Node::Leaf {
253 summary,
254 items,
255 item_summaries,
256 });
257 }
258
259 let mut parent_nodes = Vec::new();
260 let mut height = 0;
261 while nodes.len() > 1 {
262 height += 1;
263 let mut current_parent_node = None;
264 for child_node in nodes.drain(..) {
265 let parent_node = current_parent_node.get_or_insert_with(|| Node::Internal {
266 summary: <T::Summary as Summary>::zero(cx),
267 height,
268 child_summaries: ArrayVec::new(),
269 child_trees: ArrayVec::new(),
270 });
271 let Node::Internal {
272 summary,
273 child_summaries,
274 child_trees,
275 ..
276 } = parent_node
277 else {
278 unreachable!()
279 };
280 let child_summary = child_node.summary();
281 <T::Summary as Summary>::add_summary(summary, child_summary, cx);
282 child_summaries.push(child_summary.clone());
283 child_trees.push(Self(Arc::new(child_node)));
284
285 if child_trees.len() == 2 * TREE_BASE {
286 parent_nodes.extend(current_parent_node.take());
287 }
288 }
289 parent_nodes.extend(current_parent_node.take());
290 mem::swap(&mut nodes, &mut parent_nodes);
291 }
292
293 if nodes.is_empty() {
294 Self::new(cx)
295 } else {
296 debug_assert_eq!(nodes.len(), 1);
297 Self(Arc::new(nodes.pop().unwrap()))
298 }
299 }
300
301 pub fn from_par_iter<I, Iter>(iter: I, cx: <T::Summary as Summary>::Context<'_>) -> Self
302 where
303 I: IntoParallelIterator<Iter = Iter>,
304 Iter: IndexedParallelIterator<Item = T>,
305 T: Send + Sync,
306 T::Summary: Send + Sync,
307 for<'a> <T::Summary as Summary>::Context<'a>: Sync,
308 {
309 let mut nodes = iter
310 .into_par_iter()
311 .chunks(2 * TREE_BASE)
312 .map(|items| {
313 let items: ArrayVec<T, { 2 * TREE_BASE }> = items.into_iter().collect();
314 let item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }> =
315 items.iter().map(|item| item.summary(cx)).collect();
316 let mut summary = item_summaries[0].clone();
317 for item_summary in &item_summaries[1..] {
318 <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
319 }
320 SumTree(Arc::new(Node::Leaf {
321 summary,
322 items,
323 item_summaries,
324 }))
325 })
326 .collect::<Vec<_>>();
327
328 let mut height = 0;
329 while nodes.len() > 1 {
330 height += 1;
331 nodes = nodes
332 .into_par_iter()
333 .chunks(2 * TREE_BASE)
334 .map(|child_nodes| {
335 let child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }> =
336 child_nodes.into_iter().collect();
337 let child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }> = child_trees
338 .iter()
339 .map(|child_tree| child_tree.summary().clone())
340 .collect();
341 let mut summary = child_summaries[0].clone();
342 for child_summary in &child_summaries[1..] {
343 <T::Summary as Summary>::add_summary(&mut summary, child_summary, cx);
344 }
345 SumTree(Arc::new(Node::Internal {
346 height,
347 summary,
348 child_summaries,
349 child_trees,
350 }))
351 })
352 .collect::<Vec<_>>();
353 }
354
355 if nodes.is_empty() {
356 Self::new(cx)
357 } else {
358 debug_assert_eq!(nodes.len(), 1);
359 nodes.pop().unwrap()
360 }
361 }
362
363 #[allow(unused)]
364 pub fn items<'a>(&'a self, cx: <T::Summary as Summary>::Context<'a>) -> Vec<T> {
365 let mut items = Vec::new();
366 let mut cursor = self.cursor::<()>(cx);
367 cursor.next();
368 while let Some(item) = cursor.item() {
369 items.push(item.clone());
370 cursor.next();
371 }
372 items
373 }
374
375 pub fn iter(&self) -> Iter<'_, T> {
376 Iter::new(self)
377 }
378
379 /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`.
380 ///
381 /// Only returns the item that exactly has the target match.
382 pub fn find_exact<'a, 'slf, D, Target>(
383 &'slf self,
384 cx: <T::Summary as Summary>::Context<'a>,
385 target: &Target,
386 bias: Bias,
387 ) -> (D, D, Option<&'slf T>)
388 where
389 D: Dimension<'slf, T::Summary>,
390 Target: SeekTarget<'slf, T::Summary, D>,
391 {
392 let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
393 let comparison = target.cmp(&tree_end, cx);
394 if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
395 {
396 return (tree_end.clone(), tree_end, None);
397 }
398
399 let mut pos = D::zero(cx);
400 return match Self::find_recurse::<_, _, true>(cx, target, bias, &mut pos, self) {
401 Some((item, end)) => (pos, end, Some(item)),
402 None => (pos.clone(), pos, None),
403 };
404 }
405
406 /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
407 pub fn find<'a, 'slf, D, Target>(
408 &'slf self,
409 cx: <T::Summary as Summary>::Context<'a>,
410 target: &Target,
411 bias: Bias,
412 ) -> (D, D, Option<&'slf T>)
413 where
414 D: Dimension<'slf, T::Summary>,
415 Target: SeekTarget<'slf, T::Summary, D>,
416 {
417 let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
418 let comparison = target.cmp(&tree_end, cx);
419 if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
420 {
421 return (tree_end.clone(), tree_end, None);
422 }
423
424 let mut pos = D::zero(cx);
425 return match Self::find_recurse::<_, _, false>(cx, target, bias, &mut pos, self) {
426 Some((item, end)) => (pos, end, Some(item)),
427 None => (pos.clone(), pos, None),
428 };
429 }
430
431 fn find_recurse<'tree, 'a, D, Target, const EXACT: bool>(
432 cx: <T::Summary as Summary>::Context<'a>,
433 target: &Target,
434 bias: Bias,
435 position: &mut D,
436 this: &'tree SumTree<T>,
437 ) -> Option<(&'tree T, D)>
438 where
439 D: Dimension<'tree, T::Summary>,
440 Target: SeekTarget<'tree, T::Summary, D>,
441 {
442 match &*this.0 {
443 Node::Internal {
444 child_summaries,
445 child_trees,
446 ..
447 } => {
448 for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
449 let child_end = position.clone().with_added_summary(child_summary, cx);
450
451 let comparison = target.cmp(&child_end, cx);
452 let target_in_child = comparison == Ordering::Less
453 || (comparison == Ordering::Equal && bias == Bias::Left);
454 if target_in_child {
455 return Self::find_recurse::<D, Target, EXACT>(
456 cx, target, bias, position, child_tree,
457 );
458 }
459 *position = child_end;
460 }
461 }
462 Node::Leaf {
463 items,
464 item_summaries,
465 ..
466 } => {
467 for (item, item_summary) in items.iter().zip(item_summaries) {
468 let mut child_end = position.clone();
469 child_end.add_summary(item_summary, cx);
470
471 let comparison = target.cmp(&child_end, cx);
472 let entry_found = if EXACT {
473 comparison == Ordering::Equal
474 } else {
475 comparison == Ordering::Less
476 || (comparison == Ordering::Equal && bias == Bias::Left)
477 };
478 if entry_found {
479 return Some((item, child_end));
480 }
481
482 *position = child_end;
483 }
484 }
485 }
486 None
487 }
488
489 pub fn cursor<'a, 'b, D>(
490 &'a self,
491 cx: <T::Summary as Summary>::Context<'b>,
492 ) -> Cursor<'a, 'b, T, D>
493 where
494 D: Dimension<'a, T::Summary>,
495 {
496 Cursor::new(self, cx)
497 }
498
499 /// Note: If the summary type requires a non `()` context, then the filter cursor
500 /// that is returned cannot be used with Rust's iterators.
501 pub fn filter<'a, 'b, F, U>(
502 &'a self,
503 cx: <T::Summary as Summary>::Context<'b>,
504 filter_node: F,
505 ) -> FilterCursor<'a, 'b, F, T, U>
506 where
507 F: FnMut(&T::Summary) -> bool,
508 U: Dimension<'a, T::Summary>,
509 {
510 FilterCursor::new(self, cx, filter_node)
511 }
512
513 #[allow(dead_code)]
514 pub fn first(&self) -> Option<&T> {
515 self.leftmost_leaf().0.items().first()
516 }
517
518 pub fn last(&self) -> Option<&T> {
519 self.rightmost_leaf().0.items().last()
520 }
521
522 pub fn update_last(
523 &mut self,
524 f: impl FnOnce(&mut T),
525 cx: <T::Summary as Summary>::Context<'_>,
526 ) {
527 self.update_last_recursive(f, cx);
528 }
529
530 fn update_last_recursive(
531 &mut self,
532 f: impl FnOnce(&mut T),
533 cx: <T::Summary as Summary>::Context<'_>,
534 ) -> Option<T::Summary> {
535 match Arc::make_mut(&mut self.0) {
536 Node::Internal {
537 summary,
538 child_summaries,
539 child_trees,
540 ..
541 } => {
542 let last_summary = child_summaries.last_mut().unwrap();
543 let last_child = child_trees.last_mut().unwrap();
544 *last_summary = last_child.update_last_recursive(f, cx).unwrap();
545 *summary = sum(child_summaries.iter(), cx);
546 Some(summary.clone())
547 }
548 Node::Leaf {
549 summary,
550 items,
551 item_summaries,
552 } => {
553 if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
554 {
555 (f)(item);
556 *item_summary = item.summary(cx);
557 *summary = sum(item_summaries.iter(), cx);
558 Some(summary.clone())
559 } else {
560 None
561 }
562 }
563 }
564 }
565
566 pub fn extent<'a, D: Dimension<'a, T::Summary>>(
567 &'a self,
568 cx: <T::Summary as Summary>::Context<'_>,
569 ) -> D {
570 let mut extent = D::zero(cx);
571 match self.0.as_ref() {
572 Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
573 extent.add_summary(summary, cx);
574 }
575 }
576 extent
577 }
578
579 pub fn summary(&self) -> &T::Summary {
580 match self.0.as_ref() {
581 Node::Internal { summary, .. } => summary,
582 Node::Leaf { summary, .. } => summary,
583 }
584 }
585
586 pub fn is_empty(&self) -> bool {
587 match self.0.as_ref() {
588 Node::Internal { .. } => false,
589 Node::Leaf { items, .. } => items.is_empty(),
590 }
591 }
592
593 pub fn extend<I>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
594 where
595 I: IntoIterator<Item = T>,
596 {
597 self.append(Self::from_iter(iter, cx), cx);
598 }
599
600 pub fn par_extend<I, Iter>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
601 where
602 I: IntoParallelIterator<Iter = Iter>,
603 Iter: IndexedParallelIterator<Item = T>,
604 T: Send + Sync,
605 T::Summary: Send + Sync,
606 for<'a> <T::Summary as Summary>::Context<'a>: Sync,
607 {
608 self.append(Self::from_par_iter(iter, cx), cx);
609 }
610
611 pub fn push(&mut self, item: T, cx: <T::Summary as Summary>::Context<'_>) {
612 let summary = item.summary(cx);
613 self.append(
614 SumTree(Arc::new(Node::Leaf {
615 summary: summary.clone(),
616 items: ArrayVec::from_iter(Some(item)),
617 item_summaries: ArrayVec::from_iter(Some(summary)),
618 })),
619 cx,
620 );
621 }
622
623 pub fn append(&mut self, other: Self, cx: <T::Summary as Summary>::Context<'_>) {
624 if self.is_empty() {
625 *self = other;
626 } else if !other.0.is_leaf() || !other.0.items().is_empty() {
627 if self.0.height() < other.0.height() {
628 for tree in other.0.child_trees() {
629 self.append(tree.clone(), cx);
630 }
631 } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
632 *self = Self::from_child_trees(self.clone(), split_tree, cx);
633 }
634 }
635 }
636
637 fn push_tree_recursive(
638 &mut self,
639 other: SumTree<T>,
640 cx: <T::Summary as Summary>::Context<'_>,
641 ) -> Option<SumTree<T>> {
642 match Arc::make_mut(&mut self.0) {
643 Node::Internal {
644 height,
645 summary,
646 child_summaries,
647 child_trees,
648 ..
649 } => {
650 let other_node = other.0.clone();
651 <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
652
653 let height_delta = *height - other_node.height();
654 let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
655 let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
656 if height_delta == 0 {
657 summaries_to_append.extend(other_node.child_summaries().iter().cloned());
658 trees_to_append.extend(other_node.child_trees().iter().cloned());
659 } else if height_delta == 1 && !other_node.is_underflowing() {
660 summaries_to_append.push(other_node.summary().clone());
661 trees_to_append.push(other)
662 } else {
663 let tree_to_append = child_trees
664 .last_mut()
665 .unwrap()
666 .push_tree_recursive(other, cx);
667 *child_summaries.last_mut().unwrap() =
668 child_trees.last().unwrap().0.summary().clone();
669
670 if let Some(split_tree) = tree_to_append {
671 summaries_to_append.push(split_tree.0.summary().clone());
672 trees_to_append.push(split_tree);
673 }
674 }
675
676 let child_count = child_trees.len() + trees_to_append.len();
677 if child_count > 2 * TREE_BASE {
678 let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
679 let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
680 let left_trees;
681 let right_trees;
682
683 let midpoint = (child_count + child_count % 2) / 2;
684 {
685 let mut all_summaries = child_summaries
686 .iter()
687 .chain(summaries_to_append.iter())
688 .cloned();
689 left_summaries = all_summaries.by_ref().take(midpoint).collect();
690 right_summaries = all_summaries.collect();
691 let mut all_trees =
692 child_trees.iter().chain(trees_to_append.iter()).cloned();
693 left_trees = all_trees.by_ref().take(midpoint).collect();
694 right_trees = all_trees.collect();
695 }
696 *summary = sum(left_summaries.iter(), cx);
697 *child_summaries = left_summaries;
698 *child_trees = left_trees;
699
700 Some(SumTree(Arc::new(Node::Internal {
701 height: *height,
702 summary: sum(right_summaries.iter(), cx),
703 child_summaries: right_summaries,
704 child_trees: right_trees,
705 })))
706 } else {
707 child_summaries.extend(summaries_to_append);
708 child_trees.extend(trees_to_append);
709 None
710 }
711 }
712 Node::Leaf {
713 summary,
714 items,
715 item_summaries,
716 } => {
717 let other_node = other.0;
718
719 let child_count = items.len() + other_node.items().len();
720 if child_count > 2 * TREE_BASE {
721 let left_items;
722 let right_items;
723 let left_summaries;
724 let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
725
726 let midpoint = (child_count + child_count % 2) / 2;
727 {
728 let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
729 left_items = all_items.by_ref().take(midpoint).collect();
730 right_items = all_items.collect();
731
732 let mut all_summaries = item_summaries
733 .iter()
734 .chain(other_node.child_summaries())
735 .cloned();
736 left_summaries = all_summaries.by_ref().take(midpoint).collect();
737 right_summaries = all_summaries.collect();
738 }
739 *items = left_items;
740 *item_summaries = left_summaries;
741 *summary = sum(item_summaries.iter(), cx);
742 Some(SumTree(Arc::new(Node::Leaf {
743 items: right_items,
744 summary: sum(right_summaries.iter(), cx),
745 item_summaries: right_summaries,
746 })))
747 } else {
748 <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
749 items.extend(other_node.items().iter().cloned());
750 item_summaries.extend(other_node.child_summaries().iter().cloned());
751 None
752 }
753 }
754 }
755 }
756
757 fn from_child_trees(
758 left: SumTree<T>,
759 right: SumTree<T>,
760 cx: <T::Summary as Summary>::Context<'_>,
761 ) -> Self {
762 let height = left.0.height() + 1;
763 let mut child_summaries = ArrayVec::new();
764 child_summaries.push(left.0.summary().clone());
765 child_summaries.push(right.0.summary().clone());
766 let mut child_trees = ArrayVec::new();
767 child_trees.push(left);
768 child_trees.push(right);
769 SumTree(Arc::new(Node::Internal {
770 height,
771 summary: sum(child_summaries.iter(), cx),
772 child_summaries,
773 child_trees,
774 }))
775 }
776
777 fn leftmost_leaf(&self) -> &Self {
778 match *self.0 {
779 Node::Leaf { .. } => self,
780 Node::Internal {
781 ref child_trees, ..
782 } => child_trees.first().unwrap().leftmost_leaf(),
783 }
784 }
785
786 fn rightmost_leaf(&self) -> &Self {
787 match *self.0 {
788 Node::Leaf { .. } => self,
789 Node::Internal {
790 ref child_trees, ..
791 } => child_trees.last().unwrap().rightmost_leaf(),
792 }
793 }
794}
795
796impl<T: Item + PartialEq> PartialEq for SumTree<T> {
797 fn eq(&self, other: &Self) -> bool {
798 self.iter().eq(other.iter())
799 }
800}
801
802impl<T: Item + Eq> Eq for SumTree<T> {}
803
804impl<T: KeyedItem> SumTree<T> {
805 pub fn insert_or_replace<'a, 'b>(
806 &'a mut self,
807 item: T,
808 cx: <T::Summary as Summary>::Context<'b>,
809 ) -> Option<T> {
810 let mut replaced = None;
811 {
812 let mut cursor = self.cursor::<T::Key>(cx);
813 let mut new_tree = cursor.slice(&item.key(), Bias::Left);
814 if let Some(cursor_item) = cursor.item()
815 && cursor_item.key() == item.key()
816 {
817 replaced = Some(cursor_item.clone());
818 cursor.next();
819 }
820 new_tree.push(item, cx);
821 new_tree.append(cursor.suffix(), cx);
822 drop(cursor);
823 *self = new_tree
824 };
825 replaced
826 }
827
828 pub fn remove(&mut self, key: &T::Key, cx: <T::Summary as Summary>::Context<'_>) -> Option<T> {
829 let mut removed = None;
830 *self = {
831 let mut cursor = self.cursor::<T::Key>(cx);
832 let mut new_tree = cursor.slice(key, Bias::Left);
833 if let Some(item) = cursor.item()
834 && item.key() == *key
835 {
836 removed = Some(item.clone());
837 cursor.next();
838 }
839 new_tree.append(cursor.suffix(), cx);
840 new_tree
841 };
842 removed
843 }
844
845 pub fn edit(
846 &mut self,
847 mut edits: Vec<Edit<T>>,
848 cx: <T::Summary as Summary>::Context<'_>,
849 ) -> Vec<T> {
850 if edits.is_empty() {
851 return Vec::new();
852 }
853
854 let mut removed = Vec::new();
855 edits.sort_unstable_by_key(|item| item.key());
856
857 *self = {
858 let mut cursor = self.cursor::<T::Key>(cx);
859 let mut new_tree = SumTree::new(cx);
860 let mut buffered_items = Vec::new();
861
862 cursor.seek(&T::Key::zero(cx), Bias::Left);
863 for edit in edits {
864 let new_key = edit.key();
865 let mut old_item = cursor.item();
866
867 if old_item
868 .as_ref()
869 .is_some_and(|old_item| old_item.key() < new_key)
870 {
871 new_tree.extend(buffered_items.drain(..), cx);
872 let slice = cursor.slice(&new_key, Bias::Left);
873 new_tree.append(slice, cx);
874 old_item = cursor.item();
875 }
876
877 if let Some(old_item) = old_item
878 && old_item.key() == new_key
879 {
880 removed.push(old_item.clone());
881 cursor.next();
882 }
883
884 match edit {
885 Edit::Insert(item) => {
886 buffered_items.push(item);
887 }
888 Edit::Remove(_) => {}
889 }
890 }
891
892 new_tree.extend(buffered_items, cx);
893 new_tree.append(cursor.suffix(), cx);
894 new_tree
895 };
896
897 removed
898 }
899
900 pub fn get<'a>(
901 &'a self,
902 key: &T::Key,
903 cx: <T::Summary as Summary>::Context<'a>,
904 ) -> Option<&'a T> {
905 if let (_, _, Some(item)) = self.find_exact::<T::Key, _>(cx, key, Bias::Left) {
906 Some(item)
907 } else {
908 None
909 }
910 }
911}
912
913impl<T, S> Default for SumTree<T>
914where
915 T: Item<Summary = S>,
916 S: for<'a> Summary<Context<'a> = ()>,
917{
918 fn default() -> Self {
919 Self::new(())
920 }
921}
922
923#[derive(Clone)]
924pub enum Node<T: Item> {
925 Internal {
926 height: u8,
927 summary: T::Summary,
928 child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
929 child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
930 },
931 Leaf {
932 summary: T::Summary,
933 items: ArrayVec<T, { 2 * TREE_BASE }>,
934 item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
935 },
936}
937
938impl<T> fmt::Debug for Node<T>
939where
940 T: Item + fmt::Debug,
941 T::Summary: fmt::Debug,
942{
943 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
944 match self {
945 Node::Internal {
946 height,
947 summary,
948 child_summaries,
949 child_trees,
950 } => f
951 .debug_struct("Internal")
952 .field("height", height)
953 .field("summary", summary)
954 .field("child_summaries", child_summaries)
955 .field("child_trees", child_trees)
956 .finish(),
957 Node::Leaf {
958 summary,
959 items,
960 item_summaries,
961 } => f
962 .debug_struct("Leaf")
963 .field("summary", summary)
964 .field("items", items)
965 .field("item_summaries", item_summaries)
966 .finish(),
967 }
968 }
969}
970
971impl<T: Item> Node<T> {
972 fn is_leaf(&self) -> bool {
973 matches!(self, Node::Leaf { .. })
974 }
975
976 fn height(&self) -> u8 {
977 match self {
978 Node::Internal { height, .. } => *height,
979 Node::Leaf { .. } => 0,
980 }
981 }
982
983 fn summary(&self) -> &T::Summary {
984 match self {
985 Node::Internal { summary, .. } => summary,
986 Node::Leaf { summary, .. } => summary,
987 }
988 }
989
990 fn child_summaries(&self) -> &[T::Summary] {
991 match self {
992 Node::Internal {
993 child_summaries, ..
994 } => child_summaries.as_slice(),
995 Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
996 }
997 }
998
999 fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
1000 match self {
1001 Node::Internal { child_trees, .. } => child_trees,
1002 Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
1003 }
1004 }
1005
1006 fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
1007 match self {
1008 Node::Leaf { items, .. } => items,
1009 Node::Internal { .. } => panic!("Internal nodes have no items"),
1010 }
1011 }
1012
1013 fn is_underflowing(&self) -> bool {
1014 match self {
1015 Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
1016 Node::Leaf { items, .. } => items.len() < TREE_BASE,
1017 }
1018 }
1019}
1020
1021#[derive(Debug)]
1022pub enum Edit<T: KeyedItem> {
1023 Insert(T),
1024 Remove(T::Key),
1025}
1026
1027impl<T: KeyedItem> Edit<T> {
1028 fn key(&self) -> T::Key {
1029 match self {
1030 Edit::Insert(item) => item.key(),
1031 Edit::Remove(key) => key.clone(),
1032 }
1033 }
1034}
1035
1036fn sum<'a, T, I>(iter: I, cx: T::Context<'_>) -> T
1037where
1038 T: 'a + Summary,
1039 I: Iterator<Item = &'a T>,
1040{
1041 let mut sum = T::zero(cx);
1042 for value in iter {
1043 sum.add_summary(value, cx);
1044 }
1045 sum
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050 use super::*;
1051 use rand::{distr::StandardUniform, prelude::*};
1052 use std::cmp;
1053
1054 #[ctor::ctor]
1055 fn init_logger() {
1056 zlog::init_test();
1057 }
1058
1059 #[test]
1060 fn test_extend_and_push_tree() {
1061 let mut tree1 = SumTree::default();
1062 tree1.extend(0..20, ());
1063
1064 let mut tree2 = SumTree::default();
1065 tree2.extend(50..100, ());
1066
1067 tree1.append(tree2, ());
1068 assert_eq!(tree1.items(()), (0..20).chain(50..100).collect::<Vec<u8>>());
1069 }
1070
1071 #[test]
1072 fn test_random() {
1073 let mut starting_seed = 0;
1074 if let Ok(value) = std::env::var("SEED") {
1075 starting_seed = value.parse().expect("invalid SEED variable");
1076 }
1077 let mut num_iterations = 100;
1078 if let Ok(value) = std::env::var("ITERATIONS") {
1079 num_iterations = value.parse().expect("invalid ITERATIONS variable");
1080 }
1081 let num_operations = std::env::var("OPERATIONS")
1082 .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
1083
1084 for seed in starting_seed..(starting_seed + num_iterations) {
1085 eprintln!("seed = {}", seed);
1086 let mut rng = StdRng::seed_from_u64(seed);
1087
1088 let rng = &mut rng;
1089 let mut tree = SumTree::<u8>::default();
1090 let count = rng.random_range(0..10);
1091 if rng.random() {
1092 tree.extend(rng.sample_iter(StandardUniform).take(count), ());
1093 } else {
1094 let items = rng
1095 .sample_iter(StandardUniform)
1096 .take(count)
1097 .collect::<Vec<_>>();
1098 tree.par_extend(items, ());
1099 }
1100
1101 for _ in 0..num_operations {
1102 let splice_end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1103 let splice_start = rng.random_range(0..splice_end + 1);
1104 let count = rng.random_range(0..10);
1105 let tree_end = tree.extent::<Count>(());
1106 let new_items = rng
1107 .sample_iter(StandardUniform)
1108 .take(count)
1109 .collect::<Vec<u8>>();
1110
1111 let mut reference_items = tree.items(());
1112 reference_items.splice(splice_start..splice_end, new_items.clone());
1113
1114 tree = {
1115 let mut cursor = tree.cursor::<Count>(());
1116 let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
1117 if rng.random() {
1118 new_tree.extend(new_items, ());
1119 } else {
1120 new_tree.par_extend(new_items, ());
1121 }
1122 cursor.seek(&Count(splice_end), Bias::Right);
1123 new_tree.append(cursor.slice(&tree_end, Bias::Right), ());
1124 new_tree
1125 };
1126
1127 assert_eq!(tree.items(()), reference_items);
1128 assert_eq!(
1129 tree.iter().collect::<Vec<_>>(),
1130 tree.cursor::<()>(()).collect::<Vec<_>>()
1131 );
1132
1133 log::info!("tree items: {:?}", tree.items(()));
1134
1135 let mut filter_cursor =
1136 tree.filter::<_, Count>((), |summary| summary.contains_even);
1137 let expected_filtered_items = tree
1138 .items(())
1139 .into_iter()
1140 .enumerate()
1141 .filter(|(_, item)| (item & 1) == 0)
1142 .collect::<Vec<_>>();
1143
1144 let mut item_ix = if rng.random() {
1145 filter_cursor.next();
1146 0
1147 } else {
1148 filter_cursor.prev();
1149 expected_filtered_items.len().saturating_sub(1)
1150 };
1151 while item_ix < expected_filtered_items.len() {
1152 log::info!("filter_cursor, item_ix: {}", item_ix);
1153 let actual_item = filter_cursor.item().unwrap();
1154 let (reference_index, reference_item) = expected_filtered_items[item_ix];
1155 assert_eq!(actual_item, &reference_item);
1156 assert_eq!(filter_cursor.start().0, reference_index);
1157 log::info!("next");
1158 filter_cursor.next();
1159 item_ix += 1;
1160
1161 while item_ix > 0 && rng.random_bool(0.2) {
1162 log::info!("prev");
1163 filter_cursor.prev();
1164 item_ix -= 1;
1165
1166 if item_ix == 0 && rng.random_bool(0.2) {
1167 filter_cursor.prev();
1168 assert_eq!(filter_cursor.item(), None);
1169 assert_eq!(filter_cursor.start().0, 0);
1170 filter_cursor.next();
1171 }
1172 }
1173 }
1174 assert_eq!(filter_cursor.item(), None);
1175
1176 let mut before_start = false;
1177 let mut cursor = tree.cursor::<Count>(());
1178 let start_pos = rng.random_range(0..=reference_items.len());
1179 cursor.seek(&Count(start_pos), Bias::Right);
1180 let mut pos = rng.random_range(start_pos..=reference_items.len());
1181 cursor.seek_forward(&Count(pos), Bias::Right);
1182
1183 for i in 0..10 {
1184 assert_eq!(cursor.start().0, pos);
1185
1186 if pos > 0 {
1187 assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1188 } else {
1189 assert_eq!(cursor.prev_item(), None);
1190 }
1191
1192 if pos < reference_items.len() && !before_start {
1193 assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1194 } else {
1195 assert_eq!(cursor.item(), None);
1196 }
1197
1198 if before_start {
1199 assert_eq!(cursor.next_item(), reference_items.first());
1200 } else if pos + 1 < reference_items.len() {
1201 assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1202 } else {
1203 assert_eq!(cursor.next_item(), None);
1204 }
1205
1206 if i < 5 {
1207 cursor.next();
1208 if pos < reference_items.len() {
1209 pos += 1;
1210 before_start = false;
1211 }
1212 } else {
1213 cursor.prev();
1214 if pos == 0 {
1215 before_start = true;
1216 }
1217 pos = pos.saturating_sub(1);
1218 }
1219 }
1220 }
1221
1222 for _ in 0..10 {
1223 let end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1224 let start = rng.random_range(0..end + 1);
1225 let start_bias = if rng.random() {
1226 Bias::Left
1227 } else {
1228 Bias::Right
1229 };
1230 let end_bias = if rng.random() {
1231 Bias::Left
1232 } else {
1233 Bias::Right
1234 };
1235
1236 let mut cursor = tree.cursor::<Count>(());
1237 cursor.seek(&Count(start), start_bias);
1238 let slice = cursor.slice(&Count(end), end_bias);
1239
1240 cursor.seek(&Count(start), start_bias);
1241 let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1242
1243 assert_eq!(summary.0, slice.summary().sum);
1244 }
1245 }
1246 }
1247
1248 #[test]
1249 fn test_cursor() {
1250 // Empty tree
1251 let tree = SumTree::<u8>::default();
1252 let mut cursor = tree.cursor::<IntegersSummary>(());
1253 assert_eq!(
1254 cursor.slice(&Count(0), Bias::Right).items(()),
1255 Vec::<u8>::new()
1256 );
1257 assert_eq!(cursor.item(), None);
1258 assert_eq!(cursor.prev_item(), None);
1259 assert_eq!(cursor.next_item(), None);
1260 assert_eq!(cursor.start().sum, 0);
1261 cursor.prev();
1262 assert_eq!(cursor.item(), None);
1263 assert_eq!(cursor.prev_item(), None);
1264 assert_eq!(cursor.next_item(), None);
1265 assert_eq!(cursor.start().sum, 0);
1266 cursor.next();
1267 assert_eq!(cursor.item(), None);
1268 assert_eq!(cursor.prev_item(), None);
1269 assert_eq!(cursor.next_item(), None);
1270 assert_eq!(cursor.start().sum, 0);
1271
1272 // Single-element tree
1273 let mut tree = SumTree::<u8>::default();
1274 tree.extend(vec![1], ());
1275 let mut cursor = tree.cursor::<IntegersSummary>(());
1276 assert_eq!(
1277 cursor.slice(&Count(0), Bias::Right).items(()),
1278 Vec::<u8>::new()
1279 );
1280 assert_eq!(cursor.item(), Some(&1));
1281 assert_eq!(cursor.prev_item(), None);
1282 assert_eq!(cursor.next_item(), None);
1283 assert_eq!(cursor.start().sum, 0);
1284
1285 cursor.next();
1286 assert_eq!(cursor.item(), None);
1287 assert_eq!(cursor.prev_item(), Some(&1));
1288 assert_eq!(cursor.next_item(), None);
1289 assert_eq!(cursor.start().sum, 1);
1290
1291 cursor.prev();
1292 assert_eq!(cursor.item(), Some(&1));
1293 assert_eq!(cursor.prev_item(), None);
1294 assert_eq!(cursor.next_item(), None);
1295 assert_eq!(cursor.start().sum, 0);
1296
1297 let mut cursor = tree.cursor::<IntegersSummary>(());
1298 assert_eq!(cursor.slice(&Count(1), Bias::Right).items(()), [1]);
1299 assert_eq!(cursor.item(), None);
1300 assert_eq!(cursor.prev_item(), Some(&1));
1301 assert_eq!(cursor.next_item(), None);
1302 assert_eq!(cursor.start().sum, 1);
1303
1304 cursor.seek(&Count(0), Bias::Right);
1305 assert_eq!(
1306 cursor
1307 .slice(&tree.extent::<Count>(()), Bias::Right)
1308 .items(()),
1309 [1]
1310 );
1311 assert_eq!(cursor.item(), None);
1312 assert_eq!(cursor.prev_item(), Some(&1));
1313 assert_eq!(cursor.next_item(), None);
1314 assert_eq!(cursor.start().sum, 1);
1315
1316 // Multiple-element tree
1317 let mut tree = SumTree::default();
1318 tree.extend(vec![1, 2, 3, 4, 5, 6], ());
1319 let mut cursor = tree.cursor::<IntegersSummary>(());
1320
1321 assert_eq!(cursor.slice(&Count(2), Bias::Right).items(()), [1, 2]);
1322 assert_eq!(cursor.item(), Some(&3));
1323 assert_eq!(cursor.prev_item(), Some(&2));
1324 assert_eq!(cursor.next_item(), Some(&4));
1325 assert_eq!(cursor.start().sum, 3);
1326
1327 cursor.next();
1328 assert_eq!(cursor.item(), Some(&4));
1329 assert_eq!(cursor.prev_item(), Some(&3));
1330 assert_eq!(cursor.next_item(), Some(&5));
1331 assert_eq!(cursor.start().sum, 6);
1332
1333 cursor.next();
1334 assert_eq!(cursor.item(), Some(&5));
1335 assert_eq!(cursor.prev_item(), Some(&4));
1336 assert_eq!(cursor.next_item(), Some(&6));
1337 assert_eq!(cursor.start().sum, 10);
1338
1339 cursor.next();
1340 assert_eq!(cursor.item(), Some(&6));
1341 assert_eq!(cursor.prev_item(), Some(&5));
1342 assert_eq!(cursor.next_item(), None);
1343 assert_eq!(cursor.start().sum, 15);
1344
1345 cursor.next();
1346 cursor.next();
1347 assert_eq!(cursor.item(), None);
1348 assert_eq!(cursor.prev_item(), Some(&6));
1349 assert_eq!(cursor.next_item(), None);
1350 assert_eq!(cursor.start().sum, 21);
1351
1352 cursor.prev();
1353 assert_eq!(cursor.item(), Some(&6));
1354 assert_eq!(cursor.prev_item(), Some(&5));
1355 assert_eq!(cursor.next_item(), None);
1356 assert_eq!(cursor.start().sum, 15);
1357
1358 cursor.prev();
1359 assert_eq!(cursor.item(), Some(&5));
1360 assert_eq!(cursor.prev_item(), Some(&4));
1361 assert_eq!(cursor.next_item(), Some(&6));
1362 assert_eq!(cursor.start().sum, 10);
1363
1364 cursor.prev();
1365 assert_eq!(cursor.item(), Some(&4));
1366 assert_eq!(cursor.prev_item(), Some(&3));
1367 assert_eq!(cursor.next_item(), Some(&5));
1368 assert_eq!(cursor.start().sum, 6);
1369
1370 cursor.prev();
1371 assert_eq!(cursor.item(), Some(&3));
1372 assert_eq!(cursor.prev_item(), Some(&2));
1373 assert_eq!(cursor.next_item(), Some(&4));
1374 assert_eq!(cursor.start().sum, 3);
1375
1376 cursor.prev();
1377 assert_eq!(cursor.item(), Some(&2));
1378 assert_eq!(cursor.prev_item(), Some(&1));
1379 assert_eq!(cursor.next_item(), Some(&3));
1380 assert_eq!(cursor.start().sum, 1);
1381
1382 cursor.prev();
1383 assert_eq!(cursor.item(), Some(&1));
1384 assert_eq!(cursor.prev_item(), None);
1385 assert_eq!(cursor.next_item(), Some(&2));
1386 assert_eq!(cursor.start().sum, 0);
1387
1388 cursor.prev();
1389 assert_eq!(cursor.item(), None);
1390 assert_eq!(cursor.prev_item(), None);
1391 assert_eq!(cursor.next_item(), Some(&1));
1392 assert_eq!(cursor.start().sum, 0);
1393
1394 cursor.next();
1395 assert_eq!(cursor.item(), Some(&1));
1396 assert_eq!(cursor.prev_item(), None);
1397 assert_eq!(cursor.next_item(), Some(&2));
1398 assert_eq!(cursor.start().sum, 0);
1399
1400 let mut cursor = tree.cursor::<IntegersSummary>(());
1401 assert_eq!(
1402 cursor
1403 .slice(&tree.extent::<Count>(()), Bias::Right)
1404 .items(()),
1405 tree.items(())
1406 );
1407 assert_eq!(cursor.item(), None);
1408 assert_eq!(cursor.prev_item(), Some(&6));
1409 assert_eq!(cursor.next_item(), None);
1410 assert_eq!(cursor.start().sum, 21);
1411
1412 cursor.seek(&Count(3), Bias::Right);
1413 assert_eq!(
1414 cursor
1415 .slice(&tree.extent::<Count>(()), Bias::Right)
1416 .items(()),
1417 [4, 5, 6]
1418 );
1419 assert_eq!(cursor.item(), None);
1420 assert_eq!(cursor.prev_item(), Some(&6));
1421 assert_eq!(cursor.next_item(), None);
1422 assert_eq!(cursor.start().sum, 21);
1423
1424 // Seeking can bias left or right
1425 cursor.seek(&Count(1), Bias::Left);
1426 assert_eq!(cursor.item(), Some(&1));
1427 cursor.seek(&Count(1), Bias::Right);
1428 assert_eq!(cursor.item(), Some(&2));
1429
1430 // Slicing without resetting starts from where the cursor is parked at.
1431 cursor.seek(&Count(1), Bias::Right);
1432 assert_eq!(cursor.slice(&Count(3), Bias::Right).items(()), vec![2, 3]);
1433 assert_eq!(cursor.slice(&Count(6), Bias::Left).items(()), vec![4, 5]);
1434 assert_eq!(cursor.slice(&Count(6), Bias::Right).items(()), vec![6]);
1435 }
1436
1437 #[test]
1438 fn test_edit() {
1439 let mut tree = SumTree::<u8>::default();
1440
1441 let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], ());
1442 assert_eq!(tree.items(()), vec![0, 1, 2]);
1443 assert_eq!(removed, Vec::<u8>::new());
1444 assert_eq!(tree.get(&0, ()), Some(&0));
1445 assert_eq!(tree.get(&1, ()), Some(&1));
1446 assert_eq!(tree.get(&2, ()), Some(&2));
1447 assert_eq!(tree.get(&4, ()), None);
1448
1449 let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], ());
1450 assert_eq!(tree.items(()), vec![1, 2, 4]);
1451 assert_eq!(removed, vec![0, 2]);
1452 assert_eq!(tree.get(&0, ()), None);
1453 assert_eq!(tree.get(&1, ()), Some(&1));
1454 assert_eq!(tree.get(&2, ()), Some(&2));
1455 assert_eq!(tree.get(&4, ()), Some(&4));
1456 }
1457
1458 #[test]
1459 fn test_from_iter() {
1460 assert_eq!(
1461 SumTree::from_iter(0..100, ()).items(()),
1462 (0..100).collect::<Vec<_>>()
1463 );
1464
1465 // Ensure `from_iter` works correctly when the given iterator restarts
1466 // after calling `next` if `None` was already returned.
1467 let mut ix = 0;
1468 let iterator = std::iter::from_fn(|| {
1469 ix = (ix + 1) % 2;
1470 if ix == 1 { Some(1) } else { None }
1471 });
1472 assert_eq!(SumTree::from_iter(iterator, ()).items(()), vec![1]);
1473 }
1474
1475 #[derive(Clone, Default, Debug)]
1476 pub struct IntegersSummary {
1477 count: usize,
1478 sum: usize,
1479 contains_even: bool,
1480 max: u8,
1481 }
1482
1483 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1484 struct Count(usize);
1485
1486 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1487 struct Sum(usize);
1488
1489 impl Item for u8 {
1490 type Summary = IntegersSummary;
1491
1492 fn summary(&self, _cx: ()) -> Self::Summary {
1493 IntegersSummary {
1494 count: 1,
1495 sum: *self as usize,
1496 contains_even: (*self & 1) == 0,
1497 max: *self,
1498 }
1499 }
1500 }
1501
1502 impl KeyedItem for u8 {
1503 type Key = u8;
1504
1505 fn key(&self) -> Self::Key {
1506 *self
1507 }
1508 }
1509
1510 impl ContextLessSummary for IntegersSummary {
1511 fn zero() -> Self {
1512 Default::default()
1513 }
1514
1515 fn add_summary(&mut self, other: &Self) {
1516 self.count += other.count;
1517 self.sum += other.sum;
1518 self.contains_even |= other.contains_even;
1519 self.max = cmp::max(self.max, other.max);
1520 }
1521 }
1522
1523 impl Dimension<'_, IntegersSummary> for u8 {
1524 fn zero(_cx: ()) -> Self {
1525 Default::default()
1526 }
1527
1528 fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1529 *self = summary.max;
1530 }
1531 }
1532
1533 impl Dimension<'_, IntegersSummary> for Count {
1534 fn zero(_cx: ()) -> Self {
1535 Default::default()
1536 }
1537
1538 fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1539 self.0 += summary.count;
1540 }
1541 }
1542
1543 impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1544 fn cmp(&self, cursor_location: &IntegersSummary, _: ()) -> Ordering {
1545 self.0.cmp(&cursor_location.count)
1546 }
1547 }
1548
1549 impl Dimension<'_, IntegersSummary> for Sum {
1550 fn zero(_cx: ()) -> Self {
1551 Default::default()
1552 }
1553
1554 fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1555 self.0 += summary.sum;
1556 }
1557 }
1558}