lib.rs

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