sum_tree.rs

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