sum_tree.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: Fn(&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    #[crate::test(self, iterations = 100)]
 678    fn test_random(mut rng: StdRng) {
 679        let rng = &mut rng;
 680        let mut tree = SumTree::<u8>::new();
 681        let count = rng.gen_range(0..10);
 682        tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
 683
 684        for _ in 0..5 {
 685            let splice_end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 686            let splice_start = rng.gen_range(0..splice_end + 1);
 687            let count = rng.gen_range(0..3);
 688            let tree_end = tree.extent::<Count>(&());
 689            let new_items = rng
 690                .sample_iter(distributions::Standard)
 691                .take(count)
 692                .collect::<Vec<u8>>();
 693
 694            let mut reference_items = tree.items(&());
 695            reference_items.splice(splice_start..splice_end, new_items.clone());
 696
 697            tree = {
 698                let mut cursor = tree.cursor::<Count>();
 699                let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
 700                new_tree.extend(new_items, &());
 701                cursor.seek(&Count(splice_end), Bias::Right, &());
 702                new_tree.push_tree(cursor.slice(&tree_end, Bias::Right, &()), &());
 703                new_tree
 704            };
 705
 706            assert_eq!(tree.items(&()), reference_items);
 707
 708            let mut filter_cursor = tree.filter::<_, Count>(|summary| summary.contains_even, &());
 709            let mut reference_filter = tree
 710                .items(&())
 711                .into_iter()
 712                .enumerate()
 713                .filter(|(_, item)| (item & 1) == 0);
 714            while let Some(actual_item) = filter_cursor.item() {
 715                let (reference_index, reference_item) = reference_filter.next().unwrap();
 716                assert_eq!(actual_item, &reference_item);
 717                assert_eq!(filter_cursor.start().0, reference_index);
 718                filter_cursor.next(&());
 719            }
 720            assert!(reference_filter.next().is_none());
 721
 722            let mut pos = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 723            let mut before_start = false;
 724            let mut cursor = tree.cursor::<Count>();
 725            cursor.seek(&Count(pos), Bias::Right, &());
 726
 727            for i in 0..10 {
 728                assert_eq!(cursor.start().0, pos);
 729
 730                if pos > 0 {
 731                    assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]);
 732                } else {
 733                    assert_eq!(cursor.prev_item(), None);
 734                }
 735
 736                if pos < reference_items.len() && !before_start {
 737                    assert_eq!(cursor.item().unwrap(), &reference_items[pos]);
 738                } else {
 739                    assert_eq!(cursor.item(), None);
 740                }
 741
 742                if i < 5 {
 743                    cursor.next(&());
 744                    if pos < reference_items.len() {
 745                        pos += 1;
 746                        before_start = false;
 747                    }
 748                } else {
 749                    cursor.prev(&());
 750                    if pos == 0 {
 751                        before_start = true;
 752                    }
 753                    pos = pos.saturating_sub(1);
 754                }
 755            }
 756        }
 757
 758        for _ in 0..10 {
 759            let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
 760            let start = rng.gen_range(0..end + 1);
 761            let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
 762            let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
 763
 764            let mut cursor = tree.cursor::<Count>();
 765            cursor.seek(&Count(start), start_bias, &());
 766            let slice = cursor.slice(&Count(end), end_bias, &());
 767
 768            cursor.seek(&Count(start), start_bias, &());
 769            let summary = cursor.summary::<_, Sum>(&Count(end), end_bias, &());
 770
 771            assert_eq!(summary.0, slice.summary().sum);
 772        }
 773    }
 774
 775    #[test]
 776    fn test_cursor() {
 777        // Empty tree
 778        let tree = SumTree::<u8>::new();
 779        let mut cursor = tree.cursor::<IntegersSummary>();
 780        assert_eq!(
 781            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
 782            Vec::<u8>::new()
 783        );
 784        assert_eq!(cursor.item(), None);
 785        assert_eq!(cursor.prev_item(), None);
 786        assert_eq!(cursor.start().sum, 0);
 787
 788        // Single-element tree
 789        let mut tree = SumTree::<u8>::new();
 790        tree.extend(vec![1], &());
 791        let mut cursor = tree.cursor::<IntegersSummary>();
 792        assert_eq!(
 793            cursor.slice(&Count(0), Bias::Right, &()).items(&()),
 794            Vec::<u8>::new()
 795        );
 796        assert_eq!(cursor.item(), Some(&1));
 797        assert_eq!(cursor.prev_item(), None);
 798        assert_eq!(cursor.start().sum, 0);
 799
 800        cursor.next(&());
 801        assert_eq!(cursor.item(), None);
 802        assert_eq!(cursor.prev_item(), Some(&1));
 803        assert_eq!(cursor.start().sum, 1);
 804
 805        cursor.prev(&());
 806        assert_eq!(cursor.item(), Some(&1));
 807        assert_eq!(cursor.prev_item(), None);
 808        assert_eq!(cursor.start().sum, 0);
 809
 810        let mut cursor = tree.cursor::<IntegersSummary>();
 811        assert_eq!(cursor.slice(&Count(1), Bias::Right, &()).items(&()), [1]);
 812        assert_eq!(cursor.item(), None);
 813        assert_eq!(cursor.prev_item(), Some(&1));
 814        assert_eq!(cursor.start().sum, 1);
 815
 816        cursor.seek(&Count(0), Bias::Right, &());
 817        assert_eq!(
 818            cursor
 819                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 820                .items(&()),
 821            [1]
 822        );
 823        assert_eq!(cursor.item(), None);
 824        assert_eq!(cursor.prev_item(), Some(&1));
 825        assert_eq!(cursor.start().sum, 1);
 826
 827        // Multiple-element tree
 828        let mut tree = SumTree::new();
 829        tree.extend(vec![1, 2, 3, 4, 5, 6], &());
 830        let mut cursor = tree.cursor::<IntegersSummary>();
 831
 832        assert_eq!(cursor.slice(&Count(2), Bias::Right, &()).items(&()), [1, 2]);
 833        assert_eq!(cursor.item(), Some(&3));
 834        assert_eq!(cursor.prev_item(), Some(&2));
 835        assert_eq!(cursor.start().sum, 3);
 836
 837        cursor.next(&());
 838        assert_eq!(cursor.item(), Some(&4));
 839        assert_eq!(cursor.prev_item(), Some(&3));
 840        assert_eq!(cursor.start().sum, 6);
 841
 842        cursor.next(&());
 843        assert_eq!(cursor.item(), Some(&5));
 844        assert_eq!(cursor.prev_item(), Some(&4));
 845        assert_eq!(cursor.start().sum, 10);
 846
 847        cursor.next(&());
 848        assert_eq!(cursor.item(), Some(&6));
 849        assert_eq!(cursor.prev_item(), Some(&5));
 850        assert_eq!(cursor.start().sum, 15);
 851
 852        cursor.next(&());
 853        cursor.next(&());
 854        assert_eq!(cursor.item(), None);
 855        assert_eq!(cursor.prev_item(), Some(&6));
 856        assert_eq!(cursor.start().sum, 21);
 857
 858        cursor.prev(&());
 859        assert_eq!(cursor.item(), Some(&6));
 860        assert_eq!(cursor.prev_item(), Some(&5));
 861        assert_eq!(cursor.start().sum, 15);
 862
 863        cursor.prev(&());
 864        assert_eq!(cursor.item(), Some(&5));
 865        assert_eq!(cursor.prev_item(), Some(&4));
 866        assert_eq!(cursor.start().sum, 10);
 867
 868        cursor.prev(&());
 869        assert_eq!(cursor.item(), Some(&4));
 870        assert_eq!(cursor.prev_item(), Some(&3));
 871        assert_eq!(cursor.start().sum, 6);
 872
 873        cursor.prev(&());
 874        assert_eq!(cursor.item(), Some(&3));
 875        assert_eq!(cursor.prev_item(), Some(&2));
 876        assert_eq!(cursor.start().sum, 3);
 877
 878        cursor.prev(&());
 879        assert_eq!(cursor.item(), Some(&2));
 880        assert_eq!(cursor.prev_item(), Some(&1));
 881        assert_eq!(cursor.start().sum, 1);
 882
 883        cursor.prev(&());
 884        assert_eq!(cursor.item(), Some(&1));
 885        assert_eq!(cursor.prev_item(), None);
 886        assert_eq!(cursor.start().sum, 0);
 887
 888        cursor.prev(&());
 889        assert_eq!(cursor.item(), None);
 890        assert_eq!(cursor.prev_item(), None);
 891        assert_eq!(cursor.start().sum, 0);
 892
 893        cursor.next(&());
 894        assert_eq!(cursor.item(), Some(&1));
 895        assert_eq!(cursor.prev_item(), None);
 896        assert_eq!(cursor.start().sum, 0);
 897
 898        let mut cursor = tree.cursor::<IntegersSummary>();
 899        assert_eq!(
 900            cursor
 901                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 902                .items(&()),
 903            tree.items(&())
 904        );
 905        assert_eq!(cursor.item(), None);
 906        assert_eq!(cursor.prev_item(), Some(&6));
 907        assert_eq!(cursor.start().sum, 21);
 908
 909        cursor.seek(&Count(3), Bias::Right, &());
 910        assert_eq!(
 911            cursor
 912                .slice(&tree.extent::<Count>(&()), Bias::Right, &())
 913                .items(&()),
 914            [4, 5, 6]
 915        );
 916        assert_eq!(cursor.item(), None);
 917        assert_eq!(cursor.prev_item(), Some(&6));
 918        assert_eq!(cursor.start().sum, 21);
 919
 920        // Seeking can bias left or right
 921        cursor.seek(&Count(1), Bias::Left, &());
 922        assert_eq!(cursor.item(), Some(&1));
 923        cursor.seek(&Count(1), Bias::Right, &());
 924        assert_eq!(cursor.item(), Some(&2));
 925
 926        // Slicing without resetting starts from where the cursor is parked at.
 927        cursor.seek(&Count(1), Bias::Right, &());
 928        assert_eq!(
 929            cursor.slice(&Count(3), Bias::Right, &()).items(&()),
 930            vec![2, 3]
 931        );
 932        assert_eq!(
 933            cursor.slice(&Count(6), Bias::Left, &()).items(&()),
 934            vec![4, 5]
 935        );
 936        assert_eq!(
 937            cursor.slice(&Count(6), Bias::Right, &()).items(&()),
 938            vec![6]
 939        );
 940    }
 941
 942    #[test]
 943    fn test_edit() {
 944        let mut tree = SumTree::<u8>::new();
 945
 946        let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], &());
 947        assert_eq!(tree.items(&()), vec![0, 1, 2]);
 948        assert_eq!(removed, Vec::<u8>::new());
 949        assert_eq!(tree.get(&0, &()), Some(&0));
 950        assert_eq!(tree.get(&1, &()), Some(&1));
 951        assert_eq!(tree.get(&2, &()), Some(&2));
 952        assert_eq!(tree.get(&4, &()), None);
 953
 954        let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], &());
 955        assert_eq!(tree.items(&()), vec![1, 2, 4]);
 956        assert_eq!(removed, vec![0, 2]);
 957        assert_eq!(tree.get(&0, &()), None);
 958        assert_eq!(tree.get(&1, &()), Some(&1));
 959        assert_eq!(tree.get(&2, &()), Some(&2));
 960        assert_eq!(tree.get(&4, &()), Some(&4));
 961    }
 962
 963    #[derive(Clone, Default, Debug)]
 964    pub struct IntegersSummary {
 965        count: usize,
 966        sum: usize,
 967        contains_even: bool,
 968        max: u8,
 969    }
 970
 971    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
 972    struct Count(usize);
 973
 974    #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)]
 975    struct Sum(usize);
 976
 977    impl Item for u8 {
 978        type Summary = IntegersSummary;
 979
 980        fn summary(&self) -> Self::Summary {
 981            IntegersSummary {
 982                count: 1,
 983                sum: *self as usize,
 984                contains_even: (*self & 1) == 0,
 985                max: *self,
 986            }
 987        }
 988    }
 989
 990    impl KeyedItem for u8 {
 991        type Key = u8;
 992
 993        fn key(&self) -> Self::Key {
 994            *self
 995        }
 996    }
 997
 998    impl Summary for IntegersSummary {
 999        type Context = ();
1000
1001        fn add_summary(&mut self, other: &Self, _: &()) {
1002            self.count += other.count;
1003            self.sum += other.sum;
1004            self.contains_even |= other.contains_even;
1005            self.max = cmp::max(self.max, other.max);
1006        }
1007    }
1008
1009    impl<'a> Dimension<'a, IntegersSummary> for u8 {
1010        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1011            *self = summary.max;
1012        }
1013    }
1014
1015    impl<'a> Dimension<'a, IntegersSummary> for Count {
1016        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1017            self.0 += summary.count;
1018        }
1019    }
1020
1021    impl<'a> SeekTarget<'a, IntegersSummary, IntegersSummary> for Count {
1022        fn cmp(&self, cursor_location: &IntegersSummary, _: &()) -> Ordering {
1023            self.0.cmp(&cursor_location.count)
1024        }
1025    }
1026
1027    impl<'a> Dimension<'a, IntegersSummary> for Sum {
1028        fn add_summary(&mut self, summary: &IntegersSummary, _: &()) {
1029            self.0 += summary.sum;
1030        }
1031    }
1032}