sum_tree.rs

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