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