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