sum_tree.rs

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