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