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