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, summary: &Self, cx: &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
 926fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
 927where
 928    T: 'a + Summary,
 929    I: Iterator<Item = &'a T>,
 930{
 931    let mut sum = T::zero(cx);
 932    for value in iter {
 933        sum.add_summary(value, cx);
 934    }
 935    sum
 936}
 937
 938#[cfg(test)]
 939mod tests {
 940    use super::*;
 941    use rand::{distributions, prelude::*};
 942    use std::cmp;
 943
 944    #[ctor::ctor]
 945    fn init_logger() {
 946        zlog::init_test();
 947    }
 948
 949    #[test]
 950    fn test_extend_and_push_tree() {
 951        let mut tree1 = SumTree::default();
 952        tree1.extend(0..20, &());
 953
 954        let mut tree2 = SumTree::default();
 955        tree2.extend(50..100, &());
 956
 957        tree1.append(tree2, &());
 958        assert_eq!(
 959            tree1.items(&()),
 960            (0..20).chain(50..100).collect::<Vec<u8>>()
 961        );
 962    }
 963
 964    #[test]
 965    fn test_random() {
 966        let mut starting_seed = 0;
 967        if let Ok(value) = std::env::var("SEED") {
 968            starting_seed = value.parse().expect("invalid SEED variable");
 969        }
 970        let mut num_iterations = 100;
 971        if let Ok(value) = std::env::var("ITERATIONS") {
 972            num_iterations = value.parse().expect("invalid ITERATIONS variable");
 973        }
 974        let num_operations = std::env::var("OPERATIONS")
 975            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
 976
 977        for seed in starting_seed..(starting_seed + num_iterations) {
 978            eprintln!("seed = {}", seed);
 979            let mut rng = StdRng::seed_from_u64(seed);
 980
 981            let rng = &mut rng;
 982            let mut tree = SumTree::<u8>::default();
 983            let count = rng.gen_range(0..10);
 984            if rng.r#gen() {
 985                tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
 986            } else {
 987                let items = rng
 988                    .sample_iter(distributions::Standard)
 989                    .take(count)
 990                    .collect::<Vec<_>>();
 991                tree.par_extend(items, &());
 992            }
 993
 994            for _ in 0..num_operations {
 995                let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 996                let splice_start = rng.gen_range(0..splice_end + 1);
 997                let count = rng.gen_range(0..10);
 998                let tree_end = tree.extent::<Count>(&());
 999                let new_items = rng
1000                    .sample_iter(distributions::Standard)
1001                    .take(count)
1002                    .collect::<Vec<u8>>();
1003
1004                let mut reference_items = tree.items(&());
1005                reference_items.splice(splice_start..splice_end, new_items.clone());
1006
1007                tree = {
1008                    let mut cursor = tree.cursor::<Count>(&());
1009                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
1010                    if rng.r#gen() {
1011                        new_tree.extend(new_items, &());
1012                    } else {
1013                        new_tree.par_extend(new_items, &());
1014                    }
1015                    cursor.seek(&Count(splice_end), Bias::Right);
1016                    new_tree.append(cursor.slice(&tree_end, Bias::Right), &());
1017                    new_tree
1018                };
1019
1020                assert_eq!(tree.items(&()), reference_items);
1021                assert_eq!(
1022                    tree.iter().collect::<Vec<_>>(),
1023                    tree.cursor::<()>(&()).collect::<Vec<_>>()
1024                );
1025
1026                log::info!("tree items: {:?}", tree.items(&()));
1027
1028                let mut filter_cursor =
1029                    tree.filter::<_, Count>(&(), |summary| summary.contains_even.cmp(&false));
1030                let expected_filtered_items = tree
1031                    .items(&())
1032                    .into_iter()
1033                    .enumerate()
1034                    .filter(|(_, item)| (item & 1) == 0)
1035                    .collect::<Vec<_>>();
1036
1037                let mut item_ix = if rng.r#gen() {
1038                    filter_cursor.next();
1039                    0
1040                } else {
1041                    filter_cursor.prev();
1042                    expected_filtered_items.len().saturating_sub(1)
1043                };
1044                while item_ix < expected_filtered_items.len() {
1045                    log::info!("filter_cursor, item_ix: {}", item_ix);
1046                    let actual_item = filter_cursor.item().unwrap();
1047                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
1048                    assert_eq!(actual_item, &reference_item);
1049                    assert_eq!(filter_cursor.start().0, reference_index);
1050                    log::info!("next");
1051                    filter_cursor.next();
1052                    item_ix += 1;
1053
1054                    while item_ix > 0 && rng.gen_bool(0.2) {
1055                        log::info!("prev");
1056                        filter_cursor.prev();
1057                        item_ix -= 1;
1058
1059                        if item_ix == 0 && rng.gen_bool(0.2) {
1060                            filter_cursor.prev();
1061                            assert_eq!(filter_cursor.item(), None);
1062                            assert_eq!(filter_cursor.start().0, 0);
1063                            filter_cursor.next();
1064                        }
1065                    }
1066                }
1067                assert_eq!(filter_cursor.item(), None);
1068
1069                let mut before_start = false;
1070                let mut cursor = tree.cursor::<Count>(&());
1071                let start_pos = rng.gen_range(0..=reference_items.len());
1072                cursor.seek(&Count(start_pos), Bias::Right);
1073                let mut pos = rng.gen_range(start_pos..=reference_items.len());
1074                cursor.seek_forward(&Count(pos), Bias::Right);
1075
1076                for i in 0..10 {
1077                    assert_eq!(cursor.start().0, pos);
1078
1079                    if pos > 0 {
1080                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1081                    } else {
1082                        assert_eq!(cursor.prev_item(), None);
1083                    }
1084
1085                    if pos < reference_items.len() && !before_start {
1086                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1087                    } else {
1088                        assert_eq!(cursor.item(), None);
1089                    }
1090
1091                    if before_start {
1092                        assert_eq!(cursor.next_item(), reference_items.first());
1093                    } else if pos + 1 < reference_items.len() {
1094                        assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1095                    } else {
1096                        assert_eq!(cursor.next_item(), None);
1097                    }
1098
1099                    if i < 5 {
1100                        cursor.next();
1101                        if pos < reference_items.len() {
1102                            pos += 1;
1103                            before_start = false;
1104                        }
1105                    } else {
1106                        cursor.prev();
1107                        if pos == 0 {
1108                            before_start = true;
1109                        }
1110                        pos = pos.saturating_sub(1);
1111                    }
1112                }
1113            }
1114
1115            for _ in 0..10 {
1116                let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
1117                let start = rng.gen_range(0..end + 1);
1118                let start_bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
1119                let end_bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
1120
1121                let mut cursor = tree.cursor::<Count>(&());
1122                cursor.seek(&Count(start), start_bias);
1123                let slice = cursor.slice(&Count(end), end_bias);
1124
1125                cursor.seek(&Count(start), start_bias);
1126                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1127
1128                assert_eq!(summary.0, slice.0.summary_or_zero(&()).sum);
1129            }
1130        }
1131    }
1132
1133    #[test]
1134    fn test_cursor() {
1135        // Empty tree
1136        let tree = SumTree::<u8>::default();
1137        let mut cursor = tree.cursor::<IntegersSummary>(&());
1138        assert_eq!(
1139            cursor.slice(&Count(0), Bias::Right).items(&()),
1140            Vec::<u8>::new()
1141        );
1142        assert_eq!(cursor.item(), None);
1143        assert_eq!(cursor.prev_item(), None);
1144        assert_eq!(cursor.next_item(), None);
1145        assert_eq!(cursor.start().sum, 0);
1146        cursor.prev();
1147        assert_eq!(cursor.item(), None);
1148        assert_eq!(cursor.prev_item(), None);
1149        assert_eq!(cursor.next_item(), None);
1150        assert_eq!(cursor.start().sum, 0);
1151        cursor.next();
1152        assert_eq!(cursor.item(), None);
1153        assert_eq!(cursor.prev_item(), None);
1154        assert_eq!(cursor.next_item(), None);
1155        assert_eq!(cursor.start().sum, 0);
1156
1157        // Single-element tree
1158        let mut tree = SumTree::<u8>::default();
1159        tree.extend(vec![1], &());
1160        let mut cursor = tree.cursor::<IntegersSummary>(&());
1161        assert_eq!(
1162            cursor.slice(&Count(0), Bias::Right).items(&()),
1163            Vec::<u8>::new()
1164        );
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        cursor.next();
1171        assert_eq!(cursor.item(), None);
1172        assert_eq!(cursor.prev_item(), Some(&1));
1173        assert_eq!(cursor.next_item(), None);
1174        assert_eq!(cursor.start().sum, 1);
1175
1176        cursor.prev();
1177        assert_eq!(cursor.item(), Some(&1));
1178        assert_eq!(cursor.prev_item(), None);
1179        assert_eq!(cursor.next_item(), None);
1180        assert_eq!(cursor.start().sum, 0);
1181
1182        let mut cursor = tree.cursor::<IntegersSummary>(&());
1183        assert_eq!(cursor.slice(&Count(1), Bias::Right).items(&()), [1]);
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        cursor.seek(&Count(0), Bias::Right);
1190        assert_eq!(
1191            cursor
1192                .slice(&tree.extent::<Count>(&()), Bias::Right)
1193                .items(&()),
1194            [1]
1195        );
1196        assert_eq!(cursor.item(), None);
1197        assert_eq!(cursor.prev_item(), Some(&1));
1198        assert_eq!(cursor.next_item(), None);
1199        assert_eq!(cursor.start().sum, 1);
1200
1201        // Multiple-element tree
1202        let mut tree = SumTree::default();
1203        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
1204        let mut cursor = tree.cursor::<IntegersSummary>(&());
1205
1206        assert_eq!(cursor.slice(&Count(2), Bias::Right).items(&()), [1, 2]);
1207        assert_eq!(cursor.item(), Some(&3));
1208        assert_eq!(cursor.prev_item(), Some(&2));
1209        assert_eq!(cursor.next_item(), Some(&4));
1210        assert_eq!(cursor.start().sum, 3);
1211
1212        cursor.next();
1213        assert_eq!(cursor.item(), Some(&4));
1214        assert_eq!(cursor.prev_item(), Some(&3));
1215        assert_eq!(cursor.next_item(), Some(&5));
1216        assert_eq!(cursor.start().sum, 6);
1217
1218        cursor.next();
1219        assert_eq!(cursor.item(), Some(&5));
1220        assert_eq!(cursor.prev_item(), Some(&4));
1221        assert_eq!(cursor.next_item(), Some(&6));
1222        assert_eq!(cursor.start().sum, 10);
1223
1224        cursor.next();
1225        assert_eq!(cursor.item(), Some(&6));
1226        assert_eq!(cursor.prev_item(), Some(&5));
1227        assert_eq!(cursor.next_item(), None);
1228        assert_eq!(cursor.start().sum, 15);
1229
1230        cursor.next();
1231        cursor.next();
1232        assert_eq!(cursor.item(), None);
1233        assert_eq!(cursor.prev_item(), Some(&6));
1234        assert_eq!(cursor.next_item(), None);
1235        assert_eq!(cursor.start().sum, 21);
1236
1237        cursor.prev();
1238        assert_eq!(cursor.item(), Some(&6));
1239        assert_eq!(cursor.prev_item(), Some(&5));
1240        assert_eq!(cursor.next_item(), None);
1241        assert_eq!(cursor.start().sum, 15);
1242
1243        cursor.prev();
1244        assert_eq!(cursor.item(), Some(&5));
1245        assert_eq!(cursor.prev_item(), Some(&4));
1246        assert_eq!(cursor.next_item(), Some(&6));
1247        assert_eq!(cursor.start().sum, 10);
1248
1249        cursor.prev();
1250        assert_eq!(cursor.item(), Some(&4));
1251        assert_eq!(cursor.prev_item(), Some(&3));
1252        assert_eq!(cursor.next_item(), Some(&5));
1253        assert_eq!(cursor.start().sum, 6);
1254
1255        cursor.prev();
1256        assert_eq!(cursor.item(), Some(&3));
1257        assert_eq!(cursor.prev_item(), Some(&2));
1258        assert_eq!(cursor.next_item(), Some(&4));
1259        assert_eq!(cursor.start().sum, 3);
1260
1261        cursor.prev();
1262        assert_eq!(cursor.item(), Some(&2));
1263        assert_eq!(cursor.prev_item(), Some(&1));
1264        assert_eq!(cursor.next_item(), Some(&3));
1265        assert_eq!(cursor.start().sum, 1);
1266
1267        cursor.prev();
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        cursor.prev();
1274        assert_eq!(cursor.item(), None);
1275        assert_eq!(cursor.prev_item(), None);
1276        assert_eq!(cursor.next_item(), Some(&1));
1277        assert_eq!(cursor.start().sum, 0);
1278
1279        cursor.next();
1280        assert_eq!(cursor.item(), Some(&1));
1281        assert_eq!(cursor.prev_item(), None);
1282        assert_eq!(cursor.next_item(), Some(&2));
1283        assert_eq!(cursor.start().sum, 0);
1284
1285        let mut cursor = tree.cursor::<IntegersSummary>(&());
1286        assert_eq!(
1287            cursor
1288                .slice(&tree.extent::<Count>(&()), Bias::Right)
1289                .items(&()),
1290            tree.items(&())
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        cursor.seek(&Count(3), Bias::Right);
1298        assert_eq!(
1299            cursor
1300                .slice(&tree.extent::<Count>(&()), Bias::Right)
1301                .items(&()),
1302            [4, 5, 6]
1303        );
1304        assert_eq!(cursor.item(), None);
1305        assert_eq!(cursor.prev_item(), Some(&6));
1306        assert_eq!(cursor.next_item(), None);
1307        assert_eq!(cursor.start().sum, 21);
1308
1309        // Seeking can bias left or right
1310        cursor.seek(&Count(1), Bias::Left);
1311        assert_eq!(cursor.item(), Some(&1));
1312        cursor.seek(&Count(1), Bias::Right);
1313        assert_eq!(cursor.item(), Some(&2));
1314
1315        // Slicing without resetting starts from where the cursor is parked at.
1316        cursor.seek(&Count(1), Bias::Right);
1317        assert_eq!(cursor.slice(&Count(3), Bias::Right).items(&()), vec![2, 3]);
1318        assert_eq!(cursor.slice(&Count(6), Bias::Left).items(&()), vec![4, 5]);
1319        assert_eq!(cursor.slice(&Count(6), Bias::Right).items(&()), vec![6]);
1320    }
1321
1322    #[test]
1323    fn test_edit() {
1324        let mut tree = SumTree::<u8>::default();
1325
1326        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1327        assert_eq!(tree.items(&()), vec![0, 1, 2]);
1328        assert_eq!(removed, Vec::<u8>::new());
1329        assert_eq!(tree.get(&0, &()), Some(&0));
1330        assert_eq!(tree.get(&1, &()), Some(&1));
1331        assert_eq!(tree.get(&2, &()), Some(&2));
1332        assert_eq!(tree.get(&4, &()), None);
1333
1334        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1335        assert_eq!(tree.items(&()), vec![1, 2, 4]);
1336        assert_eq!(removed, vec![0, 2]);
1337        assert_eq!(tree.get(&0, &()), None);
1338        assert_eq!(tree.get(&1, &()), Some(&1));
1339        assert_eq!(tree.get(&2, &()), Some(&2));
1340        assert_eq!(tree.get(&4, &()), Some(&4));
1341    }
1342
1343    #[test]
1344    fn test_from_iter() {
1345        assert_eq!(
1346            SumTree::from_iter(0..100, &()).items(&()),
1347            (0..100).collect::<Vec<_>>()
1348        );
1349
1350        // Ensure `from_iter` works correctly when the given iterator restarts
1351        // after calling `next` if `None` was already returned.
1352        let mut ix = 0;
1353        let iterator = std::iter::from_fn(|| {
1354            ix = (ix + 1) % 2;
1355            if ix == 1 { Some(1) } else { None }
1356        });
1357        assert_eq!(SumTree::from_iter(iterator, &()).items(&()), vec![1]);
1358    }
1359
1360    #[derive(Clone, Default, Debug)]
1361    pub struct IntegersSummary {
1362        count: usize,
1363        sum: usize,
1364        contains_even: bool,
1365        max: u8,
1366    }
1367
1368    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1369    struct Count(usize);
1370
1371    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1372    struct Sum(usize);
1373
1374    impl Item for u8 {
1375        type Summary = IntegersSummary;
1376
1377        fn summary(&self, _cx: &()) -> Self::Summary {
1378            IntegersSummary {
1379                count: 1,
1380                sum: *self as usize,
1381                contains_even: (*self & 1) == 0,
1382                max: *self,
1383            }
1384        }
1385    }
1386
1387    impl KeyedItem for u8 {
1388        type Key = u8;
1389
1390        fn key(&self) -> Self::Key {
1391            *self
1392        }
1393    }
1394
1395    impl Summary for IntegersSummary {
1396        type Context = ();
1397
1398        fn zero(_cx: &()) -> Self {
1399            Default::default()
1400        }
1401
1402        fn add_summary(&mut self, other: &Self, _: &()) {
1403            self.count += other.count;
1404            self.sum += other.sum;
1405            self.contains_even |= other.contains_even;
1406            self.max = cmp::max(self.max, other.max);
1407        }
1408    }
1409
1410    impl Dimension<'_, IntegersSummary> for u8 {
1411        fn zero(_cx: &()) -> Self {
1412            Default::default()
1413        }
1414
1415        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1416            *self = summary.max;
1417        }
1418    }
1419
1420    impl Dimension<'_, IntegersSummary> for Count {
1421        fn zero(_cx: &()) -> Self {
1422            Default::default()
1423        }
1424
1425        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1426            self.0 += summary.count;
1427        }
1428    }
1429
1430    impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1431        fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1432            self.0.cmp(&cursor_location.count)
1433        }
1434    }
1435
1436    impl Dimension<'_, IntegersSummary> for Sum {
1437        fn zero(_cx: &()) -> Self {
1438            Default::default()
1439        }
1440
1441        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1442            self.0 += summary.sum;
1443        }
1444    }
1445}