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                if cursor_item.key() == item.key() {
 679                    replaced = Some(cursor_item.clone());
 680                    cursor.next();
 681                }
 682            }
 683            new_tree.push(item, cx);
 684            new_tree.append(cursor.suffix(), cx);
 685            new_tree
 686        };
 687        replaced
 688    }
 689
 690    pub fn remove(&mut self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<T> {
 691        let mut removed = None;
 692        *self = {
 693            let mut cursor = self.cursor::<T::Key>(cx);
 694            let mut new_tree = cursor.slice(key, Bias::Left);
 695            if let Some(item) = cursor.item() {
 696                if item.key() == *key {
 697                    removed = Some(item.clone());
 698                    cursor.next();
 699                }
 700            }
 701            new_tree.append(cursor.suffix(), cx);
 702            new_tree
 703        };
 704        removed
 705    }
 706
 707    pub fn edit(
 708        &mut self,
 709        mut edits: Vec<Edit<T>>,
 710        cx: &<T::Summary as Summary>::Context,
 711    ) -> Vec<T> {
 712        if edits.is_empty() {
 713            return Vec::new();
 714        }
 715
 716        let mut removed = Vec::new();
 717        edits.sort_unstable_by_key(|item| item.key());
 718
 719        *self = {
 720            let mut cursor = self.cursor::<T::Key>(cx);
 721            let mut new_tree = SumTree::new(cx);
 722            let mut buffered_items = Vec::new();
 723
 724            cursor.seek(&T::Key::zero(cx), Bias::Left);
 725            for edit in edits {
 726                let new_key = edit.key();
 727                let mut old_item = cursor.item();
 728
 729                if old_item
 730                    .as_ref()
 731                    .map_or(false, |old_item| old_item.key() < new_key)
 732                {
 733                    new_tree.extend(buffered_items.drain(..), cx);
 734                    let slice = cursor.slice(&new_key, Bias::Left);
 735                    new_tree.append(slice, cx);
 736                    old_item = cursor.item();
 737                }
 738
 739                if let Some(old_item) = old_item {
 740                    if old_item.key() == new_key {
 741                        removed.push(old_item.clone());
 742                        cursor.next();
 743                    }
 744                }
 745
 746                match edit {
 747                    Edit::Insert(item) => {
 748                        buffered_items.push(item);
 749                    }
 750                    Edit::Remove(_) => {}
 751                }
 752            }
 753
 754            new_tree.extend(buffered_items, cx);
 755            new_tree.append(cursor.suffix(), cx);
 756            new_tree
 757        };
 758
 759        removed
 760    }
 761
 762    pub fn get<'a>(
 763        &'a self,
 764        key: &T::Key,
 765        cx: &'a <T::Summary as Summary>::Context,
 766    ) -> Option<&'a T> {
 767        let mut cursor = self.cursor::<T::Key>(cx);
 768        if cursor.seek(key, Bias::Left) {
 769            cursor.item()
 770        } else {
 771            None
 772        }
 773    }
 774}
 775
 776impl<T, S> Default for SumTree<T>
 777where
 778    T: Item<Summary = S>,
 779    S: Summary<Context = ()>,
 780{
 781    fn default() -> Self {
 782        Self::new(&())
 783    }
 784}
 785
 786#[derive(Clone)]
 787pub enum Node<T: Item> {
 788    Internal {
 789        height: u8,
 790        summary: T::Summary,
 791        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 792        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
 793    },
 794    Leaf {
 795        summary: T::Summary,
 796        items: ArrayVec<T, { 2 * TREE_BASE }>,
 797        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 798    },
 799}
 800
 801impl<T> fmt::Debug for Node<T>
 802where
 803    T: Item + fmt::Debug,
 804    T::Summary: fmt::Debug,
 805{
 806    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 807        match self {
 808            Node::Internal {
 809                height,
 810                summary,
 811                child_summaries,
 812                child_trees,
 813            } => f
 814                .debug_struct("Internal")
 815                .field("height", height)
 816                .field("summary", summary)
 817                .field("child_summaries", child_summaries)
 818                .field("child_trees", child_trees)
 819                .finish(),
 820            Node::Leaf {
 821                summary,
 822                items,
 823                item_summaries,
 824            } => f
 825                .debug_struct("Leaf")
 826                .field("summary", summary)
 827                .field("items", items)
 828                .field("item_summaries", item_summaries)
 829                .finish(),
 830        }
 831    }
 832}
 833
 834impl<T: Item> Node<T> {
 835    fn is_leaf(&self) -> bool {
 836        matches!(self, Node::Leaf { .. })
 837    }
 838
 839    fn height(&self) -> u8 {
 840        match self {
 841            Node::Internal { height, .. } => *height,
 842            Node::Leaf { .. } => 0,
 843        }
 844    }
 845
 846    fn summary(&self) -> &T::Summary {
 847        match self {
 848            Node::Internal { summary, .. } => summary,
 849            Node::Leaf { summary, .. } => summary,
 850        }
 851    }
 852
 853    fn child_summaries(&self) -> &[T::Summary] {
 854        match self {
 855            Node::Internal {
 856                child_summaries, ..
 857            } => child_summaries.as_slice(),
 858            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
 859        }
 860    }
 861
 862    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
 863        match self {
 864            Node::Internal { child_trees, .. } => child_trees,
 865            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
 866        }
 867    }
 868
 869    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
 870        match self {
 871            Node::Leaf { items, .. } => items,
 872            Node::Internal { .. } => panic!("Internal nodes have no items"),
 873        }
 874    }
 875
 876    fn is_underflowing(&self) -> bool {
 877        match self {
 878            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
 879            Node::Leaf { items, .. } => items.len() < TREE_BASE,
 880        }
 881    }
 882}
 883
 884#[derive(Debug)]
 885pub enum Edit<T: KeyedItem> {
 886    Insert(T),
 887    Remove(T::Key),
 888}
 889
 890impl<T: KeyedItem> Edit<T> {
 891    fn key(&self) -> T::Key {
 892        match self {
 893            Edit::Insert(item) => item.key(),
 894            Edit::Remove(key) => key.clone(),
 895        }
 896    }
 897}
 898
 899fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
 900where
 901    T: 'a + Summary,
 902    I: Iterator<Item = &'a T>,
 903{
 904    let mut sum = T::zero(cx);
 905    for value in iter {
 906        sum.add_summary(value, cx);
 907    }
 908    sum
 909}
 910
 911#[cfg(test)]
 912mod tests {
 913    use super::*;
 914    use rand::{distributions, prelude::*};
 915    use std::cmp;
 916
 917    #[ctor::ctor]
 918    fn init_logger() {
 919        zlog::init_test();
 920    }
 921
 922    #[test]
 923    fn test_extend_and_push_tree() {
 924        let mut tree1 = SumTree::default();
 925        tree1.extend(0..20, &());
 926
 927        let mut tree2 = SumTree::default();
 928        tree2.extend(50..100, &());
 929
 930        tree1.append(tree2, &());
 931        assert_eq!(
 932            tree1.items(&()),
 933            (0..20).chain(50..100).collect::<Vec<u8>>()
 934        );
 935    }
 936
 937    #[test]
 938    fn test_random() {
 939        let mut starting_seed = 0;
 940        if let Ok(value) = std::env::var("SEED") {
 941            starting_seed = value.parse().expect("invalid SEED variable");
 942        }
 943        let mut num_iterations = 100;
 944        if let Ok(value) = std::env::var("ITERATIONS") {
 945            num_iterations = value.parse().expect("invalid ITERATIONS variable");
 946        }
 947        let num_operations = std::env::var("OPERATIONS")
 948            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
 949
 950        for seed in starting_seed..(starting_seed + num_iterations) {
 951            eprintln!("seed = {}", seed);
 952            let mut rng = StdRng::seed_from_u64(seed);
 953
 954            let rng = &mut rng;
 955            let mut tree = SumTree::<u8>::default();
 956            let count = rng.gen_range(0..10);
 957            if rng.r#gen() {
 958                tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
 959            } else {
 960                let items = rng
 961                    .sample_iter(distributions::Standard)
 962                    .take(count)
 963                    .collect::<Vec<_>>();
 964                tree.par_extend(items, &());
 965            }
 966
 967            for _ in 0..num_operations {
 968                let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 969                let splice_start = rng.gen_range(0..splice_end + 1);
 970                let count = rng.gen_range(0..10);
 971                let tree_end = tree.extent::<Count>(&());
 972                let new_items = rng
 973                    .sample_iter(distributions::Standard)
 974                    .take(count)
 975                    .collect::<Vec<u8>>();
 976
 977                let mut reference_items = tree.items(&());
 978                reference_items.splice(splice_start..splice_end, new_items.clone());
 979
 980                tree = {
 981                    let mut cursor = tree.cursor::<Count>(&());
 982                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
 983                    if rng.r#gen() {
 984                        new_tree.extend(new_items, &());
 985                    } else {
 986                        new_tree.par_extend(new_items, &());
 987                    }
 988                    cursor.seek(&Count(splice_end), Bias::Right);
 989                    new_tree.append(cursor.slice(&tree_end, Bias::Right), &());
 990                    new_tree
 991                };
 992
 993                assert_eq!(tree.items(&()), reference_items);
 994                assert_eq!(
 995                    tree.iter().collect::<Vec<_>>(),
 996                    tree.cursor::<()>(&()).collect::<Vec<_>>()
 997                );
 998
 999                log::info!("tree items: {:?}", tree.items(&()));
1000
1001                let mut filter_cursor =
1002                    tree.filter::<_, Count>(&(), |summary| summary.contains_even);
1003                let expected_filtered_items = tree
1004                    .items(&())
1005                    .into_iter()
1006                    .enumerate()
1007                    .filter(|(_, item)| (item & 1) == 0)
1008                    .collect::<Vec<_>>();
1009
1010                let mut item_ix = if rng.r#gen() {
1011                    filter_cursor.next();
1012                    0
1013                } else {
1014                    filter_cursor.prev();
1015                    expected_filtered_items.len().saturating_sub(1)
1016                };
1017                while item_ix < expected_filtered_items.len() {
1018                    log::info!("filter_cursor, item_ix: {}", item_ix);
1019                    let actual_item = filter_cursor.item().unwrap();
1020                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
1021                    assert_eq!(actual_item, &reference_item);
1022                    assert_eq!(filter_cursor.start().0, reference_index);
1023                    log::info!("next");
1024                    filter_cursor.next();
1025                    item_ix += 1;
1026
1027                    while item_ix > 0 && rng.gen_bool(0.2) {
1028                        log::info!("prev");
1029                        filter_cursor.prev();
1030                        item_ix -= 1;
1031
1032                        if item_ix == 0 && rng.gen_bool(0.2) {
1033                            filter_cursor.prev();
1034                            assert_eq!(filter_cursor.item(), None);
1035                            assert_eq!(filter_cursor.start().0, 0);
1036                            filter_cursor.next();
1037                        }
1038                    }
1039                }
1040                assert_eq!(filter_cursor.item(), None);
1041
1042                let mut before_start = false;
1043                let mut cursor = tree.cursor::<Count>(&());
1044                let start_pos = rng.gen_range(0..=reference_items.len());
1045                cursor.seek(&Count(start_pos), Bias::Right);
1046                let mut pos = rng.gen_range(start_pos..=reference_items.len());
1047                cursor.seek_forward(&Count(pos), Bias::Right);
1048
1049                for i in 0..10 {
1050                    assert_eq!(cursor.start().0, pos);
1051
1052                    if pos > 0 {
1053                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1054                    } else {
1055                        assert_eq!(cursor.prev_item(), None);
1056                    }
1057
1058                    if pos < reference_items.len() && !before_start {
1059                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1060                    } else {
1061                        assert_eq!(cursor.item(), None);
1062                    }
1063
1064                    if before_start {
1065                        assert_eq!(cursor.next_item(), reference_items.first());
1066                    } else if pos + 1 < reference_items.len() {
1067                        assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1068                    } else {
1069                        assert_eq!(cursor.next_item(), None);
1070                    }
1071
1072                    if i < 5 {
1073                        cursor.next();
1074                        if pos < reference_items.len() {
1075                            pos += 1;
1076                            before_start = false;
1077                        }
1078                    } else {
1079                        cursor.prev();
1080                        if pos == 0 {
1081                            before_start = true;
1082                        }
1083                        pos = pos.saturating_sub(1);
1084                    }
1085                }
1086            }
1087
1088            for _ in 0..10 {
1089                let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
1090                let start = rng.gen_range(0..end + 1);
1091                let start_bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
1092                let end_bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
1093
1094                let mut cursor = tree.cursor::<Count>(&());
1095                cursor.seek(&Count(start), start_bias);
1096                let slice = cursor.slice(&Count(end), end_bias);
1097
1098                cursor.seek(&Count(start), start_bias);
1099                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1100
1101                assert_eq!(summary.0, slice.summary().sum);
1102            }
1103        }
1104    }
1105
1106    #[test]
1107    fn test_cursor() {
1108        // Empty tree
1109        let tree = SumTree::<u8>::default();
1110        let mut cursor = tree.cursor::<IntegersSummary>(&());
1111        assert_eq!(
1112            cursor.slice(&Count(0), Bias::Right).items(&()),
1113            Vec::<u8>::new()
1114        );
1115        assert_eq!(cursor.item(), None);
1116        assert_eq!(cursor.prev_item(), None);
1117        assert_eq!(cursor.next_item(), None);
1118        assert_eq!(cursor.start().sum, 0);
1119        cursor.prev();
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.next();
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
1130        // Single-element tree
1131        let mut tree = SumTree::<u8>::default();
1132        tree.extend(vec![1], &());
1133        let mut cursor = tree.cursor::<IntegersSummary>(&());
1134        assert_eq!(
1135            cursor.slice(&Count(0), Bias::Right).items(&()),
1136            Vec::<u8>::new()
1137        );
1138        assert_eq!(cursor.item(), Some(&1));
1139        assert_eq!(cursor.prev_item(), None);
1140        assert_eq!(cursor.next_item(), None);
1141        assert_eq!(cursor.start().sum, 0);
1142
1143        cursor.next();
1144        assert_eq!(cursor.item(), None);
1145        assert_eq!(cursor.prev_item(), Some(&1));
1146        assert_eq!(cursor.next_item(), None);
1147        assert_eq!(cursor.start().sum, 1);
1148
1149        cursor.prev();
1150        assert_eq!(cursor.item(), Some(&1));
1151        assert_eq!(cursor.prev_item(), None);
1152        assert_eq!(cursor.next_item(), None);
1153        assert_eq!(cursor.start().sum, 0);
1154
1155        let mut cursor = tree.cursor::<IntegersSummary>(&());
1156        assert_eq!(cursor.slice(&Count(1), Bias::Right).items(&()), [1]);
1157        assert_eq!(cursor.item(), None);
1158        assert_eq!(cursor.prev_item(), Some(&1));
1159        assert_eq!(cursor.next_item(), None);
1160        assert_eq!(cursor.start().sum, 1);
1161
1162        cursor.seek(&Count(0), Bias::Right);
1163        assert_eq!(
1164            cursor
1165                .slice(&tree.extent::<Count>(&()), Bias::Right)
1166                .items(&()),
1167            [1]
1168        );
1169        assert_eq!(cursor.item(), None);
1170        assert_eq!(cursor.prev_item(), Some(&1));
1171        assert_eq!(cursor.next_item(), None);
1172        assert_eq!(cursor.start().sum, 1);
1173
1174        // Multiple-element tree
1175        let mut tree = SumTree::default();
1176        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
1177        let mut cursor = tree.cursor::<IntegersSummary>(&());
1178
1179        assert_eq!(cursor.slice(&Count(2), Bias::Right).items(&()), [1, 2]);
1180        assert_eq!(cursor.item(), Some(&3));
1181        assert_eq!(cursor.prev_item(), Some(&2));
1182        assert_eq!(cursor.next_item(), Some(&4));
1183        assert_eq!(cursor.start().sum, 3);
1184
1185        cursor.next();
1186        assert_eq!(cursor.item(), Some(&4));
1187        assert_eq!(cursor.prev_item(), Some(&3));
1188        assert_eq!(cursor.next_item(), Some(&5));
1189        assert_eq!(cursor.start().sum, 6);
1190
1191        cursor.next();
1192        assert_eq!(cursor.item(), Some(&5));
1193        assert_eq!(cursor.prev_item(), Some(&4));
1194        assert_eq!(cursor.next_item(), Some(&6));
1195        assert_eq!(cursor.start().sum, 10);
1196
1197        cursor.next();
1198        assert_eq!(cursor.item(), Some(&6));
1199        assert_eq!(cursor.prev_item(), Some(&5));
1200        assert_eq!(cursor.next_item(), None);
1201        assert_eq!(cursor.start().sum, 15);
1202
1203        cursor.next();
1204        cursor.next();
1205        assert_eq!(cursor.item(), None);
1206        assert_eq!(cursor.prev_item(), Some(&6));
1207        assert_eq!(cursor.next_item(), None);
1208        assert_eq!(cursor.start().sum, 21);
1209
1210        cursor.prev();
1211        assert_eq!(cursor.item(), Some(&6));
1212        assert_eq!(cursor.prev_item(), Some(&5));
1213        assert_eq!(cursor.next_item(), None);
1214        assert_eq!(cursor.start().sum, 15);
1215
1216        cursor.prev();
1217        assert_eq!(cursor.item(), Some(&5));
1218        assert_eq!(cursor.prev_item(), Some(&4));
1219        assert_eq!(cursor.next_item(), Some(&6));
1220        assert_eq!(cursor.start().sum, 10);
1221
1222        cursor.prev();
1223        assert_eq!(cursor.item(), Some(&4));
1224        assert_eq!(cursor.prev_item(), Some(&3));
1225        assert_eq!(cursor.next_item(), Some(&5));
1226        assert_eq!(cursor.start().sum, 6);
1227
1228        cursor.prev();
1229        assert_eq!(cursor.item(), Some(&3));
1230        assert_eq!(cursor.prev_item(), Some(&2));
1231        assert_eq!(cursor.next_item(), Some(&4));
1232        assert_eq!(cursor.start().sum, 3);
1233
1234        cursor.prev();
1235        assert_eq!(cursor.item(), Some(&2));
1236        assert_eq!(cursor.prev_item(), Some(&1));
1237        assert_eq!(cursor.next_item(), Some(&3));
1238        assert_eq!(cursor.start().sum, 1);
1239
1240        cursor.prev();
1241        assert_eq!(cursor.item(), Some(&1));
1242        assert_eq!(cursor.prev_item(), None);
1243        assert_eq!(cursor.next_item(), Some(&2));
1244        assert_eq!(cursor.start().sum, 0);
1245
1246        cursor.prev();
1247        assert_eq!(cursor.item(), None);
1248        assert_eq!(cursor.prev_item(), None);
1249        assert_eq!(cursor.next_item(), Some(&1));
1250        assert_eq!(cursor.start().sum, 0);
1251
1252        cursor.next();
1253        assert_eq!(cursor.item(), Some(&1));
1254        assert_eq!(cursor.prev_item(), None);
1255        assert_eq!(cursor.next_item(), Some(&2));
1256        assert_eq!(cursor.start().sum, 0);
1257
1258        let mut cursor = tree.cursor::<IntegersSummary>(&());
1259        assert_eq!(
1260            cursor
1261                .slice(&tree.extent::<Count>(&()), Bias::Right)
1262                .items(&()),
1263            tree.items(&())
1264        );
1265        assert_eq!(cursor.item(), None);
1266        assert_eq!(cursor.prev_item(), Some(&6));
1267        assert_eq!(cursor.next_item(), None);
1268        assert_eq!(cursor.start().sum, 21);
1269
1270        cursor.seek(&Count(3), Bias::Right);
1271        assert_eq!(
1272            cursor
1273                .slice(&tree.extent::<Count>(&()), Bias::Right)
1274                .items(&()),
1275            [4, 5, 6]
1276        );
1277        assert_eq!(cursor.item(), None);
1278        assert_eq!(cursor.prev_item(), Some(&6));
1279        assert_eq!(cursor.next_item(), None);
1280        assert_eq!(cursor.start().sum, 21);
1281
1282        // Seeking can bias left or right
1283        cursor.seek(&Count(1), Bias::Left);
1284        assert_eq!(cursor.item(), Some(&1));
1285        cursor.seek(&Count(1), Bias::Right);
1286        assert_eq!(cursor.item(), Some(&2));
1287
1288        // Slicing without resetting starts from where the cursor is parked at.
1289        cursor.seek(&Count(1), Bias::Right);
1290        assert_eq!(cursor.slice(&Count(3), Bias::Right).items(&()), vec![2, 3]);
1291        assert_eq!(cursor.slice(&Count(6), Bias::Left).items(&()), vec![4, 5]);
1292        assert_eq!(cursor.slice(&Count(6), Bias::Right).items(&()), vec![6]);
1293    }
1294
1295    #[test]
1296    fn test_edit() {
1297        let mut tree = SumTree::<u8>::default();
1298
1299        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1300        assert_eq!(tree.items(&()), vec![0, 1, 2]);
1301        assert_eq!(removed, Vec::<u8>::new());
1302        assert_eq!(tree.get(&0, &()), Some(&0));
1303        assert_eq!(tree.get(&1, &()), Some(&1));
1304        assert_eq!(tree.get(&2, &()), Some(&2));
1305        assert_eq!(tree.get(&4, &()), None);
1306
1307        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1308        assert_eq!(tree.items(&()), vec![1, 2, 4]);
1309        assert_eq!(removed, vec![0, 2]);
1310        assert_eq!(tree.get(&0, &()), None);
1311        assert_eq!(tree.get(&1, &()), Some(&1));
1312        assert_eq!(tree.get(&2, &()), Some(&2));
1313        assert_eq!(tree.get(&4, &()), Some(&4));
1314    }
1315
1316    #[test]
1317    fn test_from_iter() {
1318        assert_eq!(
1319            SumTree::from_iter(0..100, &()).items(&()),
1320            (0..100).collect::<Vec<_>>()
1321        );
1322
1323        // Ensure `from_iter` works correctly when the given iterator restarts
1324        // after calling `next` if `None` was already returned.
1325        let mut ix = 0;
1326        let iterator = std::iter::from_fn(|| {
1327            ix = (ix + 1) % 2;
1328            if ix == 1 { Some(1) } else { None }
1329        });
1330        assert_eq!(SumTree::from_iter(iterator, &()).items(&()), vec![1]);
1331    }
1332
1333    #[derive(Clone, Default, Debug)]
1334    pub struct IntegersSummary {
1335        count: usize,
1336        sum: usize,
1337        contains_even: bool,
1338        max: u8,
1339    }
1340
1341    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1342    struct Count(usize);
1343
1344    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1345    struct Sum(usize);
1346
1347    impl Item for u8 {
1348        type Summary = IntegersSummary;
1349
1350        fn summary(&self, _cx: &()) -> Self::Summary {
1351            IntegersSummary {
1352                count: 1,
1353                sum: *self as usize,
1354                contains_even: (*self & 1) == 0,
1355                max: *self,
1356            }
1357        }
1358    }
1359
1360    impl KeyedItem for u8 {
1361        type Key = u8;
1362
1363        fn key(&self) -> Self::Key {
1364            *self
1365        }
1366    }
1367
1368    impl Summary for IntegersSummary {
1369        type Context = ();
1370
1371        fn zero(_cx: &()) -> Self {
1372            Default::default()
1373        }
1374
1375        fn add_summary(&mut self, other: &Self, _: &()) {
1376            self.count += other.count;
1377            self.sum += other.sum;
1378            self.contains_even |= other.contains_even;
1379            self.max = cmp::max(self.max, other.max);
1380        }
1381    }
1382
1383    impl Dimension<'_, IntegersSummary> for u8 {
1384        fn zero(_cx: &()) -> Self {
1385            Default::default()
1386        }
1387
1388        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1389            *self = summary.max;
1390        }
1391    }
1392
1393    impl Dimension<'_, IntegersSummary> for Count {
1394        fn zero(_cx: &()) -> Self {
1395            Default::default()
1396        }
1397
1398        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1399            self.0 += summary.count;
1400        }
1401    }
1402
1403    impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1404        fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1405            self.0.cmp(&cursor_location.count)
1406        }
1407    }
1408
1409    impl Dimension<'_, IntegersSummary> for Sum {
1410        fn zero(_cx: &()) -> Self {
1411            Default::default()
1412        }
1413
1414        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1415            self.0 += summary.sum;
1416        }
1417    }
1418}