sum_tree.rs

   1mod cursor;
   2mod tree_map;
   3
   4use arrayvec::ArrayVec;
   5pub use cursor::{Cursor, FilterCursor, Iter};
   6use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator as _};
   7use std::marker::PhantomData;
   8use std::mem;
   9use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
  10pub use tree_map::{MapSeekTarget, TreeMap, TreeSet};
  11use ztracing::instrument;
  12
  13#[cfg(test)]
  14pub const TREE_BASE: usize = 2;
  15#[cfg(not(test))]
  16pub const TREE_BASE: usize = 6;
  17
  18/// An item that can be stored in a [`SumTree`]
  19///
  20/// Must be summarized by a type that implements [`Summary`]
  21pub trait Item: Clone {
  22    type Summary: Summary;
  23
  24    fn summary(&self, cx: <Self::Summary as Summary>::Context<'_>) -> Self::Summary;
  25}
  26
  27/// An [`Item`] whose summary has a specific key that can be used to identify it
  28pub trait KeyedItem: Item {
  29    type Key: for<'a> Dimension<'a, Self::Summary> + Ord;
  30
  31    fn key(&self) -> Self::Key;
  32}
  33
  34/// A type that describes the Sum of all [`Item`]s in a subtree of the [`SumTree`]
  35///
  36/// Each Summary type can have multiple [`Dimension`]s that it measures,
  37/// which can be used to navigate the tree
  38pub trait Summary: Clone {
  39    type Context<'a>: Copy;
  40    fn zero<'a>(cx: Self::Context<'a>) -> Self;
  41    fn add_summary<'a>(&mut self, summary: &Self, cx: Self::Context<'a>);
  42}
  43
  44pub trait ContextLessSummary: Clone {
  45    fn zero() -> Self;
  46    fn add_summary(&mut self, summary: &Self);
  47}
  48
  49impl<T: ContextLessSummary> Summary for T {
  50    type Context<'a> = ();
  51
  52    fn zero<'a>((): ()) -> Self {
  53        T::zero()
  54    }
  55
  56    fn add_summary<'a>(&mut self, summary: &Self, (): ()) {
  57        T::add_summary(self, summary)
  58    }
  59}
  60
  61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  62pub struct NoSummary;
  63
  64/// Catch-all implementation for when you need something that implements [`Summary`] without a specific type.
  65/// We implement it on a `NoSummary` instead of re-using `()`, as that avoids blanket impl collisions with `impl<T: Summary> Dimension for T`
  66/// (as we also need unit type to be a fill-in dimension)
  67impl ContextLessSummary for NoSummary {
  68    fn zero() -> Self {
  69        NoSummary
  70    }
  71
  72    fn add_summary(&mut self, _: &Self) {}
  73}
  74
  75/// Each [`Summary`] type can have more than one [`Dimension`] type that it measures.
  76///
  77/// You can use dimensions to seek to a specific location in the [`SumTree`]
  78///
  79/// # Example:
  80/// Zed's rope has a `TextSummary` type that summarizes lines, characters, and bytes.
  81/// Each of these are different dimensions we may want to seek to
  82pub trait Dimension<'a, S: Summary>: Clone {
  83    fn zero(cx: S::Context<'_>) -> Self;
  84
  85    fn add_summary(&mut self, summary: &'a S, cx: S::Context<'_>);
  86    #[must_use]
  87    fn with_added_summary(mut self, summary: &'a S, cx: S::Context<'_>) -> Self {
  88        self.add_summary(summary, cx);
  89        self
  90    }
  91
  92    fn from_summary(summary: &'a S, cx: S::Context<'_>) -> Self {
  93        let mut dimension = Self::zero(cx);
  94        dimension.add_summary(summary, cx);
  95        dimension
  96    }
  97}
  98
  99impl<'a, T: Summary> Dimension<'a, T> for T {
 100    fn zero(cx: T::Context<'_>) -> Self {
 101        Summary::zero(cx)
 102    }
 103
 104    fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) {
 105        Summary::add_summary(self, summary, cx);
 106    }
 107}
 108
 109pub trait SeekTarget<'a, S: Summary, D: Dimension<'a, S>> {
 110    fn cmp(&self, cursor_location: &D, cx: S::Context<'_>) -> Ordering;
 111}
 112
 113impl<'a, S: Summary, D: Dimension<'a, S> + Ord> SeekTarget<'a, S, D> for D {
 114    fn cmp(&self, cursor_location: &Self, _: S::Context<'_>) -> Ordering {
 115        Ord::cmp(self, cursor_location)
 116    }
 117}
 118
 119impl<'a, T: Summary> Dimension<'a, T> for () {
 120    fn zero(_: T::Context<'_>) -> Self {}
 121
 122    fn add_summary(&mut self, _: &'a T, _: T::Context<'_>) {}
 123}
 124
 125#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
 126pub struct Dimensions<D1, D2, D3 = ()>(pub D1, pub D2, pub D3);
 127
 128impl<'a, T: Summary, D1: Dimension<'a, T>, D2: Dimension<'a, T>, D3: Dimension<'a, T>>
 129    Dimension<'a, T> for Dimensions<D1, D2, D3>
 130{
 131    fn zero(cx: T::Context<'_>) -> Self {
 132        Dimensions(D1::zero(cx), D2::zero(cx), D3::zero(cx))
 133    }
 134
 135    fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) {
 136        self.0.add_summary(summary, cx);
 137        self.1.add_summary(summary, cx);
 138        self.2.add_summary(summary, cx);
 139    }
 140}
 141
 142impl<'a, S, D1, D2, D3> SeekTarget<'a, S, Dimensions<D1, D2, D3>> for D1
 143where
 144    S: Summary,
 145    D1: SeekTarget<'a, S, D1> + Dimension<'a, S>,
 146    D2: Dimension<'a, S>,
 147    D3: Dimension<'a, S>,
 148{
 149    fn cmp(&self, cursor_location: &Dimensions<D1, D2, D3>, cx: S::Context<'_>) -> Ordering {
 150        self.cmp(&cursor_location.0, cx)
 151    }
 152}
 153
 154/// Bias is used to settle ambiguities when determining positions in an ordered sequence.
 155///
 156/// The primary use case is for text, where Bias influences
 157/// which character an offset or anchor is associated with.
 158///
 159/// # Examples
 160/// Given the buffer `AˇBCD`:
 161/// - The offset of the cursor is 1
 162/// - [Bias::Left] would attach the cursor to the character `A`
 163/// - [Bias::Right] would attach the cursor to the character `B`
 164///
 165/// Given the buffer `A«BCˇ»D`:
 166/// - The offset of the cursor is 3, and the selection is from 1 to 3
 167/// - The left anchor of the selection has [Bias::Right], attaching it to the character `B`
 168/// - The right anchor of the selection has [Bias::Left], attaching it to the character `C`
 169///
 170/// Given the buffer `{ˇ<...>`, where `<...>` is a folded region:
 171/// - The display offset of the cursor is 1, but the offset in the buffer is determined by the bias
 172/// - [Bias::Left] would attach the cursor to the character `{`, with a buffer offset of 1
 173/// - [Bias::Right] would attach the cursor to the first character of the folded region,
 174///   and the buffer offset would be the offset of the first character of the folded region
 175#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Default)]
 176pub enum Bias {
 177    /// Attach to the character on the left
 178    #[default]
 179    Left,
 180    /// Attach to the character on the right
 181    Right,
 182}
 183
 184impl Bias {
 185    pub fn invert(self) -> Self {
 186        match self {
 187            Self::Left => Self::Right,
 188            Self::Right => Self::Left,
 189        }
 190    }
 191}
 192
 193/// A B+ tree in which each leaf node contains `Item`s of type `T` and a `Summary`s for each `Item`.
 194/// Each internal node contains a `Summary` of the items in its subtree.
 195///
 196/// The maximum number of items per node is `TREE_BASE * 2`.
 197///
 198/// Any [`Dimension`] supported by the [`Summary`] type can be used to seek to a specific location in the tree.
 199#[derive(Clone)]
 200pub struct SumTree<T: Item>(Arc<Node<T>>);
 201
 202impl<T> fmt::Debug for SumTree<T>
 203where
 204    T: fmt::Debug + Item,
 205    T::Summary: fmt::Debug,
 206{
 207    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 208        f.debug_tuple("SumTree").field(&self.0).finish()
 209    }
 210}
 211
 212impl<T: Item> SumTree<T> {
 213    pub fn new(cx: <T::Summary as Summary>::Context<'_>) -> Self {
 214        SumTree(Arc::new(Node::Leaf {
 215            summary: <T::Summary as Summary>::zero(cx),
 216            items: ArrayVec::new(),
 217            item_summaries: ArrayVec::new(),
 218        }))
 219    }
 220
 221    /// Useful in cases where the item type has a non-trivial context type, but the zero value of the summary type doesn't depend on that context.
 222    pub fn from_summary(summary: T::Summary) -> Self {
 223        SumTree(Arc::new(Node::Leaf {
 224            summary,
 225            items: ArrayVec::new(),
 226            item_summaries: ArrayVec::new(),
 227        }))
 228    }
 229
 230    pub fn from_item(item: T, cx: <T::Summary as Summary>::Context<'_>) -> Self {
 231        let mut tree = Self::new(cx);
 232        tree.push(item, cx);
 233        tree
 234    }
 235
 236    pub fn from_iter<I: IntoIterator<Item = T>>(
 237        iter: I,
 238        cx: <T::Summary as Summary>::Context<'_>,
 239    ) -> Self {
 240        let mut nodes = Vec::new();
 241
 242        let mut iter = iter.into_iter().fuse().peekable();
 243        while iter.peek().is_some() {
 244            let items: ArrayVec<T, { 2 * TREE_BASE }> = iter.by_ref().take(2 * TREE_BASE).collect();
 245            let item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }> =
 246                items.iter().map(|item| item.summary(cx)).collect();
 247
 248            let mut summary = item_summaries[0].clone();
 249            for item_summary in &item_summaries[1..] {
 250                <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
 251            }
 252
 253            nodes.push(SumTree(Arc::new(Node::Leaf {
 254                summary,
 255                items,
 256                item_summaries,
 257            })));
 258        }
 259
 260        let mut parent_nodes = Vec::new();
 261        let mut height = 0;
 262        while nodes.len() > 1 {
 263            height += 1;
 264            let mut current_parent_node = None;
 265            for child_node in nodes.drain(..) {
 266                let parent_node = current_parent_node.get_or_insert_with(|| {
 267                    SumTree(Arc::new(Node::Internal {
 268                        summary: <T::Summary as Summary>::zero(cx),
 269                        height,
 270                        child_summaries: ArrayVec::new(),
 271                        child_trees: ArrayVec::new(),
 272                    }))
 273                });
 274                let Node::Internal {
 275                    summary,
 276                    child_summaries,
 277                    child_trees,
 278                    ..
 279                } = Arc::get_mut(&mut parent_node.0).unwrap()
 280                else {
 281                    unreachable!()
 282                };
 283                let child_summary = child_node.summary();
 284                <T::Summary as Summary>::add_summary(summary, child_summary, cx);
 285                child_summaries.push(child_summary.clone());
 286                child_trees.push(child_node);
 287
 288                if child_trees.len() == 2 * TREE_BASE {
 289                    parent_nodes.extend(current_parent_node.take());
 290                }
 291            }
 292            parent_nodes.extend(current_parent_node.take());
 293            mem::swap(&mut nodes, &mut parent_nodes);
 294        }
 295
 296        if nodes.is_empty() {
 297            Self::new(cx)
 298        } else {
 299            debug_assert_eq!(nodes.len(), 1);
 300            nodes.pop().unwrap()
 301        }
 302    }
 303
 304    pub fn from_par_iter<I, Iter>(iter: I, cx: <T::Summary as Summary>::Context<'_>) -> Self
 305    where
 306        I: IntoParallelIterator<Iter = Iter>,
 307        Iter: IndexedParallelIterator<Item = T>,
 308        T: Send + Sync,
 309        T::Summary: Send + Sync,
 310        for<'a> <T::Summary as Summary>::Context<'a>: Sync,
 311    {
 312        let mut nodes = iter
 313            .into_par_iter()
 314            .chunks(2 * TREE_BASE)
 315            .map(|items| {
 316                let items: ArrayVec<T, { 2 * TREE_BASE }> = items.into_iter().collect();
 317                let item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }> =
 318                    items.iter().map(|item| item.summary(cx)).collect();
 319                let mut summary = item_summaries[0].clone();
 320                for item_summary in &item_summaries[1..] {
 321                    <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
 322                }
 323                SumTree(Arc::new(Node::Leaf {
 324                    summary,
 325                    items,
 326                    item_summaries,
 327                }))
 328            })
 329            .collect::<Vec<_>>();
 330
 331        let mut height = 0;
 332        while nodes.len() > 1 {
 333            height += 1;
 334            nodes = nodes
 335                .into_par_iter()
 336                .chunks(2 * TREE_BASE)
 337                .map(|child_nodes| {
 338                    let child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }> =
 339                        child_nodes.into_iter().collect();
 340                    let child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }> = child_trees
 341                        .iter()
 342                        .map(|child_tree| child_tree.summary().clone())
 343                        .collect();
 344                    let mut summary = child_summaries[0].clone();
 345                    for child_summary in &child_summaries[1..] {
 346                        <T::Summary as Summary>::add_summary(&mut summary, child_summary, cx);
 347                    }
 348                    SumTree(Arc::new(Node::Internal {
 349                        height,
 350                        summary,
 351                        child_summaries,
 352                        child_trees,
 353                    }))
 354                })
 355                .collect::<Vec<_>>();
 356        }
 357
 358        if nodes.is_empty() {
 359            Self::new(cx)
 360        } else {
 361            debug_assert_eq!(nodes.len(), 1);
 362            nodes.pop().unwrap()
 363        }
 364    }
 365
 366    #[allow(unused)]
 367    pub fn items<'a>(&'a self, cx: <T::Summary as Summary>::Context<'a>) -> Vec<T> {
 368        let mut items = Vec::new();
 369        let mut cursor = self.cursor::<()>(cx);
 370        cursor.next();
 371        while let Some(item) = cursor.item() {
 372            items.push(item.clone());
 373            cursor.next();
 374        }
 375        items
 376    }
 377
 378    pub fn iter(&self) -> Iter<'_, T> {
 379        Iter::new(self)
 380    }
 381
 382    /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`.
 383    ///
 384    /// Only returns the item that exactly has the target match.
 385    #[instrument(skip_all)]
 386    pub fn find_exact<'a, 'slf, D, Target>(
 387        &'slf self,
 388        cx: <T::Summary as Summary>::Context<'a>,
 389        target: &Target,
 390        bias: Bias,
 391    ) -> (D, D, Option<&'slf T>)
 392    where
 393        D: Dimension<'slf, T::Summary>,
 394        Target: SeekTarget<'slf, T::Summary, D>,
 395    {
 396        let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
 397        let comparison = target.cmp(&tree_end, cx);
 398        if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
 399        {
 400            return (tree_end.clone(), tree_end, None);
 401        }
 402
 403        let mut pos = D::zero(cx);
 404        return match Self::find_iterate::<_, _, true>(cx, target, bias, &mut pos, self) {
 405            Some((item, end)) => (pos, end, Some(item)),
 406            None => (pos.clone(), pos, None),
 407        };
 408    }
 409
 410    /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
 411    #[instrument(skip_all)]
 412    pub fn find<'a, 'slf, D, Target>(
 413        &'slf self,
 414        cx: <T::Summary as Summary>::Context<'a>,
 415        target: &Target,
 416        bias: Bias,
 417    ) -> (D, D, Option<&'slf T>)
 418    where
 419        D: Dimension<'slf, T::Summary>,
 420        Target: SeekTarget<'slf, T::Summary, D>,
 421    {
 422        let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
 423        let comparison = target.cmp(&tree_end, cx);
 424        if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
 425        {
 426            return (tree_end.clone(), tree_end, None);
 427        }
 428
 429        let mut pos = D::zero(cx);
 430        return match Self::find_iterate::<_, _, false>(cx, target, bias, &mut pos, self) {
 431            Some((item, end)) => (pos, end, Some(item)),
 432            None => (pos.clone(), pos, None),
 433        };
 434    }
 435
 436    fn find_iterate<'tree, 'a, D, Target, const EXACT: bool>(
 437        cx: <T::Summary as Summary>::Context<'a>,
 438        target: &Target,
 439        bias: Bias,
 440        position: &mut D,
 441        mut this: &'tree SumTree<T>,
 442    ) -> Option<(&'tree T, D)>
 443    where
 444        D: Dimension<'tree, T::Summary>,
 445        Target: SeekTarget<'tree, T::Summary, D>,
 446    {
 447        'iterate: loop {
 448            match &*this.0 {
 449                Node::Internal {
 450                    child_summaries,
 451                    child_trees,
 452                    ..
 453                } => {
 454                    for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
 455                        let child_end = position.clone().with_added_summary(child_summary, cx);
 456
 457                        let comparison = target.cmp(&child_end, cx);
 458                        let target_in_child = comparison == Ordering::Less
 459                            || (comparison == Ordering::Equal && bias == Bias::Left);
 460                        if target_in_child {
 461                            this = child_tree;
 462                            continue 'iterate;
 463                        }
 464                        *position = child_end;
 465                    }
 466                }
 467                Node::Leaf {
 468                    items,
 469                    item_summaries,
 470                    ..
 471                } => {
 472                    for (item, item_summary) in items.iter().zip(item_summaries) {
 473                        let mut child_end = position.clone();
 474                        child_end.add_summary(item_summary, cx);
 475
 476                        let comparison = target.cmp(&child_end, cx);
 477                        let entry_found = if EXACT {
 478                            comparison == Ordering::Equal
 479                        } else {
 480                            comparison == Ordering::Less
 481                                || (comparison == Ordering::Equal && bias == Bias::Left)
 482                        };
 483                        if entry_found {
 484                            return Some((item, child_end));
 485                        }
 486
 487                        *position = child_end;
 488                    }
 489                }
 490            }
 491            return None;
 492        }
 493    }
 494
 495    /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
 496    #[instrument(skip_all)]
 497    pub fn find_with_prev<'a, 'slf, D, Target>(
 498        &'slf self,
 499        cx: <T::Summary as Summary>::Context<'a>,
 500        target: &Target,
 501        bias: Bias,
 502    ) -> (D, D, Option<(Option<&'slf T>, &'slf T)>)
 503    where
 504        D: Dimension<'slf, T::Summary>,
 505        Target: SeekTarget<'slf, T::Summary, D>,
 506    {
 507        let tree_end = D::zero(cx).with_added_summary(self.summary(), cx);
 508        let comparison = target.cmp(&tree_end, cx);
 509        if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right)
 510        {
 511            return (tree_end.clone(), tree_end, None);
 512        }
 513
 514        let mut pos = D::zero(cx);
 515        return match Self::find_with_prev_iterate::<_, _, false>(cx, target, bias, &mut pos, self) {
 516            Some((prev, item, end)) => (pos, end, Some((prev, item))),
 517            None => (pos.clone(), pos, None),
 518        };
 519    }
 520
 521    fn find_with_prev_iterate<'tree, 'a, D, Target, const EXACT: bool>(
 522        cx: <T::Summary as Summary>::Context<'a>,
 523        target: &Target,
 524        bias: Bias,
 525        position: &mut D,
 526        mut this: &'tree SumTree<T>,
 527    ) -> Option<(Option<&'tree T>, &'tree T, D)>
 528    where
 529        D: Dimension<'tree, T::Summary>,
 530        Target: SeekTarget<'tree, T::Summary, D>,
 531    {
 532        let mut prev = None;
 533        'iterate: loop {
 534            match &*this.0 {
 535                Node::Internal {
 536                    child_summaries,
 537                    child_trees,
 538                    ..
 539                } => {
 540                    for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) {
 541                        let child_end = position.clone().with_added_summary(child_summary, cx);
 542
 543                        let comparison = target.cmp(&child_end, cx);
 544                        let target_in_child = comparison == Ordering::Less
 545                            || (comparison == Ordering::Equal && bias == Bias::Left);
 546                        if target_in_child {
 547                            this = child_tree;
 548                            continue 'iterate;
 549                        }
 550                        prev = child_tree.last();
 551                        *position = child_end;
 552                    }
 553                }
 554                Node::Leaf {
 555                    items,
 556                    item_summaries,
 557                    ..
 558                } => {
 559                    for (item, item_summary) in items.iter().zip(item_summaries) {
 560                        let mut child_end = position.clone();
 561                        child_end.add_summary(item_summary, cx);
 562
 563                        let comparison = target.cmp(&child_end, cx);
 564                        let entry_found = if EXACT {
 565                            comparison == Ordering::Equal
 566                        } else {
 567                            comparison == Ordering::Less
 568                                || (comparison == Ordering::Equal && bias == Bias::Left)
 569                        };
 570                        if entry_found {
 571                            return Some((prev, item, child_end));
 572                        }
 573
 574                        prev = Some(item);
 575                        *position = child_end;
 576                    }
 577                }
 578            }
 579            return None;
 580        }
 581    }
 582
 583    pub fn cursor<'a, 'b, D>(
 584        &'a self,
 585        cx: <T::Summary as Summary>::Context<'b>,
 586    ) -> Cursor<'a, 'b, T, D>
 587    where
 588        D: Dimension<'a, T::Summary>,
 589    {
 590        Cursor::new(self, cx)
 591    }
 592
 593    /// Note: If the summary type requires a non `()` context, then the filter cursor
 594    /// that is returned cannot be used with Rust's iterators.
 595    pub fn filter<'a, 'b, F, U>(
 596        &'a self,
 597        cx: <T::Summary as Summary>::Context<'b>,
 598        filter_node: F,
 599    ) -> FilterCursor<'a, 'b, F, T, U>
 600    where
 601        F: FnMut(&T::Summary) -> bool,
 602        U: Dimension<'a, T::Summary>,
 603    {
 604        FilterCursor::new(self, cx, filter_node)
 605    }
 606
 607    #[allow(dead_code)]
 608    pub fn first(&self) -> Option<&T> {
 609        self.leftmost_leaf().0.items().first()
 610    }
 611
 612    pub fn last(&self) -> Option<&T> {
 613        self.rightmost_leaf().0.items().last()
 614    }
 615
 616    pub fn last_summary(&self) -> Option<&T::Summary> {
 617        self.rightmost_leaf().0.child_summaries().last()
 618    }
 619
 620    pub fn update_last(
 621        &mut self,
 622        f: impl FnOnce(&mut T),
 623        cx: <T::Summary as Summary>::Context<'_>,
 624    ) {
 625        self.update_last_recursive(f, cx);
 626    }
 627
 628    fn update_last_recursive(
 629        &mut self,
 630        f: impl FnOnce(&mut T),
 631        cx: <T::Summary as Summary>::Context<'_>,
 632    ) -> Option<T::Summary> {
 633        match Arc::make_mut(&mut self.0) {
 634            Node::Internal {
 635                summary,
 636                child_summaries,
 637                child_trees,
 638                ..
 639            } => {
 640                let last_summary = child_summaries.last_mut().unwrap();
 641                let last_child = child_trees.last_mut().unwrap();
 642                *last_summary = last_child.update_last_recursive(f, cx).unwrap();
 643                *summary = sum(child_summaries.iter(), cx);
 644                Some(summary.clone())
 645            }
 646            Node::Leaf {
 647                summary,
 648                items,
 649                item_summaries,
 650            } => {
 651                if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
 652                {
 653                    (f)(item);
 654                    *item_summary = item.summary(cx);
 655                    *summary = sum(item_summaries.iter(), cx);
 656                    Some(summary.clone())
 657                } else {
 658                    None
 659                }
 660            }
 661        }
 662    }
 663
 664    pub fn extent<'a, D: Dimension<'a, T::Summary>>(
 665        &'a self,
 666        cx: <T::Summary as Summary>::Context<'_>,
 667    ) -> D {
 668        let mut extent = D::zero(cx);
 669        match self.0.as_ref() {
 670            Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
 671                extent.add_summary(summary, cx);
 672            }
 673        }
 674        extent
 675    }
 676
 677    pub fn summary(&self) -> &T::Summary {
 678        match self.0.as_ref() {
 679            Node::Internal { summary, .. } => summary,
 680            Node::Leaf { summary, .. } => summary,
 681        }
 682    }
 683
 684    pub fn is_empty(&self) -> bool {
 685        match self.0.as_ref() {
 686            Node::Internal { .. } => false,
 687            Node::Leaf { items, .. } => items.is_empty(),
 688        }
 689    }
 690
 691    pub fn extend<I>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
 692    where
 693        I: IntoIterator<Item = T>,
 694    {
 695        self.append(Self::from_iter(iter, cx), cx);
 696    }
 697
 698    pub fn par_extend<I, Iter>(&mut self, iter: I, cx: <T::Summary as Summary>::Context<'_>)
 699    where
 700        I: IntoParallelIterator<Iter = Iter>,
 701        Iter: IndexedParallelIterator<Item = T>,
 702        T: Send + Sync,
 703        T::Summary: Send + Sync,
 704        for<'a> <T::Summary as Summary>::Context<'a>: Sync,
 705    {
 706        self.append(Self::from_par_iter(iter, cx), cx);
 707    }
 708
 709    pub fn push(&mut self, item: T, cx: <T::Summary as Summary>::Context<'_>) {
 710        let summary = item.summary(cx);
 711        self.append(
 712            SumTree(Arc::new(Node::Leaf {
 713                summary: summary.clone(),
 714                items: ArrayVec::from_iter(Some(item)),
 715                item_summaries: ArrayVec::from_iter(Some(summary)),
 716            })),
 717            cx,
 718        );
 719    }
 720
 721    pub fn append(&mut self, mut other: Self, cx: <T::Summary as Summary>::Context<'_>) {
 722        if self.is_empty() {
 723            *self = other;
 724        } else if !other.0.is_leaf() || !other.0.items().is_empty() {
 725            if self.0.height() < other.0.height() {
 726                if let Some(tree) = Self::append_large(self.clone(), &mut other, cx) {
 727                    *self = Self::from_child_trees(tree, other, cx);
 728                } else {
 729                    *self = other;
 730                }
 731            } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
 732                *self = Self::from_child_trees(self.clone(), split_tree, cx);
 733            }
 734        }
 735    }
 736
 737    fn push_tree_recursive(
 738        &mut self,
 739        other: SumTree<T>,
 740        cx: <T::Summary as Summary>::Context<'_>,
 741    ) -> Option<SumTree<T>> {
 742        match Arc::make_mut(&mut self.0) {
 743            Node::Internal {
 744                height,
 745                summary,
 746                child_summaries,
 747                child_trees,
 748                ..
 749            } => {
 750                let other_node = other.0.clone();
 751                <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
 752
 753                let height_delta = *height - other_node.height();
 754                let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
 755                let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
 756                if height_delta == 0 {
 757                    summaries_to_append.extend(other_node.child_summaries().iter().cloned());
 758                    trees_to_append.extend(other_node.child_trees().iter().cloned());
 759                } else if height_delta == 1 && !other_node.is_underflowing() {
 760                    summaries_to_append.push(other_node.summary().clone());
 761                    trees_to_append.push(other)
 762                } else {
 763                    let tree_to_append = child_trees
 764                        .last_mut()
 765                        .unwrap()
 766                        .push_tree_recursive(other, cx);
 767                    *child_summaries.last_mut().unwrap() =
 768                        child_trees.last().unwrap().0.summary().clone();
 769
 770                    if let Some(split_tree) = tree_to_append {
 771                        summaries_to_append.push(split_tree.0.summary().clone());
 772                        trees_to_append.push(split_tree);
 773                    }
 774                }
 775
 776                let child_count = child_trees.len() + trees_to_append.len();
 777                if child_count > 2 * TREE_BASE {
 778                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
 779                    let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
 780                    let left_trees;
 781                    let right_trees;
 782
 783                    let midpoint = (child_count + child_count % 2) / 2;
 784                    {
 785                        let mut all_summaries = child_summaries
 786                            .iter()
 787                            .chain(summaries_to_append.iter())
 788                            .cloned();
 789                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
 790                        right_summaries = all_summaries.collect();
 791                        let mut all_trees =
 792                            child_trees.iter().chain(trees_to_append.iter()).cloned();
 793                        left_trees = all_trees.by_ref().take(midpoint).collect();
 794                        right_trees = all_trees.collect();
 795                    }
 796                    *summary = sum(left_summaries.iter(), cx);
 797                    *child_summaries = left_summaries;
 798                    *child_trees = left_trees;
 799
 800                    Some(SumTree(Arc::new(Node::Internal {
 801                        height: *height,
 802                        summary: sum(right_summaries.iter(), cx),
 803                        child_summaries: right_summaries,
 804                        child_trees: right_trees,
 805                    })))
 806                } else {
 807                    child_summaries.extend(summaries_to_append);
 808                    child_trees.extend(trees_to_append);
 809                    None
 810                }
 811            }
 812            Node::Leaf {
 813                summary,
 814                items,
 815                item_summaries,
 816            } => {
 817                let other_node = other.0;
 818
 819                let child_count = items.len() + other_node.items().len();
 820                if child_count > 2 * TREE_BASE {
 821                    let left_items;
 822                    let right_items;
 823                    let left_summaries;
 824                    let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
 825
 826                    let midpoint = (child_count + child_count % 2) / 2;
 827                    {
 828                        let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
 829                        left_items = all_items.by_ref().take(midpoint).collect();
 830                        right_items = all_items.collect();
 831
 832                        let mut all_summaries = item_summaries
 833                            .iter()
 834                            .chain(other_node.child_summaries())
 835                            .cloned();
 836                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
 837                        right_summaries = all_summaries.collect();
 838                    }
 839                    *items = left_items;
 840                    *item_summaries = left_summaries;
 841                    *summary = sum(item_summaries.iter(), cx);
 842                    Some(SumTree(Arc::new(Node::Leaf {
 843                        items: right_items,
 844                        summary: sum(right_summaries.iter(), cx),
 845                        item_summaries: right_summaries,
 846                    })))
 847                } else {
 848                    <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
 849                    items.extend(other_node.items().iter().cloned());
 850                    item_summaries.extend(other_node.child_summaries().iter().cloned());
 851                    None
 852                }
 853            }
 854        }
 855    }
 856
 857    // appends the `large` tree to a `small` tree, assumes small.height() <= large.height()
 858    fn append_large(
 859        small: Self,
 860        large: &mut Self,
 861        cx: <T::Summary as Summary>::Context<'_>,
 862    ) -> Option<Self> {
 863        if small.0.height() == large.0.height() {
 864            if !small.0.is_underflowing() {
 865                Some(small)
 866            } else {
 867                Self::merge_into_right(small, large, cx)
 868            }
 869        } else {
 870            debug_assert!(small.0.height() < large.0.height());
 871            let Node::Internal {
 872                height,
 873                summary,
 874                child_summaries,
 875                child_trees,
 876            } = Arc::make_mut(&mut large.0)
 877            else {
 878                unreachable!();
 879            };
 880            let mut full_summary = small.summary().clone();
 881            Summary::add_summary(&mut full_summary, summary, cx);
 882            *summary = full_summary;
 883
 884            let first = child_trees.first_mut().unwrap();
 885            let res = Self::append_large(small, first, cx);
 886            *child_summaries.first_mut().unwrap() = first.summary().clone();
 887            if let Some(tree) = res {
 888                if child_trees.len() < 2 * TREE_BASE {
 889                    child_summaries.insert(0, tree.summary().clone());
 890                    child_trees.insert(0, tree);
 891                    None
 892                } else {
 893                    let new_child_summaries = {
 894                        let mut res = ArrayVec::from_iter([tree.summary().clone()]);
 895                        res.extend(child_summaries.drain(..TREE_BASE));
 896                        res
 897                    };
 898                    let tree = SumTree(Arc::new(Node::Internal {
 899                        height: *height,
 900                        summary: sum(new_child_summaries.iter(), cx),
 901                        child_summaries: new_child_summaries,
 902                        child_trees: {
 903                            let mut res = ArrayVec::from_iter([tree]);
 904                            res.extend(child_trees.drain(..TREE_BASE));
 905                            res
 906                        },
 907                    }));
 908
 909                    *summary = sum(child_summaries.iter(), cx);
 910                    Some(tree)
 911                }
 912            } else {
 913                None
 914            }
 915        }
 916    }
 917
 918    // Merge two nodes into `large`.
 919    //
 920    // `large` will contain the contents of `small` followed by its own data.
 921    // If the combined data exceed the node capacity, returns a new node that
 922    // holds the first half of the merged items and `large` is left with the
 923    // second half
 924    //
 925    // The nodes must be on the same height
 926    // It only makes sense to call this when `small` is underflowing
 927    fn merge_into_right(
 928        small: Self,
 929        large: &mut Self,
 930        cx: <<T as Item>::Summary as Summary>::Context<'_>,
 931    ) -> Option<SumTree<T>> {
 932        debug_assert_eq!(small.0.height(), large.0.height());
 933        match (small.0.as_ref(), Arc::make_mut(&mut large.0)) {
 934            (
 935                Node::Internal {
 936                    summary: small_summary,
 937                    child_summaries: small_child_summaries,
 938                    child_trees: small_child_trees,
 939                    ..
 940                },
 941                Node::Internal {
 942                    summary,
 943                    child_summaries,
 944                    child_trees,
 945                    height,
 946                },
 947            ) => {
 948                let total_child_count = child_trees.len() + small_child_trees.len();
 949                if total_child_count <= 2 * TREE_BASE {
 950                    let mut all_trees = small_child_trees.clone();
 951                    all_trees.extend(child_trees.drain(..));
 952                    *child_trees = all_trees;
 953
 954                    let mut all_summaries = small_child_summaries.clone();
 955                    all_summaries.extend(child_summaries.drain(..));
 956                    *child_summaries = all_summaries;
 957
 958                    let mut full_summary = small_summary.clone();
 959                    Summary::add_summary(&mut full_summary, summary, cx);
 960                    *summary = full_summary;
 961                    None
 962                } else {
 963                    let midpoint = total_child_count.div_ceil(2);
 964                    let mut all_trees = small_child_trees.iter().chain(child_trees.iter()).cloned();
 965                    let left_trees = all_trees.by_ref().take(midpoint).collect();
 966                    *child_trees = all_trees.collect();
 967
 968                    let mut all_summaries = small_child_summaries
 969                        .iter()
 970                        .chain(child_summaries.iter())
 971                        .cloned();
 972                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }> =
 973                        all_summaries.by_ref().take(midpoint).collect();
 974                    *child_summaries = all_summaries.collect();
 975
 976                    *summary = sum(child_summaries.iter(), cx);
 977                    Some(SumTree(Arc::new(Node::Internal {
 978                        height: *height,
 979                        summary: sum(left_summaries.iter(), cx),
 980                        child_summaries: left_summaries,
 981                        child_trees: left_trees,
 982                    })))
 983                }
 984            }
 985            (
 986                Node::Leaf {
 987                    summary: small_summary,
 988                    items: small_items,
 989                    item_summaries: small_item_summaries,
 990                },
 991                Node::Leaf {
 992                    summary,
 993                    items,
 994                    item_summaries,
 995                },
 996            ) => {
 997                let total_child_count = small_items.len() + items.len();
 998                if total_child_count <= 2 * TREE_BASE {
 999                    let mut all_items = small_items.clone();
1000                    all_items.extend(items.drain(..));
1001                    *items = all_items;
1002
1003                    let mut all_summaries = small_item_summaries.clone();
1004                    all_summaries.extend(item_summaries.drain(..));
1005                    *item_summaries = all_summaries;
1006
1007                    let mut full_summary = small_summary.clone();
1008                    Summary::add_summary(&mut full_summary, summary, cx);
1009                    *summary = full_summary;
1010                    None
1011                } else {
1012                    let midpoint = total_child_count.div_ceil(2);
1013                    let mut all_items = small_items.iter().chain(items.iter()).cloned();
1014                    let left_items = all_items.by_ref().take(midpoint).collect();
1015                    *items = all_items.collect();
1016
1017                    let mut all_summaries = small_item_summaries
1018                        .iter()
1019                        .chain(item_summaries.iter())
1020                        .cloned();
1021                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }> =
1022                        all_summaries.by_ref().take(midpoint).collect();
1023                    *item_summaries = all_summaries.collect();
1024
1025                    *summary = sum(item_summaries.iter(), cx);
1026                    Some(SumTree(Arc::new(Node::Leaf {
1027                        items: left_items,
1028                        summary: sum(left_summaries.iter(), cx),
1029                        item_summaries: left_summaries,
1030                    })))
1031                }
1032            }
1033            _ => unreachable!(),
1034        }
1035    }
1036
1037    fn from_child_trees(
1038        left: SumTree<T>,
1039        right: SumTree<T>,
1040        cx: <T::Summary as Summary>::Context<'_>,
1041    ) -> Self {
1042        let height = left.0.height() + 1;
1043        let mut child_summaries = ArrayVec::new();
1044        child_summaries.push(left.0.summary().clone());
1045        child_summaries.push(right.0.summary().clone());
1046        let mut child_trees = ArrayVec::new();
1047        child_trees.push(left);
1048        child_trees.push(right);
1049        SumTree(Arc::new(Node::Internal {
1050            height,
1051            summary: sum(child_summaries.iter(), cx),
1052            child_summaries,
1053            child_trees,
1054        }))
1055    }
1056
1057    fn leftmost_leaf(&self) -> &Self {
1058        match *self.0 {
1059            Node::Leaf { .. } => self,
1060            Node::Internal {
1061                ref child_trees, ..
1062            } => child_trees.first().unwrap().leftmost_leaf(),
1063        }
1064    }
1065
1066    fn rightmost_leaf(&self) -> &Self {
1067        match *self.0 {
1068            Node::Leaf { .. } => self,
1069            Node::Internal {
1070                ref child_trees, ..
1071            } => child_trees.last().unwrap().rightmost_leaf(),
1072        }
1073    }
1074}
1075
1076impl<T: Item + PartialEq> PartialEq for SumTree<T> {
1077    fn eq(&self, other: &Self) -> bool {
1078        self.iter().eq(other.iter())
1079    }
1080}
1081
1082impl<T: Item + Eq> Eq for SumTree<T> {}
1083
1084impl<T: KeyedItem> SumTree<T> {
1085    pub fn insert_or_replace<'a, 'b>(
1086        &'a mut self,
1087        item: T,
1088        cx: <T::Summary as Summary>::Context<'b>,
1089    ) -> Option<T> {
1090        let mut replaced = None;
1091        {
1092            let mut cursor = self.cursor::<T::Key>(cx);
1093            let mut new_tree = cursor.slice(&item.key(), Bias::Left);
1094            if let Some(cursor_item) = cursor.item()
1095                && cursor_item.key() == item.key()
1096            {
1097                replaced = Some(cursor_item.clone());
1098                cursor.next();
1099            }
1100            new_tree.push(item, cx);
1101            new_tree.append(cursor.suffix(), cx);
1102            drop(cursor);
1103            *self = new_tree
1104        };
1105        replaced
1106    }
1107
1108    pub fn remove(&mut self, key: &T::Key, cx: <T::Summary as Summary>::Context<'_>) -> Option<T> {
1109        let mut removed = None;
1110        *self = {
1111            let mut cursor = self.cursor::<T::Key>(cx);
1112            let mut new_tree = cursor.slice(key, Bias::Left);
1113            if let Some(item) = cursor.item()
1114                && item.key() == *key
1115            {
1116                removed = Some(item.clone());
1117                cursor.next();
1118            }
1119            new_tree.append(cursor.suffix(), cx);
1120            new_tree
1121        };
1122        removed
1123    }
1124
1125    pub fn edit(
1126        &mut self,
1127        mut edits: Vec<Edit<T>>,
1128        cx: <T::Summary as Summary>::Context<'_>,
1129    ) -> Vec<T> {
1130        if edits.is_empty() {
1131            return Vec::new();
1132        }
1133
1134        let mut removed = Vec::new();
1135        edits.sort_unstable_by_key(|item| item.key());
1136
1137        *self = {
1138            let mut cursor = self.cursor::<T::Key>(cx);
1139            let mut new_tree = SumTree::new(cx);
1140            let mut buffered_items = Vec::new();
1141
1142            cursor.seek(&T::Key::zero(cx), Bias::Left);
1143            for edit in edits {
1144                let new_key = edit.key();
1145                let mut old_item = cursor.item();
1146
1147                if old_item
1148                    .as_ref()
1149                    .is_some_and(|old_item| old_item.key() < new_key)
1150                {
1151                    new_tree.extend(buffered_items.drain(..), cx);
1152                    let slice = cursor.slice(&new_key, Bias::Left);
1153                    new_tree.append(slice, cx);
1154                    old_item = cursor.item();
1155                }
1156
1157                if let Some(old_item) = old_item
1158                    && old_item.key() == new_key
1159                {
1160                    removed.push(old_item.clone());
1161                    cursor.next();
1162                }
1163
1164                match edit {
1165                    Edit::Insert(item) => {
1166                        buffered_items.push(item);
1167                    }
1168                    Edit::Remove(_) => {}
1169                }
1170            }
1171
1172            new_tree.extend(buffered_items, cx);
1173            new_tree.append(cursor.suffix(), cx);
1174            new_tree
1175        };
1176
1177        removed
1178    }
1179
1180    pub fn get<'a>(
1181        &'a self,
1182        key: &T::Key,
1183        cx: <T::Summary as Summary>::Context<'a>,
1184    ) -> Option<&'a T> {
1185        if let (_, _, Some(item)) = self.find_exact::<T::Key, _>(cx, key, Bias::Left) {
1186            Some(item)
1187        } else {
1188            None
1189        }
1190    }
1191}
1192
1193impl<T, S> Default for SumTree<T>
1194where
1195    T: Item<Summary = S>,
1196    S: for<'a> Summary<Context<'a> = ()>,
1197{
1198    fn default() -> Self {
1199        Self::new(())
1200    }
1201}
1202
1203#[derive(Clone)]
1204pub enum Node<T: Item> {
1205    Internal {
1206        height: u8,
1207        summary: T::Summary,
1208        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
1209        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
1210    },
1211    Leaf {
1212        summary: T::Summary,
1213        items: ArrayVec<T, { 2 * TREE_BASE }>,
1214        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
1215    },
1216}
1217
1218impl<T> fmt::Debug for Node<T>
1219where
1220    T: Item + fmt::Debug,
1221    T::Summary: fmt::Debug,
1222{
1223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1224        match self {
1225            Node::Internal {
1226                height,
1227                summary,
1228                child_summaries,
1229                child_trees,
1230            } => f
1231                .debug_struct("Internal")
1232                .field("height", height)
1233                .field("summary", summary)
1234                .field("child_summaries", child_summaries)
1235                .field("child_trees", child_trees)
1236                .finish(),
1237            Node::Leaf {
1238                summary,
1239                items,
1240                item_summaries,
1241            } => f
1242                .debug_struct("Leaf")
1243                .field("summary", summary)
1244                .field("items", items)
1245                .field("item_summaries", item_summaries)
1246                .finish(),
1247        }
1248    }
1249}
1250
1251impl<T: Item> Node<T> {
1252    fn is_leaf(&self) -> bool {
1253        matches!(self, Node::Leaf { .. })
1254    }
1255
1256    fn height(&self) -> u8 {
1257        match self {
1258            Node::Internal { height, .. } => *height,
1259            Node::Leaf { .. } => 0,
1260        }
1261    }
1262
1263    fn summary(&self) -> &T::Summary {
1264        match self {
1265            Node::Internal { summary, .. } => summary,
1266            Node::Leaf { summary, .. } => summary,
1267        }
1268    }
1269
1270    fn child_summaries(&self) -> &[T::Summary] {
1271        match self {
1272            Node::Internal {
1273                child_summaries, ..
1274            } => child_summaries.as_slice(),
1275            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
1276        }
1277    }
1278
1279    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
1280        match self {
1281            Node::Internal { child_trees, .. } => child_trees,
1282            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
1283        }
1284    }
1285
1286    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
1287        match self {
1288            Node::Leaf { items, .. } => items,
1289            Node::Internal { .. } => panic!("Internal nodes have no items"),
1290        }
1291    }
1292
1293    fn is_underflowing(&self) -> bool {
1294        match self {
1295            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
1296            Node::Leaf { items, .. } => items.len() < TREE_BASE,
1297        }
1298    }
1299}
1300
1301#[derive(Debug)]
1302pub enum Edit<T: KeyedItem> {
1303    Insert(T),
1304    Remove(T::Key),
1305}
1306
1307impl<T: KeyedItem> Edit<T> {
1308    fn key(&self) -> T::Key {
1309        match self {
1310            Edit::Insert(item) => item.key(),
1311            Edit::Remove(key) => key.clone(),
1312        }
1313    }
1314}
1315
1316fn sum<'a, T, I>(iter: I, cx: T::Context<'_>) -> T
1317where
1318    T: 'a + Summary,
1319    I: Iterator<Item = &'a T>,
1320{
1321    let mut sum = T::zero(cx);
1322    for value in iter {
1323        sum.add_summary(value, cx);
1324    }
1325    sum
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330    use super::*;
1331    use rand::{distr::StandardUniform, prelude::*};
1332    use std::cmp;
1333
1334    #[ctor::ctor]
1335    fn init_logger() {
1336        zlog::init_test();
1337    }
1338
1339    #[test]
1340    fn test_extend_and_push_tree() {
1341        let mut tree1 = SumTree::default();
1342        tree1.extend(0..20, ());
1343
1344        let mut tree2 = SumTree::default();
1345        tree2.extend(50..100, ());
1346
1347        tree1.append(tree2, ());
1348        assert_eq!(tree1.items(()), (0..20).chain(50..100).collect::<Vec<u8>>());
1349    }
1350
1351    #[test]
1352    fn test_random() {
1353        let mut starting_seed = 0;
1354        if let Ok(value) = std::env::var("SEED") {
1355            starting_seed = value.parse().expect("invalid SEED variable");
1356        }
1357        let mut num_iterations = 100;
1358        if let Ok(value) = std::env::var("ITERATIONS") {
1359            num_iterations = value.parse().expect("invalid ITERATIONS variable");
1360        }
1361        let num_operations = std::env::var("OPERATIONS")
1362            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
1363
1364        for seed in starting_seed..(starting_seed + num_iterations) {
1365            eprintln!("seed = {}", seed);
1366            let mut rng = StdRng::seed_from_u64(seed);
1367
1368            let rng = &mut rng;
1369            let mut tree = SumTree::<u8>::default();
1370            let count = rng.random_range(0..10);
1371            if rng.random() {
1372                tree.extend(rng.sample_iter(StandardUniform).take(count), ());
1373            } else {
1374                let items = rng
1375                    .sample_iter(StandardUniform)
1376                    .take(count)
1377                    .collect::<Vec<_>>();
1378                tree.par_extend(items, ());
1379            }
1380
1381            for _ in 0..num_operations {
1382                let splice_end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1383                let splice_start = rng.random_range(0..splice_end + 1);
1384                let count = rng.random_range(0..10);
1385                let tree_end = tree.extent::<Count>(());
1386                let new_items = rng
1387                    .sample_iter(StandardUniform)
1388                    .take(count)
1389                    .collect::<Vec<u8>>();
1390
1391                let mut reference_items = tree.items(());
1392                reference_items.splice(splice_start..splice_end, new_items.clone());
1393
1394                tree = {
1395                    let mut cursor = tree.cursor::<Count>(());
1396                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right);
1397                    if rng.random() {
1398                        new_tree.extend(new_items, ());
1399                    } else {
1400                        new_tree.par_extend(new_items, ());
1401                    }
1402                    cursor.seek(&Count(splice_end), Bias::Right);
1403                    new_tree.append(cursor.slice(&tree_end, Bias::Right), ());
1404                    new_tree
1405                };
1406
1407                assert_eq!(tree.items(()), reference_items);
1408                assert_eq!(
1409                    tree.iter().collect::<Vec<_>>(),
1410                    tree.cursor::<()>(()).collect::<Vec<_>>()
1411                );
1412
1413                log::info!("tree items: {:?}", tree.items(()));
1414
1415                let mut filter_cursor =
1416                    tree.filter::<_, Count>((), |summary| summary.contains_even);
1417                let expected_filtered_items = tree
1418                    .items(())
1419                    .into_iter()
1420                    .enumerate()
1421                    .filter(|(_, item)| (item & 1) == 0)
1422                    .collect::<Vec<_>>();
1423
1424                let mut item_ix = if rng.random() {
1425                    filter_cursor.next();
1426                    0
1427                } else {
1428                    filter_cursor.prev();
1429                    expected_filtered_items.len().saturating_sub(1)
1430                };
1431                while item_ix < expected_filtered_items.len() {
1432                    log::info!("filter_cursor, item_ix: {}", item_ix);
1433                    let actual_item = filter_cursor.item().unwrap();
1434                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
1435                    assert_eq!(actual_item, &reference_item);
1436                    assert_eq!(filter_cursor.start().0, reference_index);
1437                    log::info!("next");
1438                    filter_cursor.next();
1439                    item_ix += 1;
1440
1441                    while item_ix > 0 && rng.random_bool(0.2) {
1442                        log::info!("prev");
1443                        filter_cursor.prev();
1444                        item_ix -= 1;
1445
1446                        if item_ix == 0 && rng.random_bool(0.2) {
1447                            filter_cursor.prev();
1448                            assert_eq!(filter_cursor.item(), None);
1449                            assert_eq!(filter_cursor.start().0, 0);
1450                            filter_cursor.next();
1451                        }
1452                    }
1453                }
1454                assert_eq!(filter_cursor.item(), None);
1455
1456                let mut before_start = false;
1457                let mut cursor = tree.cursor::<Count>(());
1458                let start_pos = rng.random_range(0..=reference_items.len());
1459                cursor.seek(&Count(start_pos), Bias::Right);
1460                let mut pos = rng.random_range(start_pos..=reference_items.len());
1461                cursor.seek_forward(&Count(pos), Bias::Right);
1462
1463                for i in 0..10 {
1464                    assert_eq!(cursor.start().0, pos);
1465
1466                    if pos > 0 {
1467                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1468                    } else {
1469                        assert_eq!(cursor.prev_item(), None);
1470                    }
1471
1472                    if pos < reference_items.len() && !before_start {
1473                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1474                    } else {
1475                        assert_eq!(cursor.item(), None);
1476                    }
1477
1478                    if before_start {
1479                        assert_eq!(cursor.next_item(), reference_items.first());
1480                    } else if pos + 1 < reference_items.len() {
1481                        assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1482                    } else {
1483                        assert_eq!(cursor.next_item(), None);
1484                    }
1485
1486                    if i < 5 {
1487                        cursor.next();
1488                        if pos < reference_items.len() {
1489                            pos += 1;
1490                            before_start = false;
1491                        }
1492                    } else {
1493                        cursor.prev();
1494                        if pos == 0 {
1495                            before_start = true;
1496                        }
1497                        pos = pos.saturating_sub(1);
1498                    }
1499                }
1500            }
1501
1502            for _ in 0..10 {
1503                let end = rng.random_range(0..tree.extent::<Count>(()).0 + 1);
1504                let start = rng.random_range(0..end + 1);
1505                let start_bias = if rng.random() {
1506                    Bias::Left
1507                } else {
1508                    Bias::Right
1509                };
1510                let end_bias = if rng.random() {
1511                    Bias::Left
1512                } else {
1513                    Bias::Right
1514                };
1515
1516                let mut cursor = tree.cursor::<Count>(());
1517                cursor.seek(&Count(start), start_bias);
1518                let slice = cursor.slice(&Count(end), end_bias);
1519
1520                cursor.seek(&Count(start), start_bias);
1521                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias);
1522
1523                assert_eq!(summary.0, slice.summary().sum);
1524            }
1525        }
1526    }
1527
1528    #[test]
1529    fn test_cursor() {
1530        // Empty tree
1531        let tree = SumTree::<u8>::default();
1532        let mut cursor = tree.cursor::<IntegersSummary>(());
1533        assert_eq!(
1534            cursor.slice(&Count(0), Bias::Right).items(()),
1535            Vec::<u8>::new()
1536        );
1537        assert_eq!(cursor.item(), None);
1538        assert_eq!(cursor.prev_item(), None);
1539        assert_eq!(cursor.next_item(), None);
1540        assert_eq!(cursor.start().sum, 0);
1541        cursor.prev();
1542        assert_eq!(cursor.item(), None);
1543        assert_eq!(cursor.prev_item(), None);
1544        assert_eq!(cursor.next_item(), None);
1545        assert_eq!(cursor.start().sum, 0);
1546        cursor.next();
1547        assert_eq!(cursor.item(), None);
1548        assert_eq!(cursor.prev_item(), None);
1549        assert_eq!(cursor.next_item(), None);
1550        assert_eq!(cursor.start().sum, 0);
1551
1552        // Single-element tree
1553        let mut tree = SumTree::<u8>::default();
1554        tree.extend(vec![1], ());
1555        let mut cursor = tree.cursor::<IntegersSummary>(());
1556        assert_eq!(
1557            cursor.slice(&Count(0), Bias::Right).items(()),
1558            Vec::<u8>::new()
1559        );
1560        assert_eq!(cursor.item(), Some(&1));
1561        assert_eq!(cursor.prev_item(), None);
1562        assert_eq!(cursor.next_item(), None);
1563        assert_eq!(cursor.start().sum, 0);
1564
1565        cursor.next();
1566        assert_eq!(cursor.item(), None);
1567        assert_eq!(cursor.prev_item(), Some(&1));
1568        assert_eq!(cursor.next_item(), None);
1569        assert_eq!(cursor.start().sum, 1);
1570
1571        cursor.prev();
1572        assert_eq!(cursor.item(), Some(&1));
1573        assert_eq!(cursor.prev_item(), None);
1574        assert_eq!(cursor.next_item(), None);
1575        assert_eq!(cursor.start().sum, 0);
1576
1577        let mut cursor = tree.cursor::<IntegersSummary>(());
1578        assert_eq!(cursor.slice(&Count(1), Bias::Right).items(()), [1]);
1579        assert_eq!(cursor.item(), None);
1580        assert_eq!(cursor.prev_item(), Some(&1));
1581        assert_eq!(cursor.next_item(), None);
1582        assert_eq!(cursor.start().sum, 1);
1583
1584        cursor.seek(&Count(0), Bias::Right);
1585        assert_eq!(
1586            cursor
1587                .slice(&tree.extent::<Count>(()), Bias::Right)
1588                .items(()),
1589            [1]
1590        );
1591        assert_eq!(cursor.item(), None);
1592        assert_eq!(cursor.prev_item(), Some(&1));
1593        assert_eq!(cursor.next_item(), None);
1594        assert_eq!(cursor.start().sum, 1);
1595
1596        // Multiple-element tree
1597        let mut tree = SumTree::default();
1598        tree.extend(vec![1, 2, 3, 4, 5, 6], ());
1599        let mut cursor = tree.cursor::<IntegersSummary>(());
1600
1601        assert_eq!(cursor.slice(&Count(2), Bias::Right).items(()), [1, 2]);
1602        assert_eq!(cursor.item(), Some(&3));
1603        assert_eq!(cursor.prev_item(), Some(&2));
1604        assert_eq!(cursor.next_item(), Some(&4));
1605        assert_eq!(cursor.start().sum, 3);
1606
1607        cursor.next();
1608        assert_eq!(cursor.item(), Some(&4));
1609        assert_eq!(cursor.prev_item(), Some(&3));
1610        assert_eq!(cursor.next_item(), Some(&5));
1611        assert_eq!(cursor.start().sum, 6);
1612
1613        cursor.next();
1614        assert_eq!(cursor.item(), Some(&5));
1615        assert_eq!(cursor.prev_item(), Some(&4));
1616        assert_eq!(cursor.next_item(), Some(&6));
1617        assert_eq!(cursor.start().sum, 10);
1618
1619        cursor.next();
1620        assert_eq!(cursor.item(), Some(&6));
1621        assert_eq!(cursor.prev_item(), Some(&5));
1622        assert_eq!(cursor.next_item(), None);
1623        assert_eq!(cursor.start().sum, 15);
1624
1625        cursor.next();
1626        cursor.next();
1627        assert_eq!(cursor.item(), None);
1628        assert_eq!(cursor.prev_item(), Some(&6));
1629        assert_eq!(cursor.next_item(), None);
1630        assert_eq!(cursor.start().sum, 21);
1631
1632        cursor.prev();
1633        assert_eq!(cursor.item(), Some(&6));
1634        assert_eq!(cursor.prev_item(), Some(&5));
1635        assert_eq!(cursor.next_item(), None);
1636        assert_eq!(cursor.start().sum, 15);
1637
1638        cursor.prev();
1639        assert_eq!(cursor.item(), Some(&5));
1640        assert_eq!(cursor.prev_item(), Some(&4));
1641        assert_eq!(cursor.next_item(), Some(&6));
1642        assert_eq!(cursor.start().sum, 10);
1643
1644        cursor.prev();
1645        assert_eq!(cursor.item(), Some(&4));
1646        assert_eq!(cursor.prev_item(), Some(&3));
1647        assert_eq!(cursor.next_item(), Some(&5));
1648        assert_eq!(cursor.start().sum, 6);
1649
1650        cursor.prev();
1651        assert_eq!(cursor.item(), Some(&3));
1652        assert_eq!(cursor.prev_item(), Some(&2));
1653        assert_eq!(cursor.next_item(), Some(&4));
1654        assert_eq!(cursor.start().sum, 3);
1655
1656        cursor.prev();
1657        assert_eq!(cursor.item(), Some(&2));
1658        assert_eq!(cursor.prev_item(), Some(&1));
1659        assert_eq!(cursor.next_item(), Some(&3));
1660        assert_eq!(cursor.start().sum, 1);
1661
1662        cursor.prev();
1663        assert_eq!(cursor.item(), Some(&1));
1664        assert_eq!(cursor.prev_item(), None);
1665        assert_eq!(cursor.next_item(), Some(&2));
1666        assert_eq!(cursor.start().sum, 0);
1667
1668        cursor.prev();
1669        assert_eq!(cursor.item(), None);
1670        assert_eq!(cursor.prev_item(), None);
1671        assert_eq!(cursor.next_item(), Some(&1));
1672        assert_eq!(cursor.start().sum, 0);
1673
1674        cursor.next();
1675        assert_eq!(cursor.item(), Some(&1));
1676        assert_eq!(cursor.prev_item(), None);
1677        assert_eq!(cursor.next_item(), Some(&2));
1678        assert_eq!(cursor.start().sum, 0);
1679
1680        let mut cursor = tree.cursor::<IntegersSummary>(());
1681        assert_eq!(
1682            cursor
1683                .slice(&tree.extent::<Count>(()), Bias::Right)
1684                .items(()),
1685            tree.items(())
1686        );
1687        assert_eq!(cursor.item(), None);
1688        assert_eq!(cursor.prev_item(), Some(&6));
1689        assert_eq!(cursor.next_item(), None);
1690        assert_eq!(cursor.start().sum, 21);
1691
1692        cursor.seek(&Count(3), Bias::Right);
1693        assert_eq!(
1694            cursor
1695                .slice(&tree.extent::<Count>(()), Bias::Right)
1696                .items(()),
1697            [4, 5, 6]
1698        );
1699        assert_eq!(cursor.item(), None);
1700        assert_eq!(cursor.prev_item(), Some(&6));
1701        assert_eq!(cursor.next_item(), None);
1702        assert_eq!(cursor.start().sum, 21);
1703
1704        // Seeking can bias left or right
1705        cursor.seek(&Count(1), Bias::Left);
1706        assert_eq!(cursor.item(), Some(&1));
1707        cursor.seek(&Count(1), Bias::Right);
1708        assert_eq!(cursor.item(), Some(&2));
1709
1710        // Slicing without resetting starts from where the cursor is parked at.
1711        cursor.seek(&Count(1), Bias::Right);
1712        assert_eq!(cursor.slice(&Count(3), Bias::Right).items(()), vec![2, 3]);
1713        assert_eq!(cursor.slice(&Count(6), Bias::Left).items(()), vec![4, 5]);
1714        assert_eq!(cursor.slice(&Count(6), Bias::Right).items(()), vec![6]);
1715    }
1716
1717    #[test]
1718    fn test_edit() {
1719        let mut tree = SumTree::<u8>::default();
1720
1721        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], ());
1722        assert_eq!(tree.items(()), vec![0, 1, 2]);
1723        assert_eq!(removed, Vec::<u8>::new());
1724        assert_eq!(tree.get(&0, ()), Some(&0));
1725        assert_eq!(tree.get(&1, ()), Some(&1));
1726        assert_eq!(tree.get(&2, ()), Some(&2));
1727        assert_eq!(tree.get(&4, ()), None);
1728
1729        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], ());
1730        assert_eq!(tree.items(()), vec![1, 2, 4]);
1731        assert_eq!(removed, vec![0, 2]);
1732        assert_eq!(tree.get(&0, ()), None);
1733        assert_eq!(tree.get(&1, ()), Some(&1));
1734        assert_eq!(tree.get(&2, ()), Some(&2));
1735        assert_eq!(tree.get(&4, ()), Some(&4));
1736    }
1737
1738    #[test]
1739    fn test_from_iter() {
1740        assert_eq!(
1741            SumTree::from_iter(0..100, ()).items(()),
1742            (0..100).collect::<Vec<_>>()
1743        );
1744
1745        // Ensure `from_iter` works correctly when the given iterator restarts
1746        // after calling `next` if `None` was already returned.
1747        let mut ix = 0;
1748        let iterator = std::iter::from_fn(|| {
1749            ix = (ix + 1) % 2;
1750            if ix == 1 { Some(1) } else { None }
1751        });
1752        assert_eq!(SumTree::from_iter(iterator, ()).items(()), vec![1]);
1753    }
1754
1755    #[derive(Clone, Default, Debug)]
1756    pub struct IntegersSummary {
1757        count: usize,
1758        sum: usize,
1759        contains_even: bool,
1760        max: u8,
1761    }
1762
1763    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1764    struct Count(usize);
1765
1766    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1767    struct Sum(usize);
1768
1769    impl Item for u8 {
1770        type Summary = IntegersSummary;
1771
1772        fn summary(&self, _cx: ()) -> Self::Summary {
1773            IntegersSummary {
1774                count: 1,
1775                sum: *self as usize,
1776                contains_even: (*self & 1) == 0,
1777                max: *self,
1778            }
1779        }
1780    }
1781
1782    impl KeyedItem for u8 {
1783        type Key = u8;
1784
1785        fn key(&self) -> Self::Key {
1786            *self
1787        }
1788    }
1789
1790    impl ContextLessSummary for IntegersSummary {
1791        fn zero() -> Self {
1792            Default::default()
1793        }
1794
1795        fn add_summary(&mut self, other: &Self) {
1796            self.count += other.count;
1797            self.sum += other.sum;
1798            self.contains_even |= other.contains_even;
1799            self.max = cmp::max(self.max, other.max);
1800        }
1801    }
1802
1803    impl Dimension<'_, IntegersSummary> for u8 {
1804        fn zero(_cx: ()) -> Self {
1805            Default::default()
1806        }
1807
1808        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1809            *self = summary.max;
1810        }
1811    }
1812
1813    impl Dimension<'_, IntegersSummary> for Count {
1814        fn zero(_cx: ()) -> Self {
1815            Default::default()
1816        }
1817
1818        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1819            self.0 += summary.count;
1820        }
1821    }
1822
1823    impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1824        fn cmp(&self, cursor_location: &IntegersSummary, _: ()) -> Ordering {
1825            self.0.cmp(&cursor_location.count)
1826        }
1827    }
1828
1829    impl Dimension<'_, IntegersSummary> for Sum {
1830        fn zero(_cx: ()) -> Self {
1831            Default::default()
1832        }
1833
1834        fn add_summary(&mut self, summary: &IntegersSummary, _: ()) {
1835            self.0 += summary.sum;
1836        }
1837    }
1838}