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