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