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    pub fn ptr_eq(&self, other: &Self) -> bool {
 520        Arc::ptr_eq(&self.0, &other.0)
 521    }
 522
 523    fn push_tree_recursive(
 524        &mut self,
 525        other: SumTree<T>,
 526        cx: &<T::Summary as Summary>::Context,
 527    ) -> Option<SumTree<T>> {
 528        match Arc::make_mut(&mut self.0) {
 529            Node::Internal {
 530                height,
 531                summary,
 532                child_summaries,
 533                child_trees,
 534                ..
 535            } => {
 536                let other_node = other.0.clone();
 537                <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
 538
 539                let height_delta = *height - other_node.height();
 540                let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
 541                let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
 542                if height_delta == 0 {
 543                    summaries_to_append.extend(other_node.child_summaries().iter().cloned());
 544                    trees_to_append.extend(other_node.child_trees().iter().cloned());
 545                } else if height_delta == 1 && !other_node.is_underflowing() {
 546                    summaries_to_append.push(other_node.summary().clone());
 547                    trees_to_append.push(other)
 548                } else {
 549                    let tree_to_append = child_trees
 550                        .last_mut()
 551                        .unwrap()
 552                        .push_tree_recursive(other, cx);
 553                    *child_summaries.last_mut().unwrap() =
 554                        child_trees.last().unwrap().0.summary().clone();
 555
 556                    if let Some(split_tree) = tree_to_append {
 557                        summaries_to_append.push(split_tree.0.summary().clone());
 558                        trees_to_append.push(split_tree);
 559                    }
 560                }
 561
 562                let child_count = child_trees.len() + trees_to_append.len();
 563                if child_count > 2 * TREE_BASE {
 564                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
 565                    let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
 566                    let left_trees;
 567                    let right_trees;
 568
 569                    let midpoint = (child_count + child_count % 2) / 2;
 570                    {
 571                        let mut all_summaries = child_summaries
 572                            .iter()
 573                            .chain(summaries_to_append.iter())
 574                            .cloned();
 575                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
 576                        right_summaries = all_summaries.collect();
 577                        let mut all_trees =
 578                            child_trees.iter().chain(trees_to_append.iter()).cloned();
 579                        left_trees = all_trees.by_ref().take(midpoint).collect();
 580                        right_trees = all_trees.collect();
 581                    }
 582                    *summary = sum(left_summaries.iter(), cx);
 583                    *child_summaries = left_summaries;
 584                    *child_trees = left_trees;
 585
 586                    Some(SumTree(Arc::new(Node::Internal {
 587                        height: *height,
 588                        summary: sum(right_summaries.iter(), cx),
 589                        child_summaries: right_summaries,
 590                        child_trees: right_trees,
 591                    })))
 592                } else {
 593                    child_summaries.extend(summaries_to_append);
 594                    child_trees.extend(trees_to_append);
 595                    None
 596                }
 597            }
 598            Node::Leaf {
 599                summary,
 600                items,
 601                item_summaries,
 602            } => {
 603                let other_node = other.0;
 604
 605                let child_count = items.len() + other_node.items().len();
 606                if child_count > 2 * TREE_BASE {
 607                    let left_items;
 608                    let right_items;
 609                    let left_summaries;
 610                    let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
 611
 612                    let midpoint = (child_count + child_count % 2) / 2;
 613                    {
 614                        let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
 615                        left_items = all_items.by_ref().take(midpoint).collect();
 616                        right_items = all_items.collect();
 617
 618                        let mut all_summaries = item_summaries
 619                            .iter()
 620                            .chain(other_node.child_summaries())
 621                            .cloned();
 622                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
 623                        right_summaries = all_summaries.collect();
 624                    }
 625                    *items = left_items;
 626                    *item_summaries = left_summaries;
 627                    *summary = sum(item_summaries.iter(), cx);
 628                    Some(SumTree(Arc::new(Node::Leaf {
 629                        items: right_items,
 630                        summary: sum(right_summaries.iter(), cx),
 631                        item_summaries: right_summaries,
 632                    })))
 633                } else {
 634                    <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
 635                    items.extend(other_node.items().iter().cloned());
 636                    item_summaries.extend(other_node.child_summaries().iter().cloned());
 637                    None
 638                }
 639            }
 640        }
 641    }
 642
 643    fn from_child_trees(
 644        left: SumTree<T>,
 645        right: SumTree<T>,
 646        cx: &<T::Summary as Summary>::Context,
 647    ) -> Self {
 648        let height = left.0.height() + 1;
 649        let mut child_summaries = ArrayVec::new();
 650        child_summaries.push(left.0.summary().clone());
 651        child_summaries.push(right.0.summary().clone());
 652        let mut child_trees = ArrayVec::new();
 653        child_trees.push(left);
 654        child_trees.push(right);
 655        SumTree(Arc::new(Node::Internal {
 656            height,
 657            summary: sum(child_summaries.iter(), cx),
 658            child_summaries,
 659            child_trees,
 660        }))
 661    }
 662
 663    fn leftmost_leaf(&self) -> &Self {
 664        match *self.0 {
 665            Node::Leaf { .. } => self,
 666            Node::Internal {
 667                ref child_trees, ..
 668            } => child_trees.first().unwrap().leftmost_leaf(),
 669        }
 670    }
 671
 672    fn rightmost_leaf(&self) -> &Self {
 673        match *self.0 {
 674            Node::Leaf { .. } => self,
 675            Node::Internal {
 676                ref child_trees, ..
 677            } => child_trees.last().unwrap().rightmost_leaf(),
 678        }
 679    }
 680
 681    #[cfg(debug_assertions)]
 682    pub fn _debug_entries(&self) -> Vec<&T> {
 683        self.iter().collect::<Vec<_>>()
 684    }
 685}
 686
 687impl<T: Item + PartialEq> PartialEq for SumTree<T> {
 688    fn eq(&self, other: &Self) -> bool {
 689        self.iter().eq(other.iter())
 690    }
 691}
 692
 693impl<T: Item + Eq> Eq for SumTree<T> {}
 694
 695impl<T: KeyedItem> SumTree<T> {
 696    pub fn insert_or_replace(
 697        &mut self,
 698        item: T,
 699        cx: &<T::Summary as Summary>::Context,
 700    ) -> Option<T> {
 701        let mut replaced = None;
 702        *self = {
 703            let mut cursor = self.cursor::<T::Key>(cx);
 704            let mut new_tree = cursor.slice(&item.key(), Bias::Left, cx);
 705            if let Some(cursor_item) = cursor.item() {
 706                if cursor_item.key() == item.key() {
 707                    replaced = Some(cursor_item.clone());
 708                    cursor.next(cx);
 709                }
 710            }
 711            new_tree.push(item, cx);
 712            new_tree.append(cursor.suffix(cx), cx);
 713            new_tree
 714        };
 715        replaced
 716    }
 717
 718    pub fn remove(&mut self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<T> {
 719        let mut removed = None;
 720        *self = {
 721            let mut cursor = self.cursor::<T::Key>(cx);
 722            let mut new_tree = cursor.slice(key, Bias::Left, cx);
 723            if let Some(item) = cursor.item() {
 724                if item.key() == *key {
 725                    removed = Some(item.clone());
 726                    cursor.next(cx);
 727                }
 728            }
 729            new_tree.append(cursor.suffix(cx), cx);
 730            new_tree
 731        };
 732        removed
 733    }
 734
 735    pub fn edit(
 736        &mut self,
 737        mut edits: Vec<Edit<T>>,
 738        cx: &<T::Summary as Summary>::Context,
 739    ) -> Vec<T> {
 740        if edits.is_empty() {
 741            return Vec::new();
 742        }
 743
 744        let mut removed = Vec::new();
 745        edits.sort_unstable_by_key(|item| item.key());
 746
 747        *self = {
 748            let mut cursor = self.cursor::<T::Key>(cx);
 749            let mut new_tree = SumTree::new(cx);
 750            let mut buffered_items = Vec::new();
 751
 752            cursor.seek(&T::Key::zero(cx), Bias::Left, cx);
 753            for edit in edits {
 754                let new_key = edit.key();
 755                let mut old_item = cursor.item();
 756
 757                if old_item
 758                    .as_ref()
 759                    .map_or(false, |old_item| old_item.key() < new_key)
 760                {
 761                    new_tree.extend(buffered_items.drain(..), cx);
 762                    let slice = cursor.slice(&new_key, Bias::Left, cx);
 763                    new_tree.append(slice, cx);
 764                    old_item = cursor.item();
 765                }
 766
 767                if let Some(old_item) = old_item {
 768                    if old_item.key() == new_key {
 769                        removed.push(old_item.clone());
 770                        cursor.next(cx);
 771                    }
 772                }
 773
 774                match edit {
 775                    Edit::Insert(item) => {
 776                        buffered_items.push(item);
 777                    }
 778                    Edit::Remove(_) => {}
 779                }
 780            }
 781
 782            new_tree.extend(buffered_items, cx);
 783            new_tree.append(cursor.suffix(cx), cx);
 784            new_tree
 785        };
 786
 787        removed
 788    }
 789
 790    pub fn get(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<&T> {
 791        let mut cursor = self.cursor::<T::Key>(cx);
 792        if cursor.seek(key, Bias::Left, cx) {
 793            cursor.item()
 794        } else {
 795            None
 796        }
 797    }
 798
 799    #[inline]
 800    pub fn contains(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> bool {
 801        self.get(key, cx).is_some()
 802    }
 803
 804    pub fn update<F, R>(
 805        &mut self,
 806        key: &T::Key,
 807        cx: &<T::Summary as Summary>::Context,
 808        f: F,
 809    ) -> Option<R>
 810    where
 811        F: FnOnce(&mut T) -> R,
 812    {
 813        let mut cursor = self.cursor::<T::Key>(cx);
 814        let mut new_tree = cursor.slice(key, Bias::Left, cx);
 815        let mut result = None;
 816        if Ord::cmp(key, &cursor.end(cx)) == Ordering::Equal {
 817            let mut updated = cursor.item().unwrap().clone();
 818            result = Some(f(&mut updated));
 819            new_tree.push(updated, cx);
 820            cursor.next(cx);
 821        }
 822        new_tree.append(cursor.suffix(cx), cx);
 823        drop(cursor);
 824        *self = new_tree;
 825        result
 826    }
 827
 828    pub fn retain<F: FnMut(&T) -> bool>(
 829        &mut self,
 830        cx: &<T::Summary as Summary>::Context,
 831        mut predicate: F,
 832    ) {
 833        let mut new_map = SumTree::new(cx);
 834
 835        let mut cursor = self.cursor::<T::Key>(cx);
 836        cursor.next(cx);
 837        while let Some(item) = cursor.item() {
 838            if predicate(&item) {
 839                new_map.push(item.clone(), cx);
 840            }
 841            cursor.next(cx);
 842        }
 843        drop(cursor);
 844
 845        *self = new_map;
 846    }
 847}
 848
 849impl<T, S> Default for SumTree<T>
 850where
 851    T: Item<Summary = S>,
 852    S: Summary<Context = ()>,
 853{
 854    fn default() -> Self {
 855        Self::new(&())
 856    }
 857}
 858
 859#[derive(Clone)]
 860pub enum Node<T: Item> {
 861    Internal {
 862        height: u8,
 863        summary: T::Summary,
 864        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 865        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
 866    },
 867    Leaf {
 868        summary: T::Summary,
 869        items: ArrayVec<T, { 2 * TREE_BASE }>,
 870        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 871    },
 872}
 873
 874impl<T> fmt::Debug for Node<T>
 875where
 876    T: Item + fmt::Debug,
 877    T::Summary: fmt::Debug,
 878{
 879    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 880        match self {
 881            Node::Internal {
 882                height,
 883                summary,
 884                child_summaries,
 885                child_trees,
 886            } => f
 887                .debug_struct("Internal")
 888                .field("height", height)
 889                .field("summary", summary)
 890                .field("child_summaries", child_summaries)
 891                .field("child_trees", child_trees)
 892                .finish(),
 893            Node::Leaf {
 894                summary,
 895                items,
 896                item_summaries,
 897            } => f
 898                .debug_struct("Leaf")
 899                .field("summary", summary)
 900                .field("items", items)
 901                .field("item_summaries", item_summaries)
 902                .finish(),
 903        }
 904    }
 905}
 906
 907impl<T: Item> Node<T> {
 908    fn is_leaf(&self) -> bool {
 909        matches!(self, Node::Leaf { .. })
 910    }
 911
 912    fn height(&self) -> u8 {
 913        match self {
 914            Node::Internal { height, .. } => *height,
 915            Node::Leaf { .. } => 0,
 916        }
 917    }
 918
 919    fn summary(&self) -> &T::Summary {
 920        match self {
 921            Node::Internal { summary, .. } => summary,
 922            Node::Leaf { summary, .. } => summary,
 923        }
 924    }
 925
 926    fn child_summaries(&self) -> &[T::Summary] {
 927        match self {
 928            Node::Internal {
 929                child_summaries, ..
 930            } => child_summaries.as_slice(),
 931            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
 932        }
 933    }
 934
 935    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
 936        match self {
 937            Node::Internal { child_trees, .. } => child_trees,
 938            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
 939        }
 940    }
 941
 942    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
 943        match self {
 944            Node::Leaf { items, .. } => items,
 945            Node::Internal { .. } => panic!("Internal nodes have no items"),
 946        }
 947    }
 948
 949    fn is_underflowing(&self) -> bool {
 950        match self {
 951            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
 952            Node::Leaf { items, .. } => items.len() < TREE_BASE,
 953        }
 954    }
 955}
 956
 957#[derive(Debug)]
 958pub enum Edit<T: KeyedItem> {
 959    Insert(T),
 960    Remove(T::Key),
 961}
 962
 963impl<T: KeyedItem> Edit<T> {
 964    fn key(&self) -> T::Key {
 965        match self {
 966            Edit::Insert(item) => item.key(),
 967            Edit::Remove(key) => key.clone(),
 968        }
 969    }
 970}
 971
 972fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
 973where
 974    T: 'a + Summary,
 975    I: Iterator<Item = &'a T>,
 976{
 977    let mut sum = T::zero(cx);
 978    for value in iter {
 979        sum.add_summary(value, cx);
 980    }
 981    sum
 982}
 983
 984#[cfg(test)]
 985mod tests {
 986    use super::*;
 987    use rand::{distributions, prelude::*};
 988    use std::cmp;
 989
 990    #[ctor::ctor]
 991    fn init_logger() {
 992        if std::env::var("RUST_LOG").is_ok() {
 993            env_logger::init();
 994        }
 995    }
 996
 997    #[test]
 998    fn test_extend_and_push_tree() {
 999        let mut tree1 = SumTree::default();
1000        tree1.extend(0..20, &());
1001
1002        let mut tree2 = SumTree::default();
1003        tree2.extend(50..100, &());
1004
1005        tree1.append(tree2, &());
1006        assert_eq!(
1007            tree1.items(&()),
1008            (0..20).chain(50..100).collect::<Vec<u8>>()
1009        );
1010    }
1011
1012    #[test]
1013    fn test_random() {
1014        let mut starting_seed = 0;
1015        if let Ok(value) = std::env::var("SEED") {
1016            starting_seed = value.parse().expect("invalid SEED variable");
1017        }
1018        let mut num_iterations = 100;
1019        if let Ok(value) = std::env::var("ITERATIONS") {
1020            num_iterations = value.parse().expect("invalid ITERATIONS variable");
1021        }
1022        let num_operations = std::env::var("OPERATIONS")
1023            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
1024
1025        for seed in starting_seed..(starting_seed + num_iterations) {
1026            eprintln!("seed = {}", seed);
1027            let mut rng = StdRng::seed_from_u64(seed);
1028
1029            let rng = &mut rng;
1030            let mut tree = SumTree::<u8>::default();
1031            let count = rng.gen_range(0..10);
1032            if rng.gen() {
1033                tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
1034            } else {
1035                let items = rng
1036                    .sample_iter(distributions::Standard)
1037                    .take(count)
1038                    .collect::<Vec<_>>();
1039                tree.par_extend(items, &());
1040            }
1041
1042            for _ in 0..num_operations {
1043                let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
1044                let splice_start = rng.gen_range(0..splice_end + 1);
1045                let count = rng.gen_range(0..10);
1046                let tree_end = tree.extent::<Count>(&());
1047                let new_items = rng
1048                    .sample_iter(distributions::Standard)
1049                    .take(count)
1050                    .collect::<Vec<u8>>();
1051
1052                let mut reference_items = tree.items(&());
1053                reference_items.splice(splice_start..splice_end, new_items.clone());
1054
1055                tree = {
1056                    let mut cursor = tree.cursor::<Count>(&());
1057                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
1058                    if rng.gen() {
1059                        new_tree.extend(new_items, &());
1060                    } else {
1061                        new_tree.par_extend(new_items, &());
1062                    }
1063                    cursor.seek(&Count(splice_end), Bias::Right, &());
1064                    new_tree.append(cursor.slice(&tree_end, Bias::Right, &()), &());
1065                    new_tree
1066                };
1067
1068                assert_eq!(tree.items(&()), reference_items);
1069                assert_eq!(
1070                    tree.iter().collect::<Vec<_>>(),
1071                    tree.cursor::<()>(&()).collect::<Vec<_>>()
1072                );
1073
1074                log::info!("tree items: {:?}", tree.items(&()));
1075
1076                let mut filter_cursor =
1077                    tree.filter::<_, Count>(&(), |summary| summary.contains_even);
1078                let expected_filtered_items = tree
1079                    .items(&())
1080                    .into_iter()
1081                    .enumerate()
1082                    .filter(|(_, item)| (item & 1) == 0)
1083                    .collect::<Vec<_>>();
1084
1085                let mut item_ix = if rng.gen() {
1086                    filter_cursor.next(&());
1087                    0
1088                } else {
1089                    filter_cursor.prev(&());
1090                    expected_filtered_items.len().saturating_sub(1)
1091                };
1092                while item_ix < expected_filtered_items.len() {
1093                    log::info!("filter_cursor, item_ix: {}", item_ix);
1094                    let actual_item = filter_cursor.item().unwrap();
1095                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
1096                    assert_eq!(actual_item, &reference_item);
1097                    assert_eq!(filter_cursor.start().0, reference_index);
1098                    log::info!("next");
1099                    filter_cursor.next(&());
1100                    item_ix += 1;
1101
1102                    while item_ix > 0 && rng.gen_bool(0.2) {
1103                        log::info!("prev");
1104                        filter_cursor.prev(&());
1105                        item_ix -= 1;
1106
1107                        if item_ix == 0 && rng.gen_bool(0.2) {
1108                            filter_cursor.prev(&());
1109                            assert_eq!(filter_cursor.item(), None);
1110                            assert_eq!(filter_cursor.start().0, 0);
1111                            filter_cursor.next(&());
1112                        }
1113                    }
1114                }
1115                assert_eq!(filter_cursor.item(), None);
1116
1117                let mut before_start = false;
1118                let mut cursor = tree.cursor::<Count>(&());
1119                let start_pos = rng.gen_range(0..=reference_items.len());
1120                cursor.seek(&Count(start_pos), Bias::Right, &());
1121                let mut pos = rng.gen_range(start_pos..=reference_items.len());
1122                cursor.seek_forward(&Count(pos), Bias::Right, &());
1123
1124                for i in 0..10 {
1125                    assert_eq!(cursor.start().0, pos);
1126
1127                    if pos > 0 {
1128                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
1129                    } else {
1130                        assert_eq!(cursor.prev_item(), None);
1131                    }
1132
1133                    if pos < reference_items.len() && !before_start {
1134                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
1135                    } else {
1136                        assert_eq!(cursor.item(), None);
1137                    }
1138
1139                    if before_start {
1140                        assert_eq!(cursor.next_item(), reference_items.first());
1141                    } else if pos + 1 < reference_items.len() {
1142                        assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
1143                    } else {
1144                        assert_eq!(cursor.next_item(), None);
1145                    }
1146
1147                    if i < 5 {
1148                        cursor.next(&());
1149                        if pos < reference_items.len() {
1150                            pos += 1;
1151                            before_start = false;
1152                        }
1153                    } else {
1154                        cursor.prev(&());
1155                        if pos == 0 {
1156                            before_start = true;
1157                        }
1158                        pos = pos.saturating_sub(1);
1159                    }
1160                }
1161            }
1162
1163            for _ in 0..10 {
1164                let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
1165                let start = rng.gen_range(0..end + 1);
1166                let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
1167                let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
1168
1169                let mut cursor = tree.cursor::<Count>(&());
1170                cursor.seek(&Count(start), start_bias, &());
1171                let slice = cursor.slice(&Count(end), end_bias, &());
1172
1173                cursor.seek(&Count(start), start_bias, &());
1174                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
1175
1176                assert_eq!(summary.0, slice.summary().sum);
1177            }
1178        }
1179    }
1180
1181    #[test]
1182    fn test_cursor() {
1183        // Empty tree
1184        let tree = SumTree::<u8>::default();
1185        let mut cursor = tree.cursor::<IntegersSummary>(&());
1186        assert_eq!(
1187            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
1188            Vec::<u8>::new()
1189        );
1190        assert_eq!(cursor.item(), None);
1191        assert_eq!(cursor.prev_item(), None);
1192        assert_eq!(cursor.next_item(), None);
1193        assert_eq!(cursor.start().sum, 0);
1194        cursor.prev(&());
1195        assert_eq!(cursor.item(), None);
1196        assert_eq!(cursor.prev_item(), None);
1197        assert_eq!(cursor.next_item(), None);
1198        assert_eq!(cursor.start().sum, 0);
1199        cursor.next(&());
1200        assert_eq!(cursor.item(), None);
1201        assert_eq!(cursor.prev_item(), None);
1202        assert_eq!(cursor.next_item(), None);
1203        assert_eq!(cursor.start().sum, 0);
1204
1205        // Single-element tree
1206        let mut tree = SumTree::<u8>::default();
1207        tree.extend(vec![1], &());
1208        let mut cursor = tree.cursor::<IntegersSummary>(&());
1209        assert_eq!(
1210            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
1211            Vec::<u8>::new()
1212        );
1213        assert_eq!(cursor.item(), Some(&1));
1214        assert_eq!(cursor.prev_item(), None);
1215        assert_eq!(cursor.next_item(), None);
1216        assert_eq!(cursor.start().sum, 0);
1217
1218        cursor.next(&());
1219        assert_eq!(cursor.item(), None);
1220        assert_eq!(cursor.prev_item(), Some(&1));
1221        assert_eq!(cursor.next_item(), None);
1222        assert_eq!(cursor.start().sum, 1);
1223
1224        cursor.prev(&());
1225        assert_eq!(cursor.item(), Some(&1));
1226        assert_eq!(cursor.prev_item(), None);
1227        assert_eq!(cursor.next_item(), None);
1228        assert_eq!(cursor.start().sum, 0);
1229
1230        let mut cursor = tree.cursor::<IntegersSummary>(&());
1231        assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
1232        assert_eq!(cursor.item(), None);
1233        assert_eq!(cursor.prev_item(), Some(&1));
1234        assert_eq!(cursor.next_item(), None);
1235        assert_eq!(cursor.start().sum, 1);
1236
1237        cursor.seek(&Count(0), Bias::Right, &());
1238        assert_eq!(
1239            cursor
1240                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
1241                .items(&()),
1242            [1]
1243        );
1244        assert_eq!(cursor.item(), None);
1245        assert_eq!(cursor.prev_item(), Some(&1));
1246        assert_eq!(cursor.next_item(), None);
1247        assert_eq!(cursor.start().sum, 1);
1248
1249        // Multiple-element tree
1250        let mut tree = SumTree::default();
1251        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
1252        let mut cursor = tree.cursor::<IntegersSummary>(&());
1253
1254        assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
1255        assert_eq!(cursor.item(), Some(&3));
1256        assert_eq!(cursor.prev_item(), Some(&2));
1257        assert_eq!(cursor.next_item(), Some(&4));
1258        assert_eq!(cursor.start().sum, 3);
1259
1260        cursor.next(&());
1261        assert_eq!(cursor.item(), Some(&4));
1262        assert_eq!(cursor.prev_item(), Some(&3));
1263        assert_eq!(cursor.next_item(), Some(&5));
1264        assert_eq!(cursor.start().sum, 6);
1265
1266        cursor.next(&());
1267        assert_eq!(cursor.item(), Some(&5));
1268        assert_eq!(cursor.prev_item(), Some(&4));
1269        assert_eq!(cursor.next_item(), Some(&6));
1270        assert_eq!(cursor.start().sum, 10);
1271
1272        cursor.next(&());
1273        assert_eq!(cursor.item(), Some(&6));
1274        assert_eq!(cursor.prev_item(), Some(&5));
1275        assert_eq!(cursor.next_item(), None);
1276        assert_eq!(cursor.start().sum, 15);
1277
1278        cursor.next(&());
1279        cursor.next(&());
1280        assert_eq!(cursor.item(), None);
1281        assert_eq!(cursor.prev_item(), Some(&6));
1282        assert_eq!(cursor.next_item(), None);
1283        assert_eq!(cursor.start().sum, 21);
1284
1285        cursor.prev(&());
1286        assert_eq!(cursor.item(), Some(&6));
1287        assert_eq!(cursor.prev_item(), Some(&5));
1288        assert_eq!(cursor.next_item(), None);
1289        assert_eq!(cursor.start().sum, 15);
1290
1291        cursor.prev(&());
1292        assert_eq!(cursor.item(), Some(&5));
1293        assert_eq!(cursor.prev_item(), Some(&4));
1294        assert_eq!(cursor.next_item(), Some(&6));
1295        assert_eq!(cursor.start().sum, 10);
1296
1297        cursor.prev(&());
1298        assert_eq!(cursor.item(), Some(&4));
1299        assert_eq!(cursor.prev_item(), Some(&3));
1300        assert_eq!(cursor.next_item(), Some(&5));
1301        assert_eq!(cursor.start().sum, 6);
1302
1303        cursor.prev(&());
1304        assert_eq!(cursor.item(), Some(&3));
1305        assert_eq!(cursor.prev_item(), Some(&2));
1306        assert_eq!(cursor.next_item(), Some(&4));
1307        assert_eq!(cursor.start().sum, 3);
1308
1309        cursor.prev(&());
1310        assert_eq!(cursor.item(), Some(&2));
1311        assert_eq!(cursor.prev_item(), Some(&1));
1312        assert_eq!(cursor.next_item(), Some(&3));
1313        assert_eq!(cursor.start().sum, 1);
1314
1315        cursor.prev(&());
1316        assert_eq!(cursor.item(), Some(&1));
1317        assert_eq!(cursor.prev_item(), None);
1318        assert_eq!(cursor.next_item(), Some(&2));
1319        assert_eq!(cursor.start().sum, 0);
1320
1321        cursor.prev(&());
1322        assert_eq!(cursor.item(), None);
1323        assert_eq!(cursor.prev_item(), None);
1324        assert_eq!(cursor.next_item(), Some(&1));
1325        assert_eq!(cursor.start().sum, 0);
1326
1327        cursor.next(&());
1328        assert_eq!(cursor.item(), Some(&1));
1329        assert_eq!(cursor.prev_item(), None);
1330        assert_eq!(cursor.next_item(), Some(&2));
1331        assert_eq!(cursor.start().sum, 0);
1332
1333        let mut cursor = tree.cursor::<IntegersSummary>(&());
1334        assert_eq!(
1335            cursor
1336                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
1337                .items(&()),
1338            tree.items(&())
1339        );
1340        assert_eq!(cursor.item(), None);
1341        assert_eq!(cursor.prev_item(), Some(&6));
1342        assert_eq!(cursor.next_item(), None);
1343        assert_eq!(cursor.start().sum, 21);
1344
1345        cursor.seek(&Count(3), Bias::Right, &());
1346        assert_eq!(
1347            cursor
1348                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
1349                .items(&()),
1350            [4, 5, 6]
1351        );
1352        assert_eq!(cursor.item(), None);
1353        assert_eq!(cursor.prev_item(), Some(&6));
1354        assert_eq!(cursor.next_item(), None);
1355        assert_eq!(cursor.start().sum, 21);
1356
1357        // Seeking can bias left or right
1358        cursor.seek(&Count(1), Bias::Left, &());
1359        assert_eq!(cursor.item(), Some(&1));
1360        cursor.seek(&Count(1), Bias::Right, &());
1361        assert_eq!(cursor.item(), Some(&2));
1362
1363        // Slicing without resetting starts from where the cursor is parked at.
1364        cursor.seek(&Count(1), Bias::Right, &());
1365        assert_eq!(
1366            cursor.slice(&Count(3), Bias::Right, &()).items(&()),
1367            vec![2, 3]
1368        );
1369        assert_eq!(
1370            cursor.slice(&Count(6), Bias::Left, &()).items(&()),
1371            vec![4, 5]
1372        );
1373        assert_eq!(
1374            cursor.slice(&Count(6), Bias::Right, &()).items(&()),
1375            vec![6]
1376        );
1377    }
1378
1379    #[test]
1380    fn test_edit() {
1381        let mut tree = SumTree::<u8>::default();
1382
1383        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1384        assert_eq!(tree.items(&()), vec![0, 1, 2]);
1385        assert_eq!(removed, Vec::<u8>::new());
1386        assert_eq!(tree.get(&0, &()), Some(&0));
1387        assert_eq!(tree.get(&1, &()), Some(&1));
1388        assert_eq!(tree.get(&2, &()), Some(&2));
1389        assert_eq!(tree.get(&4, &()), None);
1390
1391        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1392        assert_eq!(tree.items(&()), vec![1, 2, 4]);
1393        assert_eq!(removed, vec![0, 2]);
1394        assert_eq!(tree.get(&0, &()), None);
1395        assert_eq!(tree.get(&1, &()), Some(&1));
1396        assert_eq!(tree.get(&2, &()), Some(&2));
1397        assert_eq!(tree.get(&4, &()), Some(&4));
1398    }
1399
1400    #[test]
1401    fn test_from_iter() {
1402        assert_eq!(
1403            SumTree::from_iter(0..100, &()).items(&()),
1404            (0..100).collect::<Vec<_>>()
1405        );
1406
1407        // Ensure `from_iter` works correctly when the given iterator restarts
1408        // after calling `next` if `None` was already returned.
1409        let mut ix = 0;
1410        let iterator = std::iter::from_fn(|| {
1411            ix = (ix + 1) % 2;
1412            if ix == 1 {
1413                Some(1)
1414            } else {
1415                None
1416            }
1417        });
1418        assert_eq!(SumTree::from_iter(iterator, &()).items(&()), vec![1]);
1419    }
1420
1421    #[derive(Clone, Default, Debug)]
1422    pub struct IntegersSummary {
1423        count: usize,
1424        sum: usize,
1425        contains_even: bool,
1426        max: u8,
1427    }
1428
1429    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1430    struct Count(usize);
1431
1432    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1433    struct Sum(usize);
1434
1435    impl Item for u8 {
1436        type Summary = IntegersSummary;
1437
1438        fn summary(&self, _cx: &()) -> Self::Summary {
1439            IntegersSummary {
1440                count: 1,
1441                sum: *self as usize,
1442                contains_even: (*self & 1) == 0,
1443                max: *self,
1444            }
1445        }
1446    }
1447
1448    impl KeyedItem for u8 {
1449        type Key = u8;
1450
1451        fn key(&self) -> Self::Key {
1452            *self
1453        }
1454    }
1455
1456    impl Summary for IntegersSummary {
1457        type Context = ();
1458
1459        fn zero(_cx: &()) -> Self {
1460            Default::default()
1461        }
1462
1463        fn add_summary(&mut self, other: &Self, _: &()) {
1464            self.count += other.count;
1465            self.sum += other.sum;
1466            self.contains_even |= other.contains_even;
1467            self.max = cmp::max(self.max, other.max);
1468        }
1469    }
1470
1471    impl Dimension<'_, IntegersSummary> for u8 {
1472        fn zero(_cx: &()) -> Self {
1473            Default::default()
1474        }
1475
1476        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1477            *self = summary.max;
1478        }
1479    }
1480
1481    impl Dimension<'_, IntegersSummary> for Count {
1482        fn zero(_cx: &()) -> Self {
1483            Default::default()
1484        }
1485
1486        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1487            self.0 += summary.count;
1488        }
1489    }
1490
1491    impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count {
1492        fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1493            self.0.cmp(&cursor_location.count)
1494        }
1495    }
1496
1497    impl Dimension<'_, IntegersSummary> for Sum {
1498        fn zero(_cx: &()) -> Self {
1499            Default::default()
1500        }
1501
1502        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1503            self.0 += summary.sum;
1504        }
1505    }
1506}