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