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