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: KeyedItem> SumTree<T> {
 482    pub fn insert_or_replace(&mut self, item: T, cx: &<T::Summary as Summary>::Context) -> bool {
 483        let mut replaced = false;
 484        *self = {
 485            let mut cursor = self.cursor::<T::Key>();
 486            let mut new_tree = cursor.slice(&item.key(), Bias::Left, cx);
 487            if cursor
 488                .item()
 489                .map_or(false, |cursor_item| cursor_item.key() == item.key())
 490            {
 491                cursor.next(cx);
 492                replaced = true;
 493            }
 494            new_tree.push(item, cx);
 495            new_tree.push_tree(cursor.suffix(cx), cx);
 496            new_tree
 497        };
 498        replaced
 499    }
 500
 501    pub fn edit(
 502        &mut self,
 503        mut edits: Vec<Edit<T>>,
 504        cx: &<T::Summary as Summary>::Context,
 505    ) -> Vec<T> {
 506        if edits.is_empty() {
 507            return Vec::new();
 508        }
 509
 510        let mut removed = Vec::new();
 511        edits.sort_unstable_by_key(|item| item.key());
 512
 513        *self = {
 514            let mut cursor = self.cursor::<T::Key>();
 515            let mut new_tree = SumTree::new();
 516            let mut buffered_items = Vec::new();
 517
 518            cursor.seek(&T::Key::default(), Bias::Left, cx);
 519            for edit in edits {
 520                let new_key = edit.key();
 521                let mut old_item = cursor.item();
 522
 523                if old_item
 524                    .as_ref()
 525                    .map_or(false, |old_item| old_item.key() < new_key)
 526                {
 527                    new_tree.extend(buffered_items.drain(..), cx);
 528                    let slice = cursor.slice(&new_key, Bias::Left, cx);
 529                    new_tree.push_tree(slice, cx);
 530                    old_item = cursor.item();
 531                }
 532
 533                if let Some(old_item) = old_item {
 534                    if old_item.key() == new_key {
 535                        removed.push(old_item.clone());
 536                        cursor.next(cx);
 537                    }
 538                }
 539
 540                match edit {
 541                    Edit::Insert(item) => {
 542                        buffered_items.push(item);
 543                    }
 544                    Edit::Remove(_) => {}
 545                }
 546            }
 547
 548            new_tree.extend(buffered_items, cx);
 549            new_tree.push_tree(cursor.suffix(cx), cx);
 550            new_tree
 551        };
 552
 553        removed
 554    }
 555
 556    pub fn get(&self, key: &T::Key, cx: &<T::Summary as Summary>::Context) -> Option<&T> {
 557        let mut cursor = self.cursor::<T::Key>();
 558        if cursor.seek(key, Bias::Left, cx) {
 559            cursor.item()
 560        } else {
 561            None
 562        }
 563    }
 564}
 565
 566impl<T: Item> Default for SumTree<T> {
 567    fn default() -> Self {
 568        Self::new()
 569    }
 570}
 571
 572#[derive(Clone, Debug)]
 573pub enum Node<T: Item> {
 574    Internal {
 575        height: u8,
 576        summary: T::Summary,
 577        child_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 578        child_trees: ArrayVec<SumTree<T>, { 2 * TREE_BASE }>,
 579    },
 580    Leaf {
 581        summary: T::Summary,
 582        items: ArrayVec<T, { 2 * TREE_BASE }>,
 583        item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
 584    },
 585}
 586
 587impl<T: Item> Node<T> {
 588    fn is_leaf(&self) -> bool {
 589        match self {
 590            Node::Leaf { .. } => true,
 591            _ => false,
 592        }
 593    }
 594
 595    fn height(&self) -> u8 {
 596        match self {
 597            Node::Internal { height, .. } => *height,
 598            Node::Leaf { .. } => 0,
 599        }
 600    }
 601
 602    fn summary(&self) -> &T::Summary {
 603        match self {
 604            Node::Internal { summary, .. } => summary,
 605            Node::Leaf { summary, .. } => summary,
 606        }
 607    }
 608
 609    fn child_summaries(&self) -> &[T::Summary] {
 610        match self {
 611            Node::Internal {
 612                child_summaries, ..
 613            } => child_summaries.as_slice(),
 614            Node::Leaf { item_summaries, .. } => item_summaries.as_slice(),
 615        }
 616    }
 617
 618    fn child_trees(&self) -> &ArrayVec<SumTree<T>, { 2 * TREE_BASE }> {
 619        match self {
 620            Node::Internal { child_trees, .. } => child_trees,
 621            Node::Leaf { .. } => panic!("Leaf nodes have no child trees"),
 622        }
 623    }
 624
 625    fn items(&self) -> &ArrayVec<T, { 2 * TREE_BASE }> {
 626        match self {
 627            Node::Leaf { items, .. } => items,
 628            Node::Internal { .. } => panic!("Internal nodes have no items"),
 629        }
 630    }
 631
 632    fn is_underflowing(&self) -> bool {
 633        match self {
 634            Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE,
 635            Node::Leaf { items, .. } => items.len() < TREE_BASE,
 636        }
 637    }
 638}
 639
 640#[derive(Debug)]
 641pub enum Edit<T: KeyedItem> {
 642    Insert(T),
 643    Remove(T::Key),
 644}
 645
 646impl<T: KeyedItem> Edit<T> {
 647    fn key(&self) -> T::Key {
 648        match self {
 649            Edit::Insert(item) => item.key(),
 650            Edit::Remove(key) => key.clone(),
 651        }
 652    }
 653}
 654
 655fn sum<'a, T, I>(iter: I, cx: &T::Context) -> T
 656where
 657    T: 'a + Summary,
 658    I: Iterator<Item = &'a T>,
 659{
 660    let mut sum = T::default();
 661    for value in iter {
 662        sum.add_summary(value, cx);
 663    }
 664    sum
 665}
 666
 667#[cfg(test)]
 668mod tests {
 669    use super::*;
 670    use rand::{distributions, prelude::*};
 671    use std::cmp;
 672
 673    #[test]
 674    fn test_extend_and_push_tree() {
 675        let mut tree1 = SumTree::new();
 676        tree1.extend(0..20, &());
 677
 678        let mut tree2 = SumTree::new();
 679        tree2.extend(50..100, &());
 680
 681        tree1.push_tree(tree2, &());
 682        assert_eq!(
 683            tree1.items(&()),
 684            (0..20).chain(50..100).collect::<Vec<u8>>()
 685        );
 686    }
 687
 688    #[test]
 689    fn test_random() {
 690        let mut starting_seed = 0;
 691        if let Ok(value) = std::env::var("SEED") {
 692            starting_seed = value.parse().expect("invalid SEED variable");
 693        }
 694        let mut num_iterations = 100;
 695        if let Ok(value) = std::env::var("ITERATIONS") {
 696            num_iterations = value.parse().expect("invalid ITERATIONS variable");
 697        }
 698
 699        for seed in starting_seed..(starting_seed + num_iterations) {
 700            let mut rng = StdRng::seed_from_u64(seed);
 701
 702            let rng = &mut rng;
 703            let mut tree = SumTree::<u8>::new();
 704            let count = rng.gen_range(0..10);
 705            tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
 706
 707            for _ in 0..5 {
 708                let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 709                let splice_start = rng.gen_range(0..splice_end + 1);
 710                let count = rng.gen_range(0..3);
 711                let tree_end = tree.extent::<Count>(&());
 712                let new_items = rng
 713                    .sample_iter(distributions::Standard)
 714                    .take(count)
 715                    .collect::<Vec<u8>>();
 716
 717                let mut reference_items = tree.items(&());
 718                reference_items.splice(splice_start..splice_end, new_items.clone());
 719
 720                tree = {
 721                    let mut cursor = tree.cursor::<Count>();
 722                    let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
 723                    new_tree.extend(new_items, &());
 724                    cursor.seek(&Count(splice_end), Bias::Right, &());
 725                    new_tree.push_tree(cursor.slice(&tree_end, Bias::Right, &()), &());
 726                    new_tree
 727                };
 728
 729                assert_eq!(tree.items(&()), reference_items);
 730                assert_eq!(
 731                    tree.iter().collect::<Vec<_>>(),
 732                    tree.cursor::<()>().collect::<Vec<_>>()
 733                );
 734
 735                let mut filter_cursor =
 736                    tree.filter::<_, Count>(|summary| summary.contains_even, &());
 737                let mut reference_filter = tree
 738                    .items(&())
 739                    .into_iter()
 740                    .enumerate()
 741                    .filter(|(_, item)| (item & 1) == 0);
 742                while let Some(actual_item) = filter_cursor.item() {
 743                    let (reference_index, reference_item) = reference_filter.next().unwrap();
 744                    assert_eq!(actual_item, &reference_item);
 745                    assert_eq!(filter_cursor.start().0, reference_index);
 746                    filter_cursor.next(&());
 747                }
 748                assert!(reference_filter.next().is_none());
 749
 750                let mut pos = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 751                let mut before_start = false;
 752                let mut cursor = tree.cursor::<Count>();
 753                cursor.seek(&Count(pos), Bias::Right, &());
 754
 755                for i in 0..10 {
 756                    assert_eq!(cursor.start().0, pos);
 757
 758                    if pos > 0 {
 759                        assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
 760                    } else {
 761                        assert_eq!(cursor.prev_item(), None);
 762                    }
 763
 764                    if pos < reference_items.len() && !before_start {
 765                        assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
 766                    } else {
 767                        assert_eq!(cursor.item(), None);
 768                    }
 769
 770                    if i < 5 {
 771                        cursor.next(&());
 772                        if pos < reference_items.len() {
 773                            pos += 1;
 774                            before_start = false;
 775                        }
 776                    } else {
 777                        cursor.prev(&());
 778                        if pos == 0 {
 779                            before_start = true;
 780                        }
 781                        pos = pos.saturating_sub(1);
 782                    }
 783                }
 784            }
 785
 786            for _ in 0..10 {
 787                let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 788                let start = rng.gen_range(0..end + 1);
 789                let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
 790                let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
 791
 792                let mut cursor = tree.cursor::<Count>();
 793                cursor.seek(&Count(start), start_bias, &());
 794                let slice = cursor.slice(&Count(end), end_bias, &());
 795
 796                cursor.seek(&Count(start), start_bias, &());
 797                let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
 798
 799                assert_eq!(summary.0, slice.summary().sum);
 800            }
 801        }
 802    }
 803
 804    #[test]
 805    fn test_cursor() {
 806        // Empty tree
 807        let tree = SumTree::<u8>::new();
 808        let mut cursor = tree.cursor::<IntegersSummary>();
 809        assert_eq!(
 810            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
 811            Vec::<u8>::new()
 812        );
 813        assert_eq!(cursor.item(), None);
 814        assert_eq!(cursor.prev_item(), None);
 815        assert_eq!(cursor.start().sum, 0);
 816
 817        // Single-element tree
 818        let mut tree = SumTree::<u8>::new();
 819        tree.extend(vec![1], &());
 820        let mut cursor = tree.cursor::<IntegersSummary>();
 821        assert_eq!(
 822            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
 823            Vec::<u8>::new()
 824        );
 825        assert_eq!(cursor.item(), Some(&1));
 826        assert_eq!(cursor.prev_item(), None);
 827        assert_eq!(cursor.start().sum, 0);
 828
 829        cursor.next(&());
 830        assert_eq!(cursor.item(), None);
 831        assert_eq!(cursor.prev_item(), Some(&1));
 832        assert_eq!(cursor.start().sum, 1);
 833
 834        cursor.prev(&());
 835        assert_eq!(cursor.item(), Some(&1));
 836        assert_eq!(cursor.prev_item(), None);
 837        assert_eq!(cursor.start().sum, 0);
 838
 839        let mut cursor = tree.cursor::<IntegersSummary>();
 840        assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
 841        assert_eq!(cursor.item(), None);
 842        assert_eq!(cursor.prev_item(), Some(&1));
 843        assert_eq!(cursor.start().sum, 1);
 844
 845        cursor.seek(&Count(0), Bias::Right, &());
 846        assert_eq!(
 847            cursor
 848                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 849                .items(&()),
 850            [1]
 851        );
 852        assert_eq!(cursor.item(), None);
 853        assert_eq!(cursor.prev_item(), Some(&1));
 854        assert_eq!(cursor.start().sum, 1);
 855
 856        // Multiple-element tree
 857        let mut tree = SumTree::new();
 858        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
 859        let mut cursor = tree.cursor::<IntegersSummary>();
 860
 861        assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
 862        assert_eq!(cursor.item(), Some(&3));
 863        assert_eq!(cursor.prev_item(), Some(&2));
 864        assert_eq!(cursor.start().sum, 3);
 865
 866        cursor.next(&());
 867        assert_eq!(cursor.item(), Some(&4));
 868        assert_eq!(cursor.prev_item(), Some(&3));
 869        assert_eq!(cursor.start().sum, 6);
 870
 871        cursor.next(&());
 872        assert_eq!(cursor.item(), Some(&5));
 873        assert_eq!(cursor.prev_item(), Some(&4));
 874        assert_eq!(cursor.start().sum, 10);
 875
 876        cursor.next(&());
 877        assert_eq!(cursor.item(), Some(&6));
 878        assert_eq!(cursor.prev_item(), Some(&5));
 879        assert_eq!(cursor.start().sum, 15);
 880
 881        cursor.next(&());
 882        cursor.next(&());
 883        assert_eq!(cursor.item(), None);
 884        assert_eq!(cursor.prev_item(), Some(&6));
 885        assert_eq!(cursor.start().sum, 21);
 886
 887        cursor.prev(&());
 888        assert_eq!(cursor.item(), Some(&6));
 889        assert_eq!(cursor.prev_item(), Some(&5));
 890        assert_eq!(cursor.start().sum, 15);
 891
 892        cursor.prev(&());
 893        assert_eq!(cursor.item(), Some(&5));
 894        assert_eq!(cursor.prev_item(), Some(&4));
 895        assert_eq!(cursor.start().sum, 10);
 896
 897        cursor.prev(&());
 898        assert_eq!(cursor.item(), Some(&4));
 899        assert_eq!(cursor.prev_item(), Some(&3));
 900        assert_eq!(cursor.start().sum, 6);
 901
 902        cursor.prev(&());
 903        assert_eq!(cursor.item(), Some(&3));
 904        assert_eq!(cursor.prev_item(), Some(&2));
 905        assert_eq!(cursor.start().sum, 3);
 906
 907        cursor.prev(&());
 908        assert_eq!(cursor.item(), Some(&2));
 909        assert_eq!(cursor.prev_item(), Some(&1));
 910        assert_eq!(cursor.start().sum, 1);
 911
 912        cursor.prev(&());
 913        assert_eq!(cursor.item(), Some(&1));
 914        assert_eq!(cursor.prev_item(), None);
 915        assert_eq!(cursor.start().sum, 0);
 916
 917        cursor.prev(&());
 918        assert_eq!(cursor.item(), None);
 919        assert_eq!(cursor.prev_item(), None);
 920        assert_eq!(cursor.start().sum, 0);
 921
 922        cursor.next(&());
 923        assert_eq!(cursor.item(), Some(&1));
 924        assert_eq!(cursor.prev_item(), None);
 925        assert_eq!(cursor.start().sum, 0);
 926
 927        let mut cursor = tree.cursor::<IntegersSummary>();
 928        assert_eq!(
 929            cursor
 930                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 931                .items(&()),
 932            tree.items(&())
 933        );
 934        assert_eq!(cursor.item(), None);
 935        assert_eq!(cursor.prev_item(), Some(&6));
 936        assert_eq!(cursor.start().sum, 21);
 937
 938        cursor.seek(&Count(3), Bias::Right, &());
 939        assert_eq!(
 940            cursor
 941                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 942                .items(&()),
 943            [4, 5, 6]
 944        );
 945        assert_eq!(cursor.item(), None);
 946        assert_eq!(cursor.prev_item(), Some(&6));
 947        assert_eq!(cursor.start().sum, 21);
 948
 949        // Seeking can bias left or right
 950        cursor.seek(&Count(1), Bias::Left, &());
 951        assert_eq!(cursor.item(), Some(&1));
 952        cursor.seek(&Count(1), Bias::Right, &());
 953        assert_eq!(cursor.item(), Some(&2));
 954
 955        // Slicing without resetting starts from where the cursor is parked at.
 956        cursor.seek(&Count(1), Bias::Right, &());
 957        assert_eq!(
 958            cursor.slice(&Count(3), Bias::Right, &()).items(&()),
 959            vec![2, 3]
 960        );
 961        assert_eq!(
 962            cursor.slice(&Count(6), Bias::Left, &()).items(&()),
 963            vec![4, 5]
 964        );
 965        assert_eq!(
 966            cursor.slice(&Count(6), Bias::Right, &()).items(&()),
 967            vec![6]
 968        );
 969    }
 970
 971    #[test]
 972    fn test_edit() {
 973        let mut tree = SumTree::<u8>::new();
 974
 975        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
 976        assert_eq!(tree.items(&()), vec![0, 1, 2]);
 977        assert_eq!(removed, Vec::<u8>::new());
 978        assert_eq!(tree.get(&0, &()), Some(&0));
 979        assert_eq!(tree.get(&1, &()), Some(&1));
 980        assert_eq!(tree.get(&2, &()), Some(&2));
 981        assert_eq!(tree.get(&4, &()), None);
 982
 983        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
 984        assert_eq!(tree.items(&()), vec![1, 2, 4]);
 985        assert_eq!(removed, vec![0, 2]);
 986        assert_eq!(tree.get(&0, &()), None);
 987        assert_eq!(tree.get(&1, &()), Some(&1));
 988        assert_eq!(tree.get(&2, &()), Some(&2));
 989        assert_eq!(tree.get(&4, &()), Some(&4));
 990    }
 991
 992    #[derive(Clone, Default, Debug)]
 993    pub struct IntegersSummary {
 994        count: usize,
 995        sum: usize,
 996        contains_even: bool,
 997        max: u8,
 998    }
 999
1000    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1001    struct Count(usize);
1002
1003    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
1004    struct Sum(usize);
1005
1006    impl Item for u8 {
1007        type Summary = IntegersSummary;
1008
1009        fn summary(&self) -> Self::Summary {
1010            IntegersSummary {
1011                count: 1,
1012                sum: *self as usize,
1013                contains_even: (*self & 1) == 0,
1014                max: *self,
1015            }
1016        }
1017    }
1018
1019    impl KeyedItem for u8 {
1020        type Key = u8;
1021
1022        fn key(&self) -> Self::Key {
1023            *self
1024        }
1025    }
1026
1027    impl Summary for IntegersSummary {
1028        type Context = ();
1029
1030        fn add_summary(&mut self, other: &Self, _: &()) {
1031            self.count += other.count;
1032            self.sum += other.sum;
1033            self.contains_even |= other.contains_even;
1034            self.max = cmp::max(self.max, other.max);
1035        }
1036    }
1037
1038    impl<'a> Dimension<'a, IntegersSummary> for u8 {
1039        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1040            *self = summary.max;
1041        }
1042    }
1043
1044    impl<'a> Dimension<'a, IntegersSummary> for Count {
1045        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1046            self.0 += summary.count;
1047        }
1048    }
1049
1050    impl<'a> SeekTarget<'a, IntegersSummary, IntegersSummary> for Count {
1051        fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1052            self.0.cmp(&cursor_location.count)
1053        }
1054    }
1055
1056    impl<'a> Dimension<'a, IntegersSummary> for Sum {
1057        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1058            self.0 += summary.sum;
1059        }
1060    }
1061}