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_iterate::<_, _, 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_iterate::<_, _, 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_iterate<'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 mut 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 'iterate: loop {
448 match &*this.0 {
449 Node::Internal {
450 child_summaries,
451 child_trees,
452 ..
453 } => {
454 for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
455 let child_end = position.clone().with_added_summary(child_summary, cx);
456
457 let comparison = target.cmp(&child_end, cx);
458 let target_in_child = comparison == Ordering::Less
459 || (comparison == Ordering::Equal && bias == Bias::Left);
460 if target_in_child {
461 this = child_tree;
462 continue 'iterate;
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 return None;
492 }
493 }
494
495 /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
496 #[instrument(skip_all)]
497 pub fn find_with_prev<'a, 'slf, D, Target>(
498 &'slf self,
499 cx: <T::Summary as Summary>::Context<'a>,
500 target: &Target,
501 bias: Bias,
502 ) -> (D, D, Option<(Option<&'slf T>, &'slf T)>)
503 where
504 D: Dimension<'slf, T::Summary>,
505 Target: SeekTarget<'slf, T::Summary, D>,
506 {
507 let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
508 let comparison = target.cmp(&tree_end, cx);
509 if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
510 {
511 return (tree_end.clone(), tree_end, None);
512 }
513
514 let mut pos = D::zero(cx);
515 return match Self::find_with_prev_iterate::<_, _, false>(cx, target, bias, &mut pos, self) {
516 Some((prev, item, end)) => (pos, end, Some((prev, item))),
517 None => (pos.clone(), pos, None),
518 };
519 }
520
521 fn find_with_prev_iterate<'tree, 'a, D, Target, const EXACT: bool>(
522 cx: <T::Summary as Summary>::Context<'a>,
523 target: &Target,
524 bias: Bias,
525 position: &mut D,
526 mut this: &'tree SumTree<T>,
527 ) -> Option<(Option<&'tree T>, &'tree T, D)>
528 where
529 D: Dimension<'tree, T::Summary>,
530 Target: SeekTarget<'tree, T::Summary, D>,
531 {
532 let mut prev = None;
533 'iterate: loop {
534 match &*this.0 {
535 Node::Internal {
536 child_summaries,
537 child_trees,
538 ..
539 } => {
540 for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
541 let child_end = position.clone().with_added_summary(child_summary, cx);
542
543 let comparison = target.cmp(&child_end, cx);
544 let target_in_child = comparison == Ordering::Less
545 || (comparison == Ordering::Equal && bias == Bias::Left);
546 if target_in_child {
547 this = child_tree;
548 continue 'iterate;
549 }
550 prev = child_tree.last();
551 *position = child_end;
552 }
553 }
554 Node::Leaf {
555 items,
556 item_summaries,
557 ..
558 } => {
559 for (item, item_summary) in items.iter().zip(item_summaries) {
560 let mut child_end = position.clone();
561 child_end.add_summary(item_summary, cx);
562
563 let comparison = target.cmp(&child_end, cx);
564 let entry_found = if EXACT {
565 comparison == Ordering::Equal
566 } else {
567 comparison == Ordering::Less
568 || (comparison == Ordering::Equal && bias == Bias::Left)
569 };
570 if entry_found {
571 return Some((prev, item, child_end));
572 }
573
574 prev = Some(item);
575 *position = child_end;
576 }
577 }
578 }
579 return None;
580 }
581 }
582
583 pub fn cursor<'a, 'b, D>(
584 &'a self,
585 cx: <T::Summary as Summary>::Context<'b>,
586 ) -> Cursor<'a, 'b, T, D>
587 where
588 D: Dimension<'a, T::Summary>,
589 {
590 Cursor::new(self, cx)
591 }
592
593 /// Note: If the summary type requires a non `()` context, then the filter cursor
594 /// that is returned cannot be used with Rust's iterators.
595 pub fn filter<'a, 'b, F, U>(
596 &'a self,
597 cx: <T::Summary as Summary>::Context<'b>,
598 filter_node: F,
599 ) -> FilterCursor<'a, 'b, F, T, U>
600 where
601 F: FnMut(&T::Summary) -> bool,
602 U: Dimension<'a, T::Summary>,
603 {
604 FilterCursor::new(self, cx, filter_node)
605 }
606
607 #[allow(dead_code)]
608 pub fn first(&self) -> Option<&T> {
609 self.leftmost_leaf().0.items().first()
610 }
611
612 pub fn last(&self) -> Option<&T> {
613 self.rightmost_leaf().0.items().last()
614 }
615
616 pub fn update_last(
617 &mut self,
618 f: impl FnOnce(&mut T),
619 cx: <T::Summary as Summary>::Context<'_>,
620 ) {
621 self.update_last_recursive(f, cx);
622 }
623
624 fn update_last_recursive(
625 &mut self,
626 f: impl FnOnce(&mut T),
627 cx: <T::Summary as Summary>::Context<'_>,
628 ) -> Option<T::Summary> {
629 match Arc::make_mut(&mut self.0) {
630 Node::Internal {
631 summary,
632 child_summaries,
633 child_trees,
634 ..
635 } => {
636 let last_summary = child_summaries.last_mut().unwrap();
637 let last_child = child_trees.last_mut().unwrap();
638 *last_summary = last_child.update_last_recursive(f, cx).unwrap();
639 *summary = sum(child_summaries.iter(), cx);
640 Some(summary.clone())
641 }
642 Node::Leaf {
643 summary,
644 items,
645 item_summaries,
646 } => {
647 if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
648 {
649 (f)(item);
650 *item_summary = item.summary(cx);
651 *summary = sum(item_summaries.iter(), cx);
652 Some(summary.clone())
653 } else {
654 None
655 }
656 }
657 }
658 }
659
660 pub fn extent<'a, D: Dimension<'a, T::Summary>>(
661 &'a self,
662 cx: <T::Summary as Summary>::Context<'_>,
663 ) -> D {
664 let mut extent = D::zero(cx);
665 match self.0.as_ref() {
666 Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
667 extent.add_summary(summary, cx);
668 }
669 }
670 extent
671 }
672
673 pub fn summary(&self) -> &T::Summary {
674 match self.0.as_ref() {
675 Node::Internal { summary, .. } => summary,
676 Node::Leaf { summary, .. } => summary,
677 }
678 }
679
680 pub fn is_empty(&self) -> bool {
681 match self.0.as_ref() {
682 Node::Internal { .. } => false,
683 Node::Leaf { items, .. } => items.is_empty(),
684 }
685 }
686
687 pub fn extend<I>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
688 where
689 I: IntoIterator<Item = T>,
690 {
691 self.append(Self::from_iter(iter, cx), cx);
692 }
693
694 pub fn par_extend<I, Iter>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
695 where
696 I: IntoParallelIterator<Iter = Iter>,
697 Iter: IndexedParallelIterator<Item = T>,
698 T: Send + Sync,
699 T::Summary: Send + Sync,
700 for<'a> <T::Summary as Summary>::Context<'a>: Sync,
701 {
702 self.append(Self::from_par_iter(iter, cx), cx);
703 }
704
705 pub fn push(&mut self, item: T, cx: <T::Summary as Summary>::Context<'_>) {
706 let summary = item.summary(cx);
707 self.append(
708 SumTree(Arc::new(Node::Leaf {
709 summary: summary.clone(),
710 items: ArrayVec::from_iter(Some(item)),
711 item_summaries: ArrayVec::from_iter(Some(summary)),
712 })),
713 cx,
714 );
715 }
716
717 pub fn append(&mut self, mut other: Self, cx: <T::Summary as Summary>::Context<'_>) {
718 if self.is_empty() {
719 *self = other;
720 } else if !other.0.is_leaf() || !other.0.items().is_empty() {
721 if self.0.height() < other.0.height() {
722 if let Some(tree) = Self::append_large(self.clone(), &mut other, cx) {
723 *self = Self::from_child_trees(tree, other, cx);
724 } else {
725 *self = other;
726 }
727 } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
728 *self = Self::from_child_trees(self.clone(), split_tree, cx);
729 }
730 }
731 }
732
733 fn push_tree_recursive(
734 &mut self,
735 other: SumTree<T>,
736 cx: <T::Summary as Summary>::Context<'_>,
737 ) -> Option<SumTree<T>> {
738 match Arc::make_mut(&mut self.0) {
739 Node::Internal {
740 height,
741 summary,
742 child_summaries,
743 child_trees,
744 ..
745 } => {
746 let other_node = other.0.clone();
747 <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
748
749 let height_delta = *height - other_node.height();
750 let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
751 let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
752 if height_delta == 0 {
753 summaries_to_append.extend(other_node.child_summaries().iter().cloned());
754 trees_to_append.extend(other_node.child_trees().iter().cloned());
755 } else if height_delta == 1 && !other_node.is_underflowing() {
756 summaries_to_append.push(other_node.summary().clone());
757 trees_to_append.push(other)
758 } else {
759 let tree_to_append = child_trees
760 .last_mut()
761 .unwrap()
762 .push_tree_recursive(other, cx);
763 *child_summaries.last_mut().unwrap() =
764 child_trees.last().unwrap().0.summary().clone();
765
766 if let Some(split_tree) = tree_to_append {
767 summaries_to_append.push(split_tree.0.summary().clone());
768 trees_to_append.push(split_tree);
769 }
770 }
771
772 let child_count = child_trees.len() + trees_to_append.len();
773 if child_count > 2 * TREE_BASE {
774 let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
775 let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
776 let left_trees;
777 let right_trees;
778
779 let midpoint = (child_count + child_count % 2) / 2;
780 {
781 let mut all_summaries = child_summaries
782 .iter()
783 .chain(summaries_to_append.iter())
784 .cloned();
785 left_summaries = all_summaries.by_ref().take(midpoint).collect();
786 right_summaries = all_summaries.collect();
787 let mut all_trees =
788 child_trees.iter().chain(trees_to_append.iter()).cloned();
789 left_trees = all_trees.by_ref().take(midpoint).collect();
790 right_trees = all_trees.collect();
791 }
792 *summary = sum(left_summaries.iter(), cx);
793 *child_summaries = left_summaries;
794 *child_trees = left_trees;
795
796 Some(SumTree(Arc::new(Node::Internal {
797 height: *height,
798 summary: sum(right_summaries.iter(), cx),
799 child_summaries: right_summaries,
800 child_trees: right_trees,
801 })))
802 } else {
803 child_summaries.extend(summaries_to_append);
804 child_trees.extend(trees_to_append);
805 None
806 }
807 }
808 Node::Leaf {
809 summary,
810 items,
811 item_summaries,
812 } => {
813 let other_node = other.0;
814
815 let child_count = items.len() + other_node.items().len();
816 if child_count > 2 * TREE_BASE {
817 let left_items;
818 let right_items;
819 let left_summaries;
820 let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
821
822 let midpoint = (child_count + child_count % 2) / 2;
823 {
824 let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
825 left_items = all_items.by_ref().take(midpoint).collect();
826 right_items = all_items.collect();
827
828 let mut all_summaries = item_summaries
829 .iter()
830 .chain(other_node.child_summaries())
831 .cloned();
832 left_summaries = all_summaries.by_ref().take(midpoint).collect();
833 right_summaries = all_summaries.collect();
834 }
835 *items = left_items;
836 *item_summaries = left_summaries;
837 *summary = sum(item_summaries.iter(), cx);
838 Some(SumTree(Arc::new(Node::Leaf {
839 items: right_items,
840 summary: sum(right_summaries.iter(), cx),
841 item_summaries: right_summaries,
842 })))
843 } else {
844 <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
845 items.extend(other_node.items().iter().cloned());
846 item_summaries.extend(other_node.child_summaries().iter().cloned());
847 None
848 }
849 }
850 }
851 }
852
853 // appends the `large` tree to a `small` tree, assumes small.height() <= large.height()
854 fn append_large(
855 small: Self,
856 large: &mut Self,
857 cx: <T::Summary as Summary>::Context<'_>,
858 ) -> Option<Self> {
859 if small.0.height() == large.0.height() {
860 if !small.0.is_underflowing() {
861 Some(small)
862 } else {
863 Self::merge_into_right(small, large, cx)
864 }
865 } else {
866 debug_assert!(small.0.height() < large.0.height());
867 let Node::Internal {
868 height,
869 summary,
870 child_summaries,
871 child_trees,
872 } = Arc::make_mut(&mut large.0)
873 else {
874 unreachable!();
875 };
876 let mut full_summary = small.summary().clone();
877 Summary::add_summary(&mut full_summary, summary, cx);
878 *summary = full_summary;
879
880 let first = child_trees.first_mut().unwrap();
881 let res = Self::append_large(small, first, cx);
882 *child_summaries.first_mut().unwrap() = first.summary().clone();
883 if let Some(tree) = res {
884 if child_trees.len() < 2 * TREE_BASE {
885 child_summaries.insert(0, tree.summary().clone());
886 child_trees.insert(0, tree);
887 None
888 } else {
889 let new_child_summaries = {
890 let mut res = ArrayVec::from_iter([tree.summary().clone()]);
891 res.extend(child_summaries.drain(..TREE_BASE));
892 res
893 };
894 let tree = SumTree(Arc::new(Node::Internal {
895 height: *height,
896 summary: sum(new_child_summaries.iter(), cx),
897 child_summaries: new_child_summaries,
898 child_trees: {
899 let mut res = ArrayVec::from_iter([tree]);
900 res.extend(child_trees.drain(..TREE_BASE));
901 res
902 },
903 }));
904
905 *summary = sum(child_summaries.iter(), cx);
906 Some(tree)
907 }
908 } else {
909 None
910 }
911 }
912 }
913
914 // Merge two nodes into `large`.
915 //
916 // `large` will contain the contents of `small` followed by its own data.
917 // If the combined data exceed the node capacity, returns a new node that
918 // holds the first half of the merged items and `large` is left with the
919 // second half
920 //
921 // The nodes must be on the same height
922 // It only makes sense to call this when `small` is underflowing
923 fn merge_into_right(
924 small: Self,
925 large: &mut Self,
926 cx: <<T as Item>::Summary as Summary>::Context<'_>,
927 ) -> Option<SumTree<T>> {
928 debug_assert_eq!(small.0.height(), large.0.height());
929 match (small.0.as_ref(), Arc::make_mut(&mut large.0)) {
930 (
931 Node::Internal {
932 summary: small_summary,
933 child_summaries: small_child_summaries,
934 child_trees: small_child_trees,
935 ..
936 },
937 Node::Internal {
938 summary,
939 child_summaries,
940 child_trees,
941 height,
942 },
943 ) => {
944 let total_child_count = child_trees.len() + small_child_trees.len();
945 if total_child_count <= 2 * TREE_BASE {
946 let mut all_trees = small_child_trees.clone();
947 all_trees.extend(child_trees.drain(..));
948 *child_trees = all_trees;
949
950 let mut all_summaries = small_child_summaries.clone();
951 all_summaries.extend(child_summaries.drain(..));
952 *child_summaries = all_summaries;
953
954 let mut full_summary = small_summary.clone();
955 Summary::add_summary(&mut full_summary, summary, cx);
956 *summary = full_summary;
957 None
958 } else {
959 let midpoint = total_child_count.div_ceil(2);
960 let mut all_trees = small_child_trees.iter().chain(child_trees.iter()).cloned();
961 let left_trees = all_trees.by_ref().take(midpoint).collect();
962 *child_trees = all_trees.collect();
963
964 let mut all_summaries = small_child_summaries
965 .iter()
966 .chain(child_summaries.iter())
967 .cloned();
968 let left_summaries: ArrayVec<_, { 2 * TREE_BASE }> =
969 all_summaries.by_ref().take(midpoint).collect();
970 *child_summaries = all_summaries.collect();
971
972 *summary = sum(child_summaries.iter(), cx);
973 Some(SumTree(Arc::new(Node::Internal {
974 height: *height,
975 summary: sum(left_summaries.iter(), cx),
976 child_summaries: left_summaries,
977 child_trees: left_trees,
978 })))
979 }
980 }
981 (
982 Node::Leaf {
983 summary: small_summary,
984 items: small_items,
985 item_summaries: small_item_summaries,
986 },
987 Node::Leaf {
988 summary,
989 items,
990 item_summaries,
991 },
992 ) => {
993 let total_child_count = small_items.len() + items.len();
994 if total_child_count <= 2 * TREE_BASE {
995 let mut all_items = small_items.clone();
996 all_items.extend(items.drain(..));
997 *items = all_items;
998
999 let mut all_summaries = small_item_summaries.clone();
1000 all_summaries.extend(item_summaries.drain(..));
1001 *item_summaries = all_summaries;
1002
1003 let mut full_summary = small_summary.clone();
1004 Summary::add_summary(&mut full_summary, summary, cx);
1005 *summary = full_summary;
1006 None
1007 } else {
1008 let midpoint = total_child_count.div_ceil(2);
1009 let mut all_items = small_items.iter().chain(items.iter()).cloned();
1010 let left_items = all_items.by_ref().take(midpoint).collect();
1011 *items = all_items.collect();
1012
1013 let mut all_summaries = small_item_summaries
1014 .iter()
1015 .chain(item_summaries.iter())
1016 .cloned();
1017 let left_summaries: ArrayVec<_, { 2 * TREE_BASE }> =
1018 all_summaries.by_ref().take(midpoint).collect();
1019 *item_summaries = all_summaries.collect();
1020
1021 *summary = sum(item_summaries.iter(), cx);
1022 Some(SumTree(Arc::new(Node::Leaf {
1023 items: left_items,
1024 summary: sum(left_summaries.iter(), cx),
1025 item_summaries: left_summaries,
1026 })))
1027 }
1028 }
1029 _ => unreachable!(),
1030 }
1031 }
1032
1033 fn from_child_trees(
1034 left: SumTree<T>,
1035 right: SumTree<T>,
1036 cx: <T::Summary as Summary>::Context<'_>,
1037 ) -> Self {
1038 let height = left.0.height() + 1;
1039 let mut child_summaries = ArrayVec::new();
1040 child_summaries.push(left.0.summary().clone());
1041 child_summaries.push(right.0.summary().clone());
1042 let mut child_trees = ArrayVec::new();
1043 child_trees.push(left);
1044 child_trees.push(right);
1045 SumTree(Arc::new(Node::Internal {
1046 height,
1047 summary: sum(child_summaries.iter(), cx),
1048 child_summaries,
1049 child_trees,
1050 }))
1051 }
1052
1053 fn leftmost_leaf(&self) -> &Self {
1054 match *self.0 {
1055 Node::Leaf { .. } => self,
1056 Node::Internal {
1057 ref child_trees, ..
1058 } => child_trees.first().unwrap().leftmost_leaf(),
1059 }
1060 }
1061
1062 fn rightmost_leaf(&self) -> &Self {
1063 match *self.0 {
1064 Node::Leaf { .. } => self,
1065 Node::Internal {
1066 ref child_trees, ..
1067 } => child_trees.last().unwrap().rightmost_leaf(),
1068 }
1069 }
1070}
1071
1072impl<T: Item + PartialEq> PartialEq for SumTree<T> {
1073 fn eq(&self, other: &Self) -> bool {
1074 self.iter().eq(other.iter())
1075 }
1076}
1077
1078impl<T: Item + Eq> Eq for SumTree<T> {}
1079
1080impl<T: KeyedItem> SumTree<T> {
1081 pub fn insert_or_replace<'a, 'b>(
1082 &'a mut self,
1083 item: T,
1084 cx: <T::Summary as Summary>::Context<'b>,
1085 ) -> Option<T> {
1086 let mut replaced = None;
1087 {
1088 let mut cursor = self.cursor::<T::Key>(cx);
1089 let mut new_tree = cursor.slice(&item.key(), Bias::Left);
1090 if let Some(cursor_item) = cursor.item()
1091 && cursor_item.key() == item.key()
1092 {
1093 replaced = Some(cursor_item.clone());
1094 cursor.next();
1095 }
1096 new_tree.push(item, cx);
1097 new_tree.append(cursor.suffix(), cx);
1098 drop(cursor);
1099 *self = new_tree
1100 };
1101 replaced
1102 }
1103
1104 pub fn remove(&mut self, key: &T::Key, cx: <T::Summary as Summary>::Context<'_>) -> Option<T> {
1105 let mut removed = None;
1106 *self = {
1107 let mut cursor = self.cursor::<T::Key>(cx);
1108 let mut new_tree = cursor.slice(key, Bias::Left);
1109 if let Some(item) = cursor.item()
1110 && item.key() == *key
1111 {
1112 removed = Some(item.clone());
1113 cursor.next();
1114 }
1115 new_tree.append(cursor.suffix(), cx);
1116 new_tree
1117 };
1118 removed
1119 }
1120
1121 pub fn edit(
1122 &mut self,
1123 mut edits: Vec<Edit<T>>,
1124 cx: <T::Summary as Summary>::Context<'_>,
1125 ) -> Vec<T> {
1126 if edits.is_empty() {
1127 return Vec::new();
1128 }
1129
1130 let mut removed = Vec::new();
1131 edits.sort_unstable_by_key(|item| item.key());
1132
1133 *self = {
1134 let mut cursor = self.cursor::<T::Key>(cx);
1135 let mut new_tree = SumTree::new(cx);
1136 let mut buffered_items = Vec::new();
1137
1138 cursor.seek(&T::Key::zero(cx), Bias::Left);
1139 for edit in edits {
1140 let new_key = edit.key();
1141 let mut old_item = cursor.item();
1142
1143 if old_item
1144 .as_ref()
1145 .is_some_and(|old_item| old_item.key() < new_key)
1146 {
1147 new_tree.extend(buffered_items.drain(..), cx);
1148 let slice = cursor.slice(&new_key, Bias::Left);
1149 new_tree.append(slice, cx);
1150 old_item = cursor.item();
1151 }
1152
1153 if let Some(old_item) = old_item
1154 && old_item.key() == new_key
1155 {
1156 removed.push(old_item.clone());
1157 cursor.next();
1158 }
1159
1160 match edit {
1161 Edit::Insert(item) => {
1162 buffered_items.push(item);
1163 }
1164 Edit::Remove(_) => {}
1165 }
1166 }
1167
1168 new_tree.extend(buffered_items, cx);
1169 new_tree.append(cursor.suffix(), cx);
1170 new_tree
1171 };
1172
1173 removed
1174 }
1175
1176 pub fn get<'a>(
1177 &'a self,
1178 key: &T::Key,
1179 cx: <T::Summary as Summary>::Context<'a>,
1180 ) -> Option<&'a T> {
1181 if let (_, _, Some(item)) = self.find_exact::<T::Key, _>(cx, key, Bias::Left) {
1182 Some(item)
1183 } else {
1184 None
1185 }
1186 }
1187}
1188
1189impl<T, S> Default for SumTree<T>
1190where
1191 T: Item<Summary = S>,
1192 S: for<'a> Summary<Context<'a> = ()>,
1193{
1194 fn default() -> Self {
1195 Self::new(())
1196 }
1197}
1198
1199#[derive(Clone)]
1200pub enum Node<T: Item> {
1201 Internal {
1202 height: u8,
1203 summary: T::Summary,
1204 child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
1205 child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
1206 },
1207 Leaf {
1208 summary: T::Summary,
1209 items: ArrayVec<T, { 2 * TREE_BASE }>,
1210 item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
1211 },
1212}
1213
1214impl<T> fmt::Debug for Node<T>
1215where
1216 T: Item + fmt::Debug,
1217 T::Summary: fmt::Debug,
1218{
1219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1220 match self {
1221 Node::Internal {
1222 height,
1223 summary,
1224 child_summaries,
1225 child_trees,
1226 } => f
1227 .debug_struct("Internal")
1228 .field("height", height)
1229 .field("summary", summary)
1230 .field("child_summaries", child_summaries)
1231 .field("child_trees", child_trees)
1232 .finish(),
1233 Node::Leaf {
1234 summary,
1235 items,
1236 item_summaries,
1237 } => f
1238 .debug_struct("Leaf")
1239 .field("summary", summary)
1240 .field("items", items)
1241 .field("item_summaries", item_summaries)
1242 .finish(),
1243 }
1244 }
1245}
1246
1247impl<T: Item> Node<T> {
1248 fn is_leaf(&self) -> bool {
1249 matches!(self, Node::Leaf { .. })
1250 }
1251
1252 fn height(&self) -> u8 {
1253 match self {
1254 Node::Internal { height, .. } => *height,
1255 Node::Leaf { .. } => 0,
1256 }
1257 }
1258
1259 fn summary(&self) -> &T::Summary {
1260 match self {
1261 Node::Internal { summary, .. } => summary,
1262 Node::Leaf { summary, .. } => summary,
1263 }
1264 }
1265
1266 fn child_summaries(&self) -> &[T::Summary] {
1267 match self {
1268 Node::Internal {
1269 child_summaries, ..
1270 } => child_summaries.as_slice(),
1271 Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
1272 }
1273 }
1274
1275 fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
1276 match self {
1277 Node::Internal { child_trees, .. } => child_trees,
1278 Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
1279 }
1280 }
1281
1282 fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
1283 match self {
1284 Node::Leaf { items, .. } => items,
1285 Node::Internal { .. } => panic!("Internal nodes have no items"),
1286 }
1287 }
1288
1289 fn is_underflowing(&self) -> bool {
1290 match self {
1291 Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
1292 Node::Leaf { items, .. } => items.len() < TREE_BASE,
1293 }
1294 }
1295}
1296
1297#[derive(Debug)]
1298pub enum Edit<T: KeyedItem> {
1299 Insert(T),
1300 Remove(T::Key),
1301}
1302
1303impl<T: KeyedItem> Edit<T> {
1304 fn key(&self) -> T::Key {
1305 match self {
1306 Edit::Insert(item) => item.key(),
1307 Edit::Remove(key) => key.clone(),
1308 }
1309 }
1310}
1311
1312fn sum<'a, T, I>(iter: I, cx: T::Context<'_>) -> T
1313where
1314 T: 'a + Summary,
1315 I: Iterator<Item = &'a T>,
1316{
1317 let mut sum = T::zero(cx);
1318 for value in iter {
1319 sum.add_summary(value, cx);
1320 }
1321 sum
1322}
1323
1324#[cfg(test)]
1325mod tests {
1326 use super::*;
1327 use rand::{distr::StandardUniform, prelude::*};
1328 use std::cmp;
1329
1330 #[ctor::ctor]
1331 fn init_logger() {
1332 zlog::init_test();
1333 }
1334
1335 #[test]
1336 fn test_extend_and_push_tree() {
1337 let mut tree1 = SumTree::default();
1338 tree1.extend(0..20, ());
1339
1340 let mut tree2 = SumTree::default();
1341 tree2.extend(50..100, ());
1342
1343 tree1.append(tree2, ());
1344 assert_eq!(tree1.items(()), (0..20).chain(50..100).collect::<Vec<u8>>());
1345 }
1346
1347 #[test]
1348 fn test_random() {
1349 let mut starting_seed = 0;
1350 if let Ok(value) = std::env::var("SEED") {
1351 starting_seed = value.parse().expect("invalid SEED variable");
1352 }
1353 let mut num_iterations = 100;
1354 if let Ok(value) = std::env::var("ITERATIONS") {
1355 num_iterations = value.parse().expect("invalid ITERATIONS variable");
1356 }
1357 let num_operations = std::env::var("OPERATIONS")
1358 .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
1359
1360 for seed in starting_seed..(starting_seed + num_iterations) {
1361 eprintln!("seed = {}", seed);
1362 let mut rng = StdRng::seed_from_u64(seed);
1363
1364 let rng = &mut rng;
1365 let mut tree = SumTree::<u8>::default();
1366 let count = rng.random_range(0..10);
1367 if rng.random() {
1368 tree.extend(rng.sample_iter(StandardUniform).take(count), ());
1369 } else {
1370 let items = rng
1371 .sample_iter(StandardUniform)
1372 .take(count)
1373 .collect::<Vec<_>>();
1374 tree.par_extend(items, ());
1375 }
1376
1377 for _ in 0..num_operations {
1378 let splice_end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1379 let splice_start = rng.random_range(0..splice_end + 1);
1380 let count = rng.random_range(0..10);
1381 let tree_end = tree.extent::<Count>(());
1382 let new_items = rng
1383 .sample_iter(StandardUniform)
1384 .take(count)
1385 .collect::<Vec<u8>>();
1386
1387 let mut reference_items = tree.items(());
1388 reference_items.splice(splice_start..splice_end, new_items.clone());
1389
1390 tree = {
1391 let mut cursor = tree.cursor::<Count>(());
1392 let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
1393 if rng.random() {
1394 new_tree.extend(new_items, ());
1395 } else {
1396 new_tree.par_extend(new_items, ());
1397 }
1398 cursor.seek(&Count(splice_end), Bias::Right);
1399 new_tree.append(cursor.slice(&tree_end, Bias::Right), ());
1400 new_tree
1401 };
1402
1403 assert_eq!(tree.items(()), reference_items);
1404 assert_eq!(
1405 tree.iter().collect::<Vec<_>>(),
1406 tree.cursor::<()>(()).collect::<Vec<_>>()
1407 );
1408
1409 log::info!("tree items: {:?}", tree.items(()));
1410
1411 let mut filter_cursor =
1412 tree.filter::<_, Count>((), |summary| summary.contains_even);
1413 let expected_filtered_items = tree
1414 .items(())
1415 .into_iter()
1416 .enumerate()
1417 .filter(|(_, item)| (item & 1) == 0)
1418 .collect::<Vec<_>>();
1419
1420 let mut item_ix = if rng.random() {
1421 filter_cursor.next();
1422 0
1423 } else {
1424 filter_cursor.prev();
1425 expected_filtered_items.len().saturating_sub(1)
1426 };
1427 while item_ix < expected_filtered_items.len() {
1428 log::info!("filter_cursor, item_ix: {}", item_ix);
1429 let actual_item = filter_cursor.item().unwrap();
1430 let (reference_index, reference_item) = expected_filtered_items[item_ix];
1431 assert_eq!(actual_item, &reference_item);
1432 assert_eq!(filter_cursor.start().0, reference_index);
1433 log::info!("next");
1434 filter_cursor.next();
1435 item_ix += 1;
1436
1437 while item_ix > 0 && rng.random_bool(0.2) {
1438 log::info!("prev");
1439 filter_cursor.prev();
1440 item_ix -= 1;
1441
1442 if item_ix == 0 && rng.random_bool(0.2) {
1443 filter_cursor.prev();
1444 assert_eq!(filter_cursor.item(), None);
1445 assert_eq!(filter_cursor.start().0, 0);
1446 filter_cursor.next();
1447 }
1448 }
1449 }
1450 assert_eq!(filter_cursor.item(), None);
1451
1452 let mut before_start = false;
1453 let mut cursor = tree.cursor::<Count>(());
1454 let start_pos = rng.random_range(0..=reference_items.len());
1455 cursor.seek(&Count(start_pos), Bias::Right);
1456 let mut pos = rng.random_range(start_pos..=reference_items.len());
1457 cursor.seek_forward(&Count(pos), Bias::Right);
1458
1459 for i in 0..10 {
1460 assert_eq!(cursor.start().0, pos);
1461
1462 if pos > 0 {
1463 assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1464 } else {
1465 assert_eq!(cursor.prev_item(), None);
1466 }
1467
1468 if pos < reference_items.len() && !before_start {
1469 assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1470 } else {
1471 assert_eq!(cursor.item(), None);
1472 }
1473
1474 if before_start {
1475 assert_eq!(cursor.next_item(), reference_items.first());
1476 } else if pos + 1 < reference_items.len() {
1477 assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1478 } else {
1479 assert_eq!(cursor.next_item(), None);
1480 }
1481
1482 if i < 5 {
1483 cursor.next();
1484 if pos < reference_items.len() {
1485 pos += 1;
1486 before_start = false;
1487 }
1488 } else {
1489 cursor.prev();
1490 if pos == 0 {
1491 before_start = true;
1492 }
1493 pos = pos.saturating_sub(1);
1494 }
1495 }
1496 }
1497
1498 for _ in 0..10 {
1499 let end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1500 let start = rng.random_range(0..end + 1);
1501 let start_bias = if rng.random() {
1502 Bias::Left
1503 } else {
1504 Bias::Right
1505 };
1506 let end_bias = if rng.random() {
1507 Bias::Left
1508 } else {
1509 Bias::Right
1510 };
1511
1512 let mut cursor = tree.cursor::<Count>(());
1513 cursor.seek(&Count(start), start_bias);
1514 let slice = cursor.slice(&Count(end), end_bias);
1515
1516 cursor.seek(&Count(start), start_bias);
1517 let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1518
1519 assert_eq!(summary.0, slice.summary().sum);
1520 }
1521 }
1522 }
1523
1524 #[test]
1525 fn test_cursor() {
1526 // Empty tree
1527 let tree = SumTree::<u8>::default();
1528 let mut cursor = tree.cursor::<IntegersSummary>(());
1529 assert_eq!(
1530 cursor.slice(&Count(0), Bias::Right).items(()),
1531 Vec::<u8>::new()
1532 );
1533 assert_eq!(cursor.item(), None);
1534 assert_eq!(cursor.prev_item(), None);
1535 assert_eq!(cursor.next_item(), None);
1536 assert_eq!(cursor.start().sum, 0);
1537 cursor.prev();
1538 assert_eq!(cursor.item(), None);
1539 assert_eq!(cursor.prev_item(), None);
1540 assert_eq!(cursor.next_item(), None);
1541 assert_eq!(cursor.start().sum, 0);
1542 cursor.next();
1543 assert_eq!(cursor.item(), None);
1544 assert_eq!(cursor.prev_item(), None);
1545 assert_eq!(cursor.next_item(), None);
1546 assert_eq!(cursor.start().sum, 0);
1547
1548 // Single-element tree
1549 let mut tree = SumTree::<u8>::default();
1550 tree.extend(vec![1], ());
1551 let mut cursor = tree.cursor::<IntegersSummary>(());
1552 assert_eq!(
1553 cursor.slice(&Count(0), Bias::Right).items(()),
1554 Vec::<u8>::new()
1555 );
1556 assert_eq!(cursor.item(), Some(&1));
1557 assert_eq!(cursor.prev_item(), None);
1558 assert_eq!(cursor.next_item(), None);
1559 assert_eq!(cursor.start().sum, 0);
1560
1561 cursor.next();
1562 assert_eq!(cursor.item(), None);
1563 assert_eq!(cursor.prev_item(), Some(&1));
1564 assert_eq!(cursor.next_item(), None);
1565 assert_eq!(cursor.start().sum, 1);
1566
1567 cursor.prev();
1568 assert_eq!(cursor.item(), Some(&1));
1569 assert_eq!(cursor.prev_item(), None);
1570 assert_eq!(cursor.next_item(), None);
1571 assert_eq!(cursor.start().sum, 0);
1572
1573 let mut cursor = tree.cursor::<IntegersSummary>(());
1574 assert_eq!(cursor.slice(&Count(1), Bias::Right).items(()), [1]);
1575 assert_eq!(cursor.item(), None);
1576 assert_eq!(cursor.prev_item(), Some(&1));
1577 assert_eq!(cursor.next_item(), None);
1578 assert_eq!(cursor.start().sum, 1);
1579
1580 cursor.seek(&Count(0), Bias::Right);
1581 assert_eq!(
1582 cursor
1583 .slice(&tree.extent::<Count>(()), Bias::Right)
1584 .items(()),
1585 [1]
1586 );
1587 assert_eq!(cursor.item(), None);
1588 assert_eq!(cursor.prev_item(), Some(&1));
1589 assert_eq!(cursor.next_item(), None);
1590 assert_eq!(cursor.start().sum, 1);
1591
1592 // Multiple-element tree
1593 let mut tree = SumTree::default();
1594 tree.extend(vec![1, 2, 3, 4, 5, 6], ());
1595 let mut cursor = tree.cursor::<IntegersSummary>(());
1596
1597 assert_eq!(cursor.slice(&Count(2), Bias::Right).items(()), [1, 2]);
1598 assert_eq!(cursor.item(), Some(&3));
1599 assert_eq!(cursor.prev_item(), Some(&2));
1600 assert_eq!(cursor.next_item(), Some(&4));
1601 assert_eq!(cursor.start().sum, 3);
1602
1603 cursor.next();
1604 assert_eq!(cursor.item(), Some(&4));
1605 assert_eq!(cursor.prev_item(), Some(&3));
1606 assert_eq!(cursor.next_item(), Some(&5));
1607 assert_eq!(cursor.start().sum, 6);
1608
1609 cursor.next();
1610 assert_eq!(cursor.item(), Some(&5));
1611 assert_eq!(cursor.prev_item(), Some(&4));
1612 assert_eq!(cursor.next_item(), Some(&6));
1613 assert_eq!(cursor.start().sum, 10);
1614
1615 cursor.next();
1616 assert_eq!(cursor.item(), Some(&6));
1617 assert_eq!(cursor.prev_item(), Some(&5));
1618 assert_eq!(cursor.next_item(), None);
1619 assert_eq!(cursor.start().sum, 15);
1620
1621 cursor.next();
1622 cursor.next();
1623 assert_eq!(cursor.item(), None);
1624 assert_eq!(cursor.prev_item(), Some(&6));
1625 assert_eq!(cursor.next_item(), None);
1626 assert_eq!(cursor.start().sum, 21);
1627
1628 cursor.prev();
1629 assert_eq!(cursor.item(), Some(&6));
1630 assert_eq!(cursor.prev_item(), Some(&5));
1631 assert_eq!(cursor.next_item(), None);
1632 assert_eq!(cursor.start().sum, 15);
1633
1634 cursor.prev();
1635 assert_eq!(cursor.item(), Some(&5));
1636 assert_eq!(cursor.prev_item(), Some(&4));
1637 assert_eq!(cursor.next_item(), Some(&6));
1638 assert_eq!(cursor.start().sum, 10);
1639
1640 cursor.prev();
1641 assert_eq!(cursor.item(), Some(&4));
1642 assert_eq!(cursor.prev_item(), Some(&3));
1643 assert_eq!(cursor.next_item(), Some(&5));
1644 assert_eq!(cursor.start().sum, 6);
1645
1646 cursor.prev();
1647 assert_eq!(cursor.item(), Some(&3));
1648 assert_eq!(cursor.prev_item(), Some(&2));
1649 assert_eq!(cursor.next_item(), Some(&4));
1650 assert_eq!(cursor.start().sum, 3);
1651
1652 cursor.prev();
1653 assert_eq!(cursor.item(), Some(&2));
1654 assert_eq!(cursor.prev_item(), Some(&1));
1655 assert_eq!(cursor.next_item(), Some(&3));
1656 assert_eq!(cursor.start().sum, 1);
1657
1658 cursor.prev();
1659 assert_eq!(cursor.item(), Some(&1));
1660 assert_eq!(cursor.prev_item(), None);
1661 assert_eq!(cursor.next_item(), Some(&2));
1662 assert_eq!(cursor.start().sum, 0);
1663
1664 cursor.prev();
1665 assert_eq!(cursor.item(), None);
1666 assert_eq!(cursor.prev_item(), None);
1667 assert_eq!(cursor.next_item(), Some(&1));
1668 assert_eq!(cursor.start().sum, 0);
1669
1670 cursor.next();
1671 assert_eq!(cursor.item(), Some(&1));
1672 assert_eq!(cursor.prev_item(), None);
1673 assert_eq!(cursor.next_item(), Some(&2));
1674 assert_eq!(cursor.start().sum, 0);
1675
1676 let mut cursor = tree.cursor::<IntegersSummary>(());
1677 assert_eq!(
1678 cursor
1679 .slice(&tree.extent::<Count>(()), Bias::Right)
1680 .items(()),
1681 tree.items(())
1682 );
1683 assert_eq!(cursor.item(), None);
1684 assert_eq!(cursor.prev_item(), Some(&6));
1685 assert_eq!(cursor.next_item(), None);
1686 assert_eq!(cursor.start().sum, 21);
1687
1688 cursor.seek(&Count(3), Bias::Right);
1689 assert_eq!(
1690 cursor
1691 .slice(&tree.extent::<Count>(()), Bias::Right)
1692 .items(()),
1693 [4, 5, 6]
1694 );
1695 assert_eq!(cursor.item(), None);
1696 assert_eq!(cursor.prev_item(), Some(&6));
1697 assert_eq!(cursor.next_item(), None);
1698 assert_eq!(cursor.start().sum, 21);
1699
1700 // Seeking can bias left or right
1701 cursor.seek(&Count(1), Bias::Left);
1702 assert_eq!(cursor.item(), Some(&1));
1703 cursor.seek(&Count(1), Bias::Right);
1704 assert_eq!(cursor.item(), Some(&2));
1705
1706 // Slicing without resetting starts from where the cursor is parked at.
1707 cursor.seek(&Count(1), Bias::Right);
1708 assert_eq!(cursor.slice(&Count(3), Bias::Right).items(()), vec![2, 3]);
1709 assert_eq!(cursor.slice(&Count(6), Bias::Left).items(()), vec![4, 5]);
1710 assert_eq!(cursor.slice(&Count(6), Bias::Right).items(()), vec![6]);
1711 }
1712
1713 #[test]
1714 fn test_edit() {
1715 let mut tree = SumTree::<u8>::default();
1716
1717 let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], ());
1718 assert_eq!(tree.items(()), vec![0, 1, 2]);
1719 assert_eq!(removed, Vec::<u8>::new());
1720 assert_eq!(tree.get(&0, ()), Some(&0));
1721 assert_eq!(tree.get(&1, ()), Some(&1));
1722 assert_eq!(tree.get(&2, ()), Some(&2));
1723 assert_eq!(tree.get(&4, ()), None);
1724
1725 let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], ());
1726 assert_eq!(tree.items(()), vec![1, 2, 4]);
1727 assert_eq!(removed, vec![0, 2]);
1728 assert_eq!(tree.get(&0, ()), None);
1729 assert_eq!(tree.get(&1, ()), Some(&1));
1730 assert_eq!(tree.get(&2, ()), Some(&2));
1731 assert_eq!(tree.get(&4, ()), Some(&4));
1732 }
1733
1734 #[test]
1735 fn test_from_iter() {
1736 assert_eq!(
1737 SumTree::from_iter(0..100, ()).items(()),
1738 (0..100).collect::<Vec<_>>()
1739 );
1740
1741 // Ensure `from_iter` works correctly when the given iterator restarts
1742 // after calling `next` if `None` was already returned.
1743 let mut ix = 0;
1744 let iterator = std::iter::from_fn(|| {
1745 ix = (ix + 1) % 2;
1746 if ix == 1 { Some(1) } else { None }
1747 });
1748 assert_eq!(SumTree::from_iter(iterator, ()).items(()), vec![1]);
1749 }
1750
1751 #[derive(Clone, Default, Debug)]
1752 pub struct IntegersSummary {
1753 count: usize,
1754 sum: usize,
1755 contains_even: bool,
1756 max: u8,
1757 }
1758
1759 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1760 struct Count(usize);
1761
1762 #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1763 struct Sum(usize);
1764
1765 impl Item for u8 {
1766 type Summary = IntegersSummary;
1767
1768 fn summary(&self, _cx: ()) -> Self::Summary {
1769 IntegersSummary {
1770 count: 1,
1771 sum: *self as usize,
1772 contains_even: (*self & 1) == 0,
1773 max: *self,
1774 }
1775 }
1776 }
1777
1778 impl KeyedItem for u8 {
1779 type Key = u8;
1780
1781 fn key(&self) -> Self::Key {
1782 *self
1783 }
1784 }
1785
1786 impl ContextLessSummary for IntegersSummary {
1787 fn zero() -> Self {
1788 Default::default()
1789 }
1790
1791 fn add_summary(&mut self, other: &Self) {
1792 self.count += other.count;
1793 self.sum += other.sum;
1794 self.contains_even |= other.contains_even;
1795 self.max = cmp::max(self.max, other.max);
1796 }
1797 }
1798
1799 impl Dimension<'_, IntegersSummary> for u8 {
1800 fn zero(_cx: ()) -> Self {
1801 Default::default()
1802 }
1803
1804 fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1805 *self = summary.max;
1806 }
1807 }
1808
1809 impl Dimension<'_, IntegersSummary> for Count {
1810 fn zero(_cx: ()) -> Self {
1811 Default::default()
1812 }
1813
1814 fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1815 self.0 += summary.count;
1816 }
1817 }
1818
1819 impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1820 fn cmp(&self, cursor_location: &IntegersSummary, _: ()) -> Ordering {
1821 self.0.cmp(&cursor_location.count)
1822 }
1823 }
1824
1825 impl Dimension<'_, IntegersSummary> for Sum {
1826 fn zero(_cx: ()) -> Self {
1827 Default::default()
1828 }
1829
1830 fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1831 self.0 += summary.sum;
1832 }
1833 }
1834}