sum_tree.rs

   1mod cursor;
   2mod tree_map;
   3
   4use arrayvec::ArrayVec;
   5pub use cursor::{Cursor, FilterCursor, Iter};
   6use std::marker::PhantomData;
   7use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
   8pub use tree_map::{MapSeekTarget, TreeMap, TreeSet};
   9
  10#[cfg(test)]
  11const TREE_BASE: usize = 2;
  12#[cfg(not(test))]
  13const TREE_BASE: usize = 6;
  14
  15pub trait Item: Clone {
  16    type Summary: Summary;
  17
  18    fn summary(&self) -> Self::Summary;
  19}
  20
  21pub trait KeyedItem: Item {
  22    type Key: for<'a> Dimension<'a, Self::Summary> + Ord;
  23
  24    fn key(&self) -> Self::Key;
  25}
  26
  27pub trait Summary: Default + Clone + fmt::Debug {
  28    type Context;
  29
  30    fn add_summary(&mut self, summary: &Self, cx: &Self::Context);
  31}
  32
  33pub trait Dimension<'a, S: Summary>: Clone + fmt::Debug + Default {
  34    fn add_summary(&mut self, _summary: &'a S, _: &S::Context);
  35
  36    fn from_summary(summary: &'a S, cx: &S::Context) -> Self {
  37        let mut dimension = Self::default();
  38        dimension.add_summary(summary, cx);
  39        dimension
  40    }
  41}
  42
  43impl<'a, T: Summary> Dimension<'a, T> for T {
  44    fn add_summary(&mut self, summary: &'a T, cx: &T::Context) {
  45        Summary::add_summary(self, summary, cx);
  46    }
  47}
  48
  49pub trait SeekTarget<'a, S: Summary, D: Dimension<'a, S>>: fmt::Debug {
  50    fn cmp(&self, cursor_location: &D, cx: &S::Context) -> Ordering;
  51}
  52
  53impl<'a, S: Summary, D: Dimension<'a, S> + Ord> SeekTarget<'a, S, D> for D {
  54    fn cmp(&self, cursor_location: &Self, _: &S::Context) -> Ordering {
  55        Ord::cmp(self, cursor_location)
  56    }
  57}
  58
  59impl<'a, T: Summary> Dimension<'a, T> for () {
  60    fn add_summary(&mut self, _: &'a T, _: &T::Context) {}
  61}
  62
  63impl<'a, T: Summary, D1: Dimension<'a, T>, D2: Dimension<'a, T>> Dimension<'a, T> for (D1, D2) {
  64    fn add_summary(&mut self, summary: &'a T, cx: &T::Context) {
  65        self.0.add_summary(summary, cx);
  66        self.1.add_summary(summary, cx);
  67    }
  68}
  69
  70impl<'a, S: Summary, D1: SeekTarget<'a, S, D1> + Dimension<'a, S>, D2: Dimension<'a, S>>
  71    SeekTarget<'a, S, (D1, D2)> for D1
  72{
  73    fn cmp(&self, cursor_location: &(D1, D2), cx: &S::Context) -> Ordering {
  74        self.cmp(&cursor_location.0, cx)
  75    }
  76}
  77
  78struct End<D>(PhantomData<D>);
  79
  80impl<D> End<D> {
  81    fn new() -> Self {
  82        Self(PhantomData)
  83    }
  84}
  85
  86impl<'a, S: Summary, D: Dimension<'a, S>> SeekTarget<'a, S, D> for End<D> {
  87    fn cmp(&self, _: &D, _: &S::Context) -> Ordering {
  88        Ordering::Greater
  89    }
  90}
  91
  92impl<D> fmt::Debug for End<D> {
  93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  94        f.debug_tuple("End").finish()
  95    }
  96}
  97
  98#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Default)]
  99pub enum Bias {
 100    #[default]
 101    Left,
 102    Right,
 103}
 104
 105#[derive(Debug, Clone)]
 106pub struct SumTree<T: Item>(Arc<Node<T>>);
 107
 108impl<T: Item> SumTree<T> {
 109    pub fn new() -> Self {
 110        SumTree(Arc::new(Node::Leaf {
 111            summary: T::Summary::default(),
 112            items: ArrayVec::new(),
 113            item_summaries: ArrayVec::new(),
 114        }))
 115    }
 116
 117    pub fn from_item(item: T, cx: &<T::Summary as Summary>::Context) -> Self {
 118        let mut tree = Self::new();
 119        tree.push(item, cx);
 120        tree
 121    }
 122
 123    pub fn from_iter<I: IntoIterator<Item = T>>(
 124        iter: I,
 125        cx: &<T::Summary as Summary>::Context,
 126    ) -> Self {
 127        let mut tree = Self::new();
 128        tree.extend(iter, cx);
 129        tree
 130    }
 131
 132    #[allow(unused)]
 133    pub fn items(&self, cx: &<T::Summary as Summary>::Context) -> Vec<T> {
 134        let mut items = Vec::new();
 135        let mut cursor = self.cursor::<()>();
 136        cursor.next(cx);
 137        while let Some(item) = cursor.item() {
 138            items.push(item.clone());
 139            cursor.next(cx);
 140        }
 141        items
 142    }
 143
 144    pub fn iter(&self) -> Iter<T> {
 145        Iter::new(self)
 146    }
 147
 148    pub fn cursor<'a, S>(&'a self) -> Cursor<T, S>
 149    where
 150        S: Dimension<'a, T::Summary>,
 151    {
 152        Cursor::new(self)
 153    }
 154
 155    /// Note: If the summary type requires a non `()` context, then the filter cursor
 156    /// that is returned cannot be used with Rust's iterators.
 157    pub fn filter<'a, F, U>(&'a self, filter_node: F) -> FilterCursor<F, T, U>
 158    where
 159        F: FnMut(&T::Summary) -> bool,
 160        U: Dimension<'a, T::Summary>,
 161    {
 162        FilterCursor::new(self, filter_node)
 163    }
 164
 165    #[allow(dead_code)]
 166    pub fn first(&self) -> Option<&T> {
 167        self.leftmost_leaf().0.items().first()
 168    }
 169
 170    pub fn last(&self) -> Option<&T> {
 171        self.rightmost_leaf().0.items().last()
 172    }
 173
 174    pub fn update_last(&mut self, f: impl FnOnce(&mut T), cx: &<T::Summary as Summary>::Context) {
 175        self.update_last_recursive(f, cx);
 176    }
 177
 178    fn update_last_recursive(
 179        &mut self,
 180        f: impl FnOnce(&mut T),
 181        cx: &<T::Summary as Summary>::Context,
 182    ) -> Option<T::Summary> {
 183        match Arc::make_mut(&mut self.0) {
 184            Node::Internal {
 185                summary,
 186                child_summaries,
 187                child_trees,
 188                ..
 189            } => {
 190                let last_summary = child_summaries.last_mut().unwrap();
 191                let last_child = child_trees.last_mut().unwrap();
 192                *last_summary = last_child.update_last_recursive(f, cx).unwrap();
 193                *summary = sum(child_summaries.iter(), cx);
 194                Some(summary.clone())
 195            }
 196            Node::Leaf {
 197                summary,
 198                items,
 199                item_summaries,
 200            } => {
 201                if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut())
 202                {
 203                    (f)(item);
 204                    *item_summary = item.summary();
 205                    *summary = sum(item_summaries.iter(), cx);
 206                    Some(summary.clone())
 207                } else {
 208                    None
 209                }
 210            }
 211        }
 212    }
 213
 214    pub fn extent<'a, D: Dimension<'a, T::Summary>>(
 215        &'a self,
 216        cx: &<T::Summary as Summary>::Context,
 217    ) -> D {
 218        let mut extent = D::default();
 219        match self.0.as_ref() {
 220            Node::Internal { summary, .. } | Node::Leaf { summary, .. } => {
 221                extent.add_summary(summary, cx);
 222            }
 223        }
 224        extent
 225    }
 226
 227    pub fn summary(&self) -> &T::Summary {
 228        match self.0.as_ref() {
 229            Node::Internal { summary, .. } => summary,
 230            Node::Leaf { summary, .. } => summary,
 231        }
 232    }
 233
 234    pub fn is_empty(&self) -> bool {
 235        match self.0.as_ref() {
 236            Node::Internal { .. } => false,
 237            Node::Leaf { items, .. } => items.is_empty(),
 238        }
 239    }
 240
 241    pub fn extend<I>(&mut self, iter: I, cx: &<T::Summary as Summary>::Context)
 242    where
 243        I: IntoIterator<Item = T>,
 244    {
 245        let mut leaf: Option<Node<T>> = None;
 246
 247        for item in iter {
 248            if leaf.is_some() && leaf.as_ref().unwrap().items().len() == 2 * TREE_BASE {
 249                self.append(SumTree(Arc::new(leaf.take().unwrap())), cx);
 250            }
 251
 252            if leaf.is_none() {
 253                leaf = Some(Node::Leaf::<T> {
 254                    summary: T::Summary::default(),
 255                    items: ArrayVec::new(),
 256                    item_summaries: ArrayVec::new(),
 257                });
 258            }
 259
 260            if let Some(Node::Leaf {
 261                summary,
 262                items,
 263                item_summaries,
 264            }) = leaf.as_mut()
 265            {
 266                let item_summary = item.summary();
 267                <T::Summary as Summary>::add_summary(summary, &item_summary, cx);
 268                items.push(item);
 269                item_summaries.push(item_summary);
 270            } else {
 271                unreachable!()
 272            }
 273        }
 274
 275        if leaf.is_some() {
 276            self.append(SumTree(Arc::new(leaf.take().unwrap())), cx);
 277        }
 278    }
 279
 280    pub fn push(&mut self, item: T, cx: &<T::Summary as Summary>::Context) {
 281        let summary = item.summary();
 282        self.append(
 283            SumTree(Arc::new(Node::Leaf {
 284                summary: summary.clone(),
 285                items: ArrayVec::from_iter(Some(item)),
 286                item_summaries: ArrayVec::from_iter(Some(summary)),
 287            })),
 288            cx,
 289        );
 290    }
 291
 292    pub fn append(&mut self, other: Self, cx: &<T::Summary as Summary>::Context) {
 293        if !other.0.is_leaf() || !other.0.items().is_empty() {
 294            if self.0.height() < other.0.height() {
 295                for tree in other.0.child_trees() {
 296                    self.append(tree.clone(), cx);
 297                }
 298            } else if let Some(split_tree) = self.push_tree_recursive(other, cx) {
 299                *self = Self::from_child_trees(self.clone(), split_tree, cx);
 300            }
 301        }
 302    }
 303
 304    fn push_tree_recursive(
 305        &mut self,
 306        other: SumTree<T>,
 307        cx: &<T::Summary as Summary>::Context,
 308    ) -> Option<SumTree<T>> {
 309        match Arc::make_mut(&mut self.0) {
 310            Node::Internal {
 311                height,
 312                summary,
 313                child_summaries,
 314                child_trees,
 315                ..
 316            } => {
 317                let other_node = other.0.clone();
 318                <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
 319
 320                let height_delta = *height - other_node.height();
 321                let mut summaries_to_append = ArrayVec::<T::Summary, { 2 * TREE_BASE }>::new();
 322                let mut trees_to_append = ArrayVec::<SumTree<T>, { 2 * TREE_BASE }>::new();
 323                if height_delta == 0 {
 324                    summaries_to_append.extend(other_node.child_summaries().iter().cloned());
 325                    trees_to_append.extend(other_node.child_trees().iter().cloned());
 326                } else if height_delta == 1 && !other_node.is_underflowing() {
 327                    summaries_to_append.push(other_node.summary().clone());
 328                    trees_to_append.push(other)
 329                } else {
 330                    let tree_to_append = child_trees
 331                        .last_mut()
 332                        .unwrap()
 333                        .push_tree_recursive(other, cx);
 334                    *child_summaries.last_mut().unwrap() =
 335                        child_trees.last().unwrap().0.summary().clone();
 336
 337                    if let Some(split_tree) = tree_to_append {
 338                        summaries_to_append.push(split_tree.0.summary().clone());
 339                        trees_to_append.push(split_tree);
 340                    }
 341                }
 342
 343                let child_count = child_trees.len() + trees_to_append.len();
 344                if child_count > 2 * TREE_BASE {
 345                    let left_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
 346                    let right_summaries: ArrayVec<_, { 2 * TREE_BASE }>;
 347                    let left_trees;
 348                    let right_trees;
 349
 350                    let midpoint = (child_count + child_count % 2) / 2;
 351                    {
 352                        let mut all_summaries = child_summaries
 353                            .iter()
 354                            .chain(summaries_to_append.iter())
 355                            .cloned();
 356                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
 357                        right_summaries = all_summaries.collect();
 358                        let mut all_trees =
 359                            child_trees.iter().chain(trees_to_append.iter()).cloned();
 360                        left_trees = all_trees.by_ref().take(midpoint).collect();
 361                        right_trees = all_trees.collect();
 362                    }
 363                    *summary = sum(left_summaries.iter(), cx);
 364                    *child_summaries = left_summaries;
 365                    *child_trees = left_trees;
 366
 367                    Some(SumTree(Arc::new(Node::Internal {
 368                        height: *height,
 369                        summary: sum(right_summaries.iter(), cx),
 370                        child_summaries: right_summaries,
 371                        child_trees: right_trees,
 372                    })))
 373                } else {
 374                    child_summaries.extend(summaries_to_append);
 375                    child_trees.extend(trees_to_append);
 376                    None
 377                }
 378            }
 379            Node::Leaf {
 380                summary,
 381                items,
 382                item_summaries,
 383            } => {
 384                let other_node = other.0;
 385
 386                let child_count = items.len() + other_node.items().len();
 387                if child_count > 2 * TREE_BASE {
 388                    let left_items;
 389                    let right_items;
 390                    let left_summaries;
 391                    let right_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>;
 392
 393                    let midpoint = (child_count + child_count % 2) / 2;
 394                    {
 395                        let mut all_items = items.iter().chain(other_node.items().iter()).cloned();
 396                        left_items = all_items.by_ref().take(midpoint).collect();
 397                        right_items = all_items.collect();
 398
 399                        let mut all_summaries = item_summaries
 400                            .iter()
 401                            .chain(other_node.child_summaries())
 402                            .cloned();
 403                        left_summaries = all_summaries.by_ref().take(midpoint).collect();
 404                        right_summaries = all_summaries.collect();
 405                    }
 406                    *items = left_items;
 407                    *item_summaries = left_summaries;
 408                    *summary = sum(item_summaries.iter(), cx);
 409                    Some(SumTree(Arc::new(Node::Leaf {
 410                        items: right_items,
 411                        summary: sum(right_summaries.iter(), cx),
 412                        item_summaries: right_summaries,
 413                    })))
 414                } else {
 415                    <T::Summary as Summary>::add_summary(summary, other_node.summary(), cx);
 416                    items.extend(other_node.items().iter().cloned());
 417                    item_summaries.extend(other_node.child_summaries().iter().cloned());
 418                    None
 419                }
 420            }
 421        }
 422    }
 423
 424    fn from_child_trees(
 425        left: SumTree<T>,
 426        right: SumTree<T>,
 427        cx: &<T::Summary as Summary>::Context,
 428    ) -> Self {
 429        let height = left.0.height() + 1;
 430        let mut child_summaries = ArrayVec::new();
 431        child_summaries.push(left.0.summary().clone());
 432        child_summaries.push(right.0.summary().clone());
 433        let mut child_trees = ArrayVec::new();
 434        child_trees.push(left);
 435        child_trees.push(right);
 436        SumTree(Arc::new(Node::Internal {
 437            height,
 438            summary: sum(child_summaries.iter(), cx),
 439            child_summaries,
 440            child_trees,
 441        }))
 442    }
 443
 444    fn leftmost_leaf(&self) -> &Self {
 445        match *self.0 {
 446            Node::Leaf { .. } => self,
 447            Node::Internal {
 448                ref child_trees, ..
 449            } => child_trees.first().unwrap().leftmost_leaf(),
 450        }
 451    }
 452
 453    fn rightmost_leaf(&self) -> &Self {
 454        match *self.0 {
 455            Node::Leaf { .. } => self,
 456            Node::Internal {
 457                ref child_trees, ..
 458            } => child_trees.last().unwrap().rightmost_leaf(),
 459        }
 460    }
 461
 462    #[cfg(debug_assertions)]
 463    pub fn _debug_entries(&self) -> Vec<&T> {
 464        self.iter().collect::<Vec<_>>()
 465    }
 466}
 467
 468impl<T: Item + PartialEq> PartialEq for SumTree<T> {
 469    fn eq(&self, other: &Self) -> bool {
 470        self.iter().eq(other.iter())
 471    }
 472}
 473
 474impl<T: Item + Eq> Eq for SumTree<T> {}
 475
 476impl<T: KeyedItem> SumTree<T> {
 477    pub fn insert_or_replace(
 478        &mut self,
 479        item: T,
 480        cx: &<T::Summary as Summary>::Context,
 481    ) -> Option<T> {
 482        let mut replaced = None;
 483        *self = {
 484            let mut cursor = self.cursor::<T::Key>();
 485            let mut new_tree = cursor.slice(&item.key(), Bias::Left, cx);
 486            if let Some(cursor_item) = cursor.item() {
 487                if cursor_item.key() == item.key() {
 488                    replaced = Some(cursor_item.clone());
 489                    cursor.next(cx);
 490                }
 491            }
 492            new_tree.push(item, cx);
 493            new_tree.append(cursor.suffix(cx), cx);
 494            new_tree
 495        };
 496        replaced
 497    }
 498
 499    pub fn remove(&mut self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<T> {
 500        let mut removed = None;
 501        *self = {
 502            let mut cursor = self.cursor::<T::Key>();
 503            let mut new_tree = cursor.slice(key, Bias::Left, cx);
 504            if let Some(item) = cursor.item() {
 505                if item.key() == *key {
 506                    removed = Some(item.clone());
 507                    cursor.next(cx);
 508                }
 509            }
 510            new_tree.append(cursor.suffix(cx), cx);
 511            new_tree
 512        };
 513        removed
 514    }
 515
 516    pub fn edit(
 517        &mut self,
 518        mut edits: Vec<Edit<T>>,
 519        cx: &<T::Summary as Summary>::Context,
 520    ) -> Vec<T> {
 521        if edits.is_empty() {
 522            return Vec::new();
 523        }
 524
 525        let mut removed = Vec::new();
 526        edits.sort_unstable_by_key(|item| item.key());
 527
 528        *self = {
 529            let mut cursor = self.cursor::<T::Key>();
 530            let mut new_tree = SumTree::new();
 531            let mut buffered_items = Vec::new();
 532
 533            cursor.seek(&T::Key::default(), Bias::Left, cx);
 534            for edit in edits {
 535                let new_key = edit.key();
 536                let mut old_item = cursor.item();
 537
 538                if old_item
 539                    .as_ref()
 540                    .map_or(false, |old_item| old_item.key() < new_key)
 541                {
 542                    new_tree.extend(buffered_items.drain(..), cx);
 543                    let slice = cursor.slice(&new_key, Bias::Left, cx);
 544                    new_tree.append(slice, cx);
 545                    old_item = cursor.item();
 546                }
 547
 548                if let Some(old_item) = old_item {
 549                    if old_item.key() == new_key {
 550                        removed.push(old_item.clone());
 551                        cursor.next(cx);
 552                    }
 553                }
 554
 555                match edit {
 556                    Edit::Insert(item) => {
 557                        buffered_items.push(item);
 558                    }
 559                    Edit::Remove(_) => {}
 560                }
 561            }
 562
 563            new_tree.extend(buffered_items, cx);
 564            new_tree.append(cursor.suffix(cx), cx);
 565            new_tree
 566        };
 567
 568        removed
 569    }
 570
 571    pub fn get(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<&T> {
 572        let mut cursor = self.cursor::<T::Key>();
 573        if cursor.seek(key, Bias::Left, cx) {
 574            cursor.item()
 575        } else {
 576            None
 577        }
 578    }
 579}
 580
 581impl<T: Item> Default for SumTree<T> {
 582    fn default() -> Self {
 583        Self::new()
 584    }
 585}
 586
 587#[derive(Clone, Debug)]
 588pub enum Node<T: Item> {
 589    Internal {
 590        height: u8,
 591        summary: T::Summary,
 592        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 593        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
 594    },
 595    Leaf {
 596        summary: T::Summary,
 597        items: ArrayVec<T, { 2 * TREE_BASE }>,
 598        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 599    },
 600}
 601
 602impl<T: Item> Node<T> {
 603    fn is_leaf(&self) -> bool {
 604        matches!(self, Node::Leaf { .. })
 605    }
 606
 607    fn height(&self) -> u8 {
 608        match self {
 609            Node::Internal { height, .. } => *height,
 610            Node::Leaf { .. } => 0,
 611        }
 612    }
 613
 614    fn summary(&self) -> &T::Summary {
 615        match self {
 616            Node::Internal { summary, .. } => summary,
 617            Node::Leaf { summary, .. } => summary,
 618        }
 619    }
 620
 621    fn child_summaries(&self) -> &[T::Summary] {
 622        match self {
 623            Node::Internal {
 624                child_summaries, ..
 625            } => child_summaries.as_slice(),
 626            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
 627        }
 628    }
 629
 630    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
 631        match self {
 632            Node::Internal { child_trees, .. } => child_trees,
 633            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
 634        }
 635    }
 636
 637    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
 638        match self {
 639            Node::Leaf { items, .. } => items,
 640            Node::Internal { .. } => panic!("Internal nodes have no items"),
 641        }
 642    }
 643
 644    fn is_underflowing(&self) -> bool {
 645        match self {
 646            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
 647            Node::Leaf { items, .. } => items.len() < TREE_BASE,
 648        }
 649    }
 650}
 651
 652#[derive(Debug)]
 653pub enum Edit<T: KeyedItem> {
 654    Insert(T),
 655    Remove(T::Key),
 656}
 657
 658impl<T: KeyedItem> Edit<T> {
 659    fn key(&self) -> T::Key {
 660        match self {
 661            Edit::Insert(item) => item.key(),
 662            Edit::Remove(key) => key.clone(),
 663        }
 664    }
 665}
 666
 667fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
 668where
 669    T: 'a + Summary,
 670    I: Iterator<Item = &'a T>,
 671{
 672    let mut sum = T::default();
 673    for value in iter {
 674        sum.add_summary(value, cx);
 675    }
 676    sum
 677}
 678
 679#[cfg(test)]
 680mod tests {
 681    use super::*;
 682    use rand::{distributions, prelude::*};
 683    use std::cmp;
 684
 685    #[ctor::ctor]
 686    fn init_logger() {
 687        if std::env::var("RUST_LOG").is_ok() {
 688            env_logger::init();
 689        }
 690    }
 691
 692    #[test]
 693    fn test_extend_and_push_tree() {
 694        let mut tree1 = SumTree::new();
 695        tree1.extend(0..20, &());
 696
 697        let mut tree2 = SumTree::new();
 698        tree2.extend(50..100, &());
 699
 700        tree1.append(tree2, &());
 701        assert_eq!(
 702            tree1.items(&()),
 703            (0..20).chain(50..100).collect::<Vec<u8>>()
 704        );
 705    }
 706
 707    #[test]
 708    fn test_random() {
 709        let mut starting_seed = 0;
 710        if let Ok(value) = std::env::var("SEED") {
 711            starting_seed = value.parse().expect("invalid SEED variable");
 712        }
 713        let mut num_iterations = 100;
 714        if let Ok(value) = std::env::var("ITERATIONS") {
 715            num_iterations = value.parse().expect("invalid ITERATIONS variable");
 716        }
 717        let num_operations = std::env::var("OPERATIONS")
 718            .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable"));
 719
 720        for seed in starting_seed..(starting_seed + num_iterations) {
 721            eprintln!("seed = {}", seed);
 722            let mut rng = StdRng::seed_from_u64(seed);
 723
 724            let rng = &mut rng;
 725            let mut tree = SumTree::<u8>::new();
 726            let count = rng.gen_range(0..10);
 727            tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
 728
 729            for _ in 0..num_operations {
 730                let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 731                let splice_start = rng.gen_range(0..splice_end + 1);
 732                let count = rng.gen_range(0..3);
 733                let tree_end = tree.extent::<Count>(&());
 734                let new_items = rng
 735                    .sample_iter(distributions::Standard)
 736                    .take(count)
 737                    .collect::<Vec<u8>>();
 738
 739                let mut reference_items = tree.items(&());
 740                reference_items.splice(splice_start..splice_end, new_items.clone());
 741
 742                tree = {
 743                    let mut cursor = tree.cursor::<Count>();
 744                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
 745                    new_tree.extend(new_items, &());
 746                    cursor.seek(&Count(splice_end), Bias::Right, &());
 747                    new_tree.append(cursor.slice(&tree_end, Bias::Right, &()), &());
 748                    new_tree
 749                };
 750
 751                assert_eq!(tree.items(&()), reference_items);
 752                assert_eq!(
 753                    tree.iter().collect::<Vec<_>>(),
 754                    tree.cursor::<()>().collect::<Vec<_>>()
 755                );
 756
 757                log::info!("tree items: {:?}", tree.items(&()));
 758
 759                let mut filter_cursor = tree.filter::<_, Count>(|summary| summary.contains_even);
 760                let expected_filtered_items = tree
 761                    .items(&())
 762                    .into_iter()
 763                    .enumerate()
 764                    .filter(|(_, item)| (item & 1) == 0)
 765                    .collect::<Vec<_>>();
 766
 767                let mut item_ix = if rng.gen() {
 768                    filter_cursor.next(&());
 769                    0
 770                } else {
 771                    filter_cursor.prev(&());
 772                    expected_filtered_items.len().saturating_sub(1)
 773                };
 774                while item_ix < expected_filtered_items.len() {
 775                    log::info!("filter_cursor, item_ix: {}", item_ix);
 776                    let actual_item = filter_cursor.item().unwrap();
 777                    let (reference_index, reference_item) = expected_filtered_items[item_ix];
 778                    assert_eq!(actual_item, &reference_item);
 779                    assert_eq!(filter_cursor.start().0, reference_index);
 780                    log::info!("next");
 781                    filter_cursor.next(&());
 782                    item_ix += 1;
 783
 784                    while item_ix > 0 && rng.gen_bool(0.2) {
 785                        log::info!("prev");
 786                        filter_cursor.prev(&());
 787                        item_ix -= 1;
 788
 789                        if item_ix == 0 && rng.gen_bool(0.2) {
 790                            filter_cursor.prev(&());
 791                            assert_eq!(filter_cursor.item(), None);
 792                            assert_eq!(filter_cursor.start().0, 0);
 793                            filter_cursor.next(&());
 794                        }
 795                    }
 796                }
 797                assert_eq!(filter_cursor.item(), None);
 798
 799                let mut pos = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 800                let mut before_start = false;
 801                let mut cursor = tree.cursor::<Count>();
 802                cursor.seek(&Count(pos), Bias::Right, &());
 803
 804                for i in 0..10 {
 805                    assert_eq!(cursor.start().0, pos);
 806
 807                    if pos > 0 {
 808                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
 809                    } else {
 810                        assert_eq!(cursor.prev_item(), None);
 811                    }
 812
 813                    if pos < reference_items.len() && !before_start {
 814                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
 815                    } else {
 816                        assert_eq!(cursor.item(), None);
 817                    }
 818
 819                    if i < 5 {
 820                        cursor.next(&());
 821                        if pos < reference_items.len() {
 822                            pos += 1;
 823                            before_start = false;
 824                        }
 825                    } else {
 826                        cursor.prev(&());
 827                        if pos == 0 {
 828                            before_start = true;
 829                        }
 830                        pos = pos.saturating_sub(1);
 831                    }
 832                }
 833            }
 834
 835            for _ in 0..10 {
 836                let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 837                let start = rng.gen_range(0..end + 1);
 838                let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
 839                let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
 840
 841                let mut cursor = tree.cursor::<Count>();
 842                cursor.seek(&Count(start), start_bias, &());
 843                let slice = cursor.slice(&Count(end), end_bias, &());
 844
 845                cursor.seek(&Count(start), start_bias, &());
 846                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
 847
 848                assert_eq!(summary.0, slice.summary().sum);
 849            }
 850        }
 851    }
 852
 853    #[test]
 854    fn test_cursor() {
 855        // Empty tree
 856        let tree = SumTree::<u8>::new();
 857        let mut cursor = tree.cursor::<IntegersSummary>();
 858        assert_eq!(
 859            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
 860            Vec::<u8>::new()
 861        );
 862        assert_eq!(cursor.item(), None);
 863        assert_eq!(cursor.prev_item(), None);
 864        assert_eq!(cursor.start().sum, 0);
 865        cursor.prev(&());
 866        assert_eq!(cursor.item(), None);
 867        assert_eq!(cursor.prev_item(), None);
 868        assert_eq!(cursor.start().sum, 0);
 869        cursor.next(&());
 870        assert_eq!(cursor.item(), None);
 871        assert_eq!(cursor.prev_item(), None);
 872        assert_eq!(cursor.start().sum, 0);
 873
 874        // Single-element tree
 875        let mut tree = SumTree::<u8>::new();
 876        tree.extend(vec![1], &());
 877        let mut cursor = tree.cursor::<IntegersSummary>();
 878        assert_eq!(
 879            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
 880            Vec::<u8>::new()
 881        );
 882        assert_eq!(cursor.item(), Some(&1));
 883        assert_eq!(cursor.prev_item(), None);
 884        assert_eq!(cursor.start().sum, 0);
 885
 886        cursor.next(&());
 887        assert_eq!(cursor.item(), None);
 888        assert_eq!(cursor.prev_item(), Some(&1));
 889        assert_eq!(cursor.start().sum, 1);
 890
 891        cursor.prev(&());
 892        assert_eq!(cursor.item(), Some(&1));
 893        assert_eq!(cursor.prev_item(), None);
 894        assert_eq!(cursor.start().sum, 0);
 895
 896        let mut cursor = tree.cursor::<IntegersSummary>();
 897        assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
 898        assert_eq!(cursor.item(), None);
 899        assert_eq!(cursor.prev_item(), Some(&1));
 900        assert_eq!(cursor.start().sum, 1);
 901
 902        cursor.seek(&Count(0), Bias::Right, &());
 903        assert_eq!(
 904            cursor
 905                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 906                .items(&()),
 907            [1]
 908        );
 909        assert_eq!(cursor.item(), None);
 910        assert_eq!(cursor.prev_item(), Some(&1));
 911        assert_eq!(cursor.start().sum, 1);
 912
 913        // Multiple-element tree
 914        let mut tree = SumTree::new();
 915        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
 916        let mut cursor = tree.cursor::<IntegersSummary>();
 917
 918        assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
 919        assert_eq!(cursor.item(), Some(&3));
 920        assert_eq!(cursor.prev_item(), Some(&2));
 921        assert_eq!(cursor.start().sum, 3);
 922
 923        cursor.next(&());
 924        assert_eq!(cursor.item(), Some(&4));
 925        assert_eq!(cursor.prev_item(), Some(&3));
 926        assert_eq!(cursor.start().sum, 6);
 927
 928        cursor.next(&());
 929        assert_eq!(cursor.item(), Some(&5));
 930        assert_eq!(cursor.prev_item(), Some(&4));
 931        assert_eq!(cursor.start().sum, 10);
 932
 933        cursor.next(&());
 934        assert_eq!(cursor.item(), Some(&6));
 935        assert_eq!(cursor.prev_item(), Some(&5));
 936        assert_eq!(cursor.start().sum, 15);
 937
 938        cursor.next(&());
 939        cursor.next(&());
 940        assert_eq!(cursor.item(), None);
 941        assert_eq!(cursor.prev_item(), Some(&6));
 942        assert_eq!(cursor.start().sum, 21);
 943
 944        cursor.prev(&());
 945        assert_eq!(cursor.item(), Some(&6));
 946        assert_eq!(cursor.prev_item(), Some(&5));
 947        assert_eq!(cursor.start().sum, 15);
 948
 949        cursor.prev(&());
 950        assert_eq!(cursor.item(), Some(&5));
 951        assert_eq!(cursor.prev_item(), Some(&4));
 952        assert_eq!(cursor.start().sum, 10);
 953
 954        cursor.prev(&());
 955        assert_eq!(cursor.item(), Some(&4));
 956        assert_eq!(cursor.prev_item(), Some(&3));
 957        assert_eq!(cursor.start().sum, 6);
 958
 959        cursor.prev(&());
 960        assert_eq!(cursor.item(), Some(&3));
 961        assert_eq!(cursor.prev_item(), Some(&2));
 962        assert_eq!(cursor.start().sum, 3);
 963
 964        cursor.prev(&());
 965        assert_eq!(cursor.item(), Some(&2));
 966        assert_eq!(cursor.prev_item(), Some(&1));
 967        assert_eq!(cursor.start().sum, 1);
 968
 969        cursor.prev(&());
 970        assert_eq!(cursor.item(), Some(&1));
 971        assert_eq!(cursor.prev_item(), None);
 972        assert_eq!(cursor.start().sum, 0);
 973
 974        cursor.prev(&());
 975        assert_eq!(cursor.item(), None);
 976        assert_eq!(cursor.prev_item(), None);
 977        assert_eq!(cursor.start().sum, 0);
 978
 979        cursor.next(&());
 980        assert_eq!(cursor.item(), Some(&1));
 981        assert_eq!(cursor.prev_item(), None);
 982        assert_eq!(cursor.start().sum, 0);
 983
 984        let mut cursor = tree.cursor::<IntegersSummary>();
 985        assert_eq!(
 986            cursor
 987                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 988                .items(&()),
 989            tree.items(&())
 990        );
 991        assert_eq!(cursor.item(), None);
 992        assert_eq!(cursor.prev_item(), Some(&6));
 993        assert_eq!(cursor.start().sum, 21);
 994
 995        cursor.seek(&Count(3), Bias::Right, &());
 996        assert_eq!(
 997            cursor
 998                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 999                .items(&()),
1000            [4, 5, 6]
1001        );
1002        assert_eq!(cursor.item(), None);
1003        assert_eq!(cursor.prev_item(), Some(&6));
1004        assert_eq!(cursor.start().sum, 21);
1005
1006        // Seeking can bias left or right
1007        cursor.seek(&Count(1), Bias::Left, &());
1008        assert_eq!(cursor.item(), Some(&1));
1009        cursor.seek(&Count(1), Bias::Right, &());
1010        assert_eq!(cursor.item(), Some(&2));
1011
1012        // Slicing without resetting starts from where the cursor is parked at.
1013        cursor.seek(&Count(1), Bias::Right, &());
1014        assert_eq!(
1015            cursor.slice(&Count(3), Bias::Right, &()).items(&()),
1016            vec![2, 3]
1017        );
1018        assert_eq!(
1019            cursor.slice(&Count(6), Bias::Left, &()).items(&()),
1020            vec![4, 5]
1021        );
1022        assert_eq!(
1023            cursor.slice(&Count(6), Bias::Right, &()).items(&()),
1024            vec![6]
1025        );
1026    }
1027
1028    #[test]
1029    fn test_edit() {
1030        let mut tree = SumTree::<u8>::new();
1031
1032        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
1033        assert_eq!(tree.items(&()), vec![0, 1, 2]);
1034        assert_eq!(removed, Vec::<u8>::new());
1035        assert_eq!(tree.get(&0, &()), Some(&0));
1036        assert_eq!(tree.get(&1, &()), Some(&1));
1037        assert_eq!(tree.get(&2, &()), Some(&2));
1038        assert_eq!(tree.get(&4, &()), None);
1039
1040        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
1041        assert_eq!(tree.items(&()), vec![1, 2, 4]);
1042        assert_eq!(removed, vec![0, 2]);
1043        assert_eq!(tree.get(&0, &()), None);
1044        assert_eq!(tree.get(&1, &()), Some(&1));
1045        assert_eq!(tree.get(&2, &()), Some(&2));
1046        assert_eq!(tree.get(&4, &()), Some(&4));
1047    }
1048
1049    #[derive(Clone, Default, Debug)]
1050    pub struct IntegersSummary {
1051        count: usize,
1052        sum: usize,
1053        contains_even: bool,
1054        max: u8,
1055    }
1056
1057    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1058    struct Count(usize);
1059
1060    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1061    struct Sum(usize);
1062
1063    impl Item for u8 {
1064        type Summary = IntegersSummary;
1065
1066        fn summary(&self) -> Self::Summary {
1067            IntegersSummary {
1068                count: 1,
1069                sum: *self as usize,
1070                contains_even: (*self & 1) == 0,
1071                max: *self,
1072            }
1073        }
1074    }
1075
1076    impl KeyedItem for u8 {
1077        type Key = u8;
1078
1079        fn key(&self) -> Self::Key {
1080            *self
1081        }
1082    }
1083
1084    impl Summary for IntegersSummary {
1085        type Context = ();
1086
1087        fn add_summary(&mut self, other: &Self, _: &()) {
1088            self.count += other.count;
1089            self.sum += other.sum;
1090            self.contains_even |= other.contains_even;
1091            self.max = cmp::max(self.max, other.max);
1092        }
1093    }
1094
1095    impl<'a> Dimension<'a, IntegersSummary> for u8 {
1096        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1097            *self = summary.max;
1098        }
1099    }
1100
1101    impl<'a> Dimension<'a, IntegersSummary> for Count {
1102        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1103            self.0 += summary.count;
1104        }
1105    }
1106
1107    impl<'a> SeekTarget<'a, IntegersSummary, IntegersSummary> for Count {
1108        fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1109            self.0.cmp(&cursor_location.count)
1110        }
1111    }
1112
1113    impl<'a> Dimension<'a, IntegersSummary> for Sum {
1114        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1115            self.0 += summary.sum;
1116        }
1117    }
1118}