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