cursor.rs

  1use super::*;
  2use arrayvec::ArrayVec;
  3use std::{cmp::Ordering, mem, sync::Arc};
  4
  5#[derive(Clone)]
  6struct StackEntry<'a, T: Item, D> {
  7    tree: &'a SumTree<T>,
  8    index: u32,
  9    position: D,
 10}
 11
 12impl<'a, T: Item, D> StackEntry<'a, T, D> {
 13    #[inline]
 14    fn index(&self) -> usize {
 15        self.index as usize
 16    }
 17}
 18
 19impl<T: Item + fmt::Debug, D: fmt::Debug> fmt::Debug for StackEntry<'_, T, D> {
 20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 21        f.debug_struct("StackEntry")
 22            .field("index", &self.index)
 23            .field("position", &self.position)
 24            .finish()
 25    }
 26}
 27
 28#[derive(Clone)]
 29pub struct Cursor<'a, 'b, T: Item, D> {
 30    tree: &'a SumTree<T>,
 31    stack: ArrayVec<StackEntry<'a, T, D>, 16>,
 32    position: D,
 33    did_seek: bool,
 34    at_end: bool,
 35    cx: <T::Summary as Summary>::Context<'b>,
 36}
 37
 38impl<T: Item + fmt::Debug, D: fmt::Debug> fmt::Debug for Cursor<'_, '_, T, D>
 39where
 40    T::Summary: fmt::Debug,
 41{
 42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 43        f.debug_struct("Cursor")
 44            .field("tree", &self.tree)
 45            .field("stack", &self.stack)
 46            .field("position", &self.position)
 47            .field("did_seek", &self.did_seek)
 48            .field("at_end", &self.at_end)
 49            .finish()
 50    }
 51}
 52
 53pub struct Iter<'a, T: Item> {
 54    tree: &'a SumTree<T>,
 55    stack: ArrayVec<StackEntry<'a, T, ()>, 16>,
 56}
 57
 58impl<'a, 'b, T, D> Cursor<'a, 'b, T, D>
 59where
 60    T: Item,
 61    D: Dimension<'a, T::Summary>,
 62{
 63    pub fn new(tree: &'a SumTree<T>, cx: <T::Summary as Summary>::Context<'b>) -> Self {
 64        Self {
 65            tree,
 66            stack: ArrayVec::new(),
 67            position: D::zero(cx),
 68            did_seek: false,
 69            at_end: tree.is_empty(),
 70            cx,
 71        }
 72    }
 73
 74    fn reset(&mut self) {
 75        self.did_seek = false;
 76        self.at_end = self.tree.is_empty();
 77        self.stack.truncate(0);
 78        self.position = D::zero(self.cx);
 79    }
 80
 81    pub fn start(&self) -> &D {
 82        &self.position
 83    }
 84
 85    #[track_caller]
 86    pub fn end(&self) -> D {
 87        if let Some(item_summary) = self.item_summary() {
 88            let mut end = self.start().clone();
 89            end.add_summary(item_summary, self.cx);
 90            end
 91        } else {
 92            self.start().clone()
 93        }
 94    }
 95
 96    /// Item is None, when the list is empty, or this cursor is at the end of the list.
 97    #[track_caller]
 98    pub fn item(&self) -> Option<&'a T> {
 99        self.assert_did_seek();
100        if let Some(entry) = self.stack.last() {
101            match *entry.tree.0 {
102                Node::Leaf { ref items, .. } => {
103                    if entry.index() == items.len() {
104                        None
105                    } else {
106                        Some(&items[entry.index()])
107                    }
108                }
109                _ => unreachable!(),
110            }
111        } else {
112            None
113        }
114    }
115
116    #[track_caller]
117    pub fn item_summary(&self) -> Option<&'a T::Summary> {
118        self.assert_did_seek();
119        if let Some(entry) = self.stack.last() {
120            match *entry.tree.0 {
121                Node::Leaf {
122                    ref item_summaries, ..
123                } => {
124                    if entry.index() == item_summaries.len() {
125                        None
126                    } else {
127                        Some(&item_summaries[entry.index()])
128                    }
129                }
130                _ => unreachable!(),
131            }
132        } else {
133            None
134        }
135    }
136
137    #[track_caller]
138    pub fn next_item(&self) -> Option<&'a T> {
139        self.assert_did_seek();
140        if let Some(entry) = self.stack.last() {
141            if entry.index() == entry.tree.0.items().len() - 1 {
142                if let Some(next_leaf) = self.next_leaf() {
143                    Some(next_leaf.0.items().first().unwrap())
144                } else {
145                    None
146                }
147            } else {
148                match *entry.tree.0 {
149                    Node::Leaf { ref items, .. } => Some(&items[entry.index() + 1]),
150                    _ => unreachable!(),
151                }
152            }
153        } else if self.at_end {
154            None
155        } else {
156            self.tree.first()
157        }
158    }
159
160    #[track_caller]
161    fn next_leaf(&self) -> Option<&'a SumTree<T>> {
162        for entry in self.stack.iter().rev().skip(1) {
163            if entry.index() < entry.tree.0.child_trees().len() - 1 {
164                match *entry.tree.0 {
165                    Node::Internal {
166                        ref child_trees, ..
167                    } => return Some(child_trees[entry.index() + 1].leftmost_leaf()),
168                    Node::Leaf { .. } => unreachable!(),
169                };
170            }
171        }
172        None
173    }
174
175    #[track_caller]
176    pub fn prev_item(&self) -> Option<&'a T> {
177        self.assert_did_seek();
178        if let Some(entry) = self.stack.last() {
179            if entry.index() == 0 {
180                if let Some(prev_leaf) = self.prev_leaf() {
181                    Some(prev_leaf.0.items().last().unwrap())
182                } else {
183                    None
184                }
185            } else {
186                match *entry.tree.0 {
187                    Node::Leaf { ref items, .. } => Some(&items[entry.index() - 1]),
188                    _ => unreachable!(),
189                }
190            }
191        } else if self.at_end {
192            self.tree.last()
193        } else {
194            None
195        }
196    }
197
198    #[track_caller]
199    fn prev_leaf(&self) -> Option<&'a SumTree<T>> {
200        for entry in self.stack.iter().rev().skip(1) {
201            if entry.index() != 0 {
202                match *entry.tree.0 {
203                    Node::Internal {
204                        ref child_trees, ..
205                    } => return Some(child_trees[entry.index() - 1].rightmost_leaf()),
206                    Node::Leaf { .. } => unreachable!(),
207                };
208            }
209        }
210        None
211    }
212
213    #[track_caller]
214    pub fn prev(&mut self) {
215        self.search_backward(|_| true)
216    }
217
218    #[track_caller]
219    pub fn search_backward<F>(&mut self, mut filter_node: F)
220    where
221        F: FnMut(&T::Summary) -> bool,
222    {
223        if !self.did_seek {
224            self.did_seek = true;
225            self.at_end = true;
226        }
227
228        if self.at_end {
229            self.position = D::zero(self.cx);
230            self.at_end = self.tree.is_empty();
231            if !self.tree.is_empty() {
232                self.stack.push(StackEntry {
233                    tree: self.tree,
234                    index: self.tree.0.child_summaries().len() as u32,
235                    position: D::from_summary(self.tree.summary(), self.cx),
236                });
237            }
238        }
239
240        let mut descending = false;
241        while !self.stack.is_empty() {
242            if let Some(StackEntry { position, .. }) = self.stack.iter().rev().nth(1) {
243                self.position = position.clone();
244            } else {
245                self.position = D::zero(self.cx);
246            }
247
248            let entry = self.stack.last_mut().unwrap();
249            if !descending {
250                if entry.index() == 0 {
251                    self.stack.pop();
252                    continue;
253                } else {
254                    entry.index -= 1;
255                }
256            }
257
258            for summary in &entry.tree.0.child_summaries()[..entry.index()] {
259                self.position.add_summary(summary, self.cx);
260            }
261            entry.position = self.position.clone();
262
263            descending = filter_node(&entry.tree.0.child_summaries()[entry.index()]);
264            match entry.tree.0.as_ref() {
265                Node::Internal { child_trees, .. } => {
266                    if descending {
267                        let tree = &child_trees[entry.index()];
268                        self.stack.push(StackEntry {
269                            position: D::zero(self.cx),
270                            tree,
271                            index: tree.0.child_summaries().len() as u32 - 1,
272                        })
273                    }
274                }
275                Node::Leaf { .. } => {
276                    if descending {
277                        break;
278                    }
279                }
280            }
281        }
282    }
283
284    #[track_caller]
285    pub fn next(&mut self) {
286        self.search_forward(|_| true)
287    }
288
289    #[track_caller]
290    pub fn search_forward<F>(&mut self, mut filter_node: F)
291    where
292        F: FnMut(&T::Summary) -> bool,
293    {
294        let mut descend = false;
295
296        if self.stack.is_empty() {
297            if !self.at_end {
298                self.stack.push(StackEntry {
299                    tree: self.tree,
300                    index: 0,
301                    position: D::zero(self.cx),
302                });
303                descend = true;
304            }
305            self.did_seek = true;
306        }
307
308        while !self.stack.is_empty() {
309            let new_subtree = {
310                let entry = self.stack.last_mut().unwrap();
311                match entry.tree.0.as_ref() {
312                    Node::Internal {
313                        child_trees,
314                        child_summaries,
315                        ..
316                    } => {
317                        if !descend {
318                            entry.index += 1;
319                            entry.position = self.position.clone();
320                        }
321
322                        while entry.index() < child_summaries.len() {
323                            let next_summary = &child_summaries[entry.index()];
324                            if filter_node(next_summary) {
325                                break;
326                            } else {
327                                entry.index += 1;
328                                entry.position.add_summary(next_summary, self.cx);
329                                self.position.add_summary(next_summary, self.cx);
330                            }
331                        }
332
333                        child_trees.get(entry.index())
334                    }
335                    Node::Leaf { item_summaries, .. } => {
336                        if !descend {
337                            let item_summary = &item_summaries[entry.index()];
338                            entry.index += 1;
339                            entry.position.add_summary(item_summary, self.cx);
340                            self.position.add_summary(item_summary, self.cx);
341                        }
342
343                        loop {
344                            if let Some(next_item_summary) = item_summaries.get(entry.index()) {
345                                if filter_node(next_item_summary) {
346                                    return;
347                                } else {
348                                    entry.index += 1;
349                                    entry.position.add_summary(next_item_summary, self.cx);
350                                    self.position.add_summary(next_item_summary, self.cx);
351                                }
352                            } else {
353                                break None;
354                            }
355                        }
356                    }
357                }
358            };
359
360            if let Some(subtree) = new_subtree {
361                descend = true;
362                self.stack.push(StackEntry {
363                    tree: subtree,
364                    index: 0,
365                    position: self.position.clone(),
366                });
367            } else {
368                descend = false;
369                self.stack.pop();
370            }
371        }
372
373        self.at_end = self.stack.is_empty();
374        debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf());
375    }
376
377    #[track_caller]
378    fn assert_did_seek(&self) {
379        assert!(
380            self.did_seek,
381            "Must call `seek`, `next` or `prev` before calling this method"
382        );
383    }
384
385    pub fn did_seek(&self) -> bool {
386        self.did_seek
387    }
388}
389
390impl<'a, 'b, T, D> Cursor<'a, 'b, T, D>
391where
392    T: Item,
393    D: Dimension<'a, T::Summary>,
394{
395    /// Returns whether we found the item you were seeking for.
396    #[track_caller]
397    pub fn seek<Target>(&mut self, pos: &Target, bias: Bias) -> bool
398    where
399        Target: SeekTarget<'a, T::Summary, D>,
400    {
401        self.reset();
402        self.seek_internal(pos, bias, &mut ())
403    }
404
405    /// Returns whether we found the item you were seeking for.
406    #[track_caller]
407    pub fn seek_forward<Target>(&mut self, pos: &Target, bias: Bias) -> bool
408    where
409        Target: SeekTarget<'a, T::Summary, D>,
410    {
411        self.seek_internal(pos, bias, &mut ())
412    }
413
414    /// Advances the cursor and returns traversed items as a tree.
415    #[track_caller]
416    pub fn slice<Target>(&mut self, end: &Target, bias: Bias) -> SumTree<T>
417    where
418        Target: SeekTarget<'a, T::Summary, D>,
419    {
420        let mut slice = SliceSeekAggregate {
421            tree: SumTree::new(self.cx),
422            leaf_items: ArrayVec::new(),
423            leaf_item_summaries: ArrayVec::new(),
424            leaf_summary: <T::Summary as Summary>::zero(self.cx),
425        };
426        self.seek_internal(end, bias, &mut slice);
427        slice.tree
428    }
429
430    #[track_caller]
431    pub fn suffix(&mut self) -> SumTree<T> {
432        self.slice(&End::new(), Bias::Right)
433    }
434
435    #[track_caller]
436    pub fn summary<Target, Output>(&mut self, end: &Target, bias: Bias) -> Output
437    where
438        Target: SeekTarget<'a, T::Summary, D>,
439        Output: Dimension<'a, T::Summary>,
440    {
441        let mut summary = SummarySeekAggregate(Output::zero(self.cx));
442        self.seek_internal(end, bias, &mut summary);
443        summary.0
444    }
445
446    /// Returns whether we found the item you were seeking for.
447    #[track_caller]
448    fn seek_internal(
449        &mut self,
450        target: &dyn SeekTarget<'a, T::Summary, D>,
451        bias: Bias,
452        aggregate: &mut dyn SeekAggregate<'a, T>,
453    ) -> bool {
454        assert!(
455            target.cmp(&self.position, self.cx).is_ge(),
456            "cannot seek backward",
457        );
458
459        if !self.did_seek {
460            self.did_seek = true;
461            self.stack.push(StackEntry {
462                tree: self.tree,
463                index: 0,
464                position: D::zero(self.cx),
465            });
466        }
467
468        let mut ascending = false;
469        'outer: while let Some(entry) = self.stack.last_mut() {
470            match *entry.tree.0 {
471                Node::Internal {
472                    ref child_summaries,
473                    ref child_trees,
474                    ..
475                } => {
476                    if ascending {
477                        entry.index += 1;
478                        entry.position = self.position.clone();
479                    }
480
481                    for (child_tree, child_summary) in child_trees[entry.index()..]
482                        .iter()
483                        .zip(&child_summaries[entry.index()..])
484                    {
485                        let mut child_end = self.position.clone();
486                        child_end.add_summary(child_summary, self.cx);
487
488                        let comparison = target.cmp(&child_end, self.cx);
489                        if comparison == Ordering::Greater
490                            || (comparison == Ordering::Equal && bias == Bias::Right)
491                        {
492                            self.position = child_end;
493                            aggregate.push_tree(child_tree, child_summary, self.cx);
494                            entry.index += 1;
495                            entry.position = self.position.clone();
496                        } else {
497                            self.stack.push(StackEntry {
498                                tree: child_tree,
499                                index: 0,
500                                position: self.position.clone(),
501                            });
502                            ascending = false;
503                            continue 'outer;
504                        }
505                    }
506                }
507                Node::Leaf {
508                    ref items,
509                    ref item_summaries,
510                    ..
511                } => {
512                    aggregate.begin_leaf();
513
514                    for (item, item_summary) in items[entry.index()..]
515                        .iter()
516                        .zip(&item_summaries[entry.index()..])
517                    {
518                        let mut child_end = self.position.clone();
519                        child_end.add_summary(item_summary, self.cx);
520
521                        let comparison = target.cmp(&child_end, self.cx);
522                        if comparison == Ordering::Greater
523                            || (comparison == Ordering::Equal && bias == Bias::Right)
524                        {
525                            self.position = child_end;
526                            aggregate.push_item(item, item_summary, self.cx);
527                            entry.index += 1;
528                        } else {
529                            aggregate.end_leaf(self.cx);
530                            break 'outer;
531                        }
532                    }
533
534                    aggregate.end_leaf(self.cx);
535                }
536            }
537
538            self.stack.pop();
539            ascending = true;
540        }
541
542        self.at_end = self.stack.is_empty();
543        debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf());
544
545        let mut end = self.position.clone();
546        if bias == Bias::Left
547            && let Some(summary) = self.item_summary()
548        {
549            end.add_summary(summary, self.cx);
550        }
551
552        target.cmp(&end, self.cx) == Ordering::Equal
553    }
554}
555
556impl<'a, T: Item> Iter<'a, T> {
557    pub(crate) fn new(tree: &'a SumTree<T>) -> Self {
558        Self {
559            tree,
560            stack: Default::default(),
561        }
562    }
563}
564
565impl<'a, T: Item> Iterator for Iter<'a, T> {
566    type Item = &'a T;
567
568    fn next(&mut self) -> Option<Self::Item> {
569        let mut descend = false;
570
571        if self.stack.is_empty() {
572            self.stack.push(StackEntry {
573                tree: self.tree,
574                index: 0,
575                position: (),
576            });
577            descend = true;
578        }
579
580        while !self.stack.is_empty() {
581            let new_subtree = {
582                let entry = self.stack.last_mut().unwrap();
583                match entry.tree.0.as_ref() {
584                    Node::Internal { child_trees, .. } => {
585                        if !descend {
586                            entry.index += 1;
587                        }
588                        child_trees.get(entry.index())
589                    }
590                    Node::Leaf { items, .. } => {
591                        if !descend {
592                            entry.index += 1;
593                        }
594
595                        if let Some(next_item) = items.get(entry.index()) {
596                            return Some(next_item);
597                        } else {
598                            None
599                        }
600                    }
601                }
602            };
603
604            if let Some(subtree) = new_subtree {
605                descend = true;
606                self.stack.push(StackEntry {
607                    tree: subtree,
608                    index: 0,
609                    position: (),
610                });
611            } else {
612                descend = false;
613                self.stack.pop();
614            }
615        }
616
617        None
618    }
619}
620
621impl<'a, 'b, T: Item, D> Iterator for Cursor<'a, 'b, T, D>
622where
623    D: Dimension<'a, T::Summary>,
624{
625    type Item = &'a T;
626
627    fn next(&mut self) -> Option<Self::Item> {
628        if !self.did_seek {
629            self.next();
630        }
631
632        if let Some(item) = self.item() {
633            self.next();
634            Some(item)
635        } else {
636            None
637        }
638    }
639}
640
641pub struct FilterCursor<'a, 'b, F, T: Item, D> {
642    cursor: Cursor<'a, 'b, T, D>,
643    filter_node: F,
644}
645
646impl<'a, 'b, F, T: Item, D> FilterCursor<'a, 'b, F, T, D>
647where
648    F: FnMut(&T::Summary) -> bool,
649    T: Item,
650    D: Dimension<'a, T::Summary>,
651{
652    pub fn new(
653        tree: &'a SumTree<T>,
654        cx: <T::Summary as Summary>::Context<'b>,
655        filter_node: F,
656    ) -> Self {
657        let cursor = tree.cursor::<D>(cx);
658        Self {
659            cursor,
660            filter_node,
661        }
662    }
663
664    pub fn start(&self) -> &D {
665        self.cursor.start()
666    }
667
668    pub fn end(&self) -> D {
669        self.cursor.end()
670    }
671
672    pub fn item(&self) -> Option<&'a T> {
673        self.cursor.item()
674    }
675
676    pub fn item_summary(&self) -> Option<&'a T::Summary> {
677        self.cursor.item_summary()
678    }
679
680    pub fn next(&mut self) {
681        self.cursor.search_forward(&mut self.filter_node);
682    }
683
684    pub fn prev(&mut self) {
685        self.cursor.search_backward(&mut self.filter_node);
686    }
687}
688
689impl<'a, 'b, F, T: Item, U> Iterator for FilterCursor<'a, 'b, F, T, U>
690where
691    F: FnMut(&T::Summary) -> bool,
692    U: Dimension<'a, T::Summary>,
693{
694    type Item = &'a T;
695
696    fn next(&mut self) -> Option<Self::Item> {
697        if !self.cursor.did_seek {
698            self.next();
699        }
700
701        if let Some(item) = self.item() {
702            self.cursor.search_forward(&mut self.filter_node);
703            Some(item)
704        } else {
705            None
706        }
707    }
708}
709
710trait SeekAggregate<'a, T: Item> {
711    fn begin_leaf(&mut self);
712    fn end_leaf(&mut self, cx: <T::Summary as Summary>::Context<'_>);
713    fn push_item(
714        &mut self,
715        item: &'a T,
716        summary: &'a T::Summary,
717        cx: <T::Summary as Summary>::Context<'_>,
718    );
719    fn push_tree(
720        &mut self,
721        tree: &'a SumTree<T>,
722        summary: &'a T::Summary,
723        cx: <T::Summary as Summary>::Context<'_>,
724    );
725}
726
727struct SliceSeekAggregate<T: Item> {
728    tree: SumTree<T>,
729    leaf_items: ArrayVec<T, { 2 * TREE_BASE }>,
730    leaf_item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
731    leaf_summary: T::Summary,
732}
733
734struct SummarySeekAggregate<D>(D);
735
736impl<T: Item> SeekAggregate<'_, T> for () {
737    fn begin_leaf(&mut self) {}
738    fn end_leaf(&mut self, _: <T::Summary as Summary>::Context<'_>) {}
739    fn push_item(&mut self, _: &T, _: &T::Summary, _: <T::Summary as Summary>::Context<'_>) {}
740    fn push_tree(
741        &mut self,
742        _: &SumTree<T>,
743        _: &T::Summary,
744        _: <T::Summary as Summary>::Context<'_>,
745    ) {
746    }
747}
748
749impl<T: Item> SeekAggregate<'_, T> for SliceSeekAggregate<T> {
750    fn begin_leaf(&mut self) {}
751    fn end_leaf(&mut self, cx: <T::Summary as Summary>::Context<'_>) {
752        self.tree.append(
753            SumTree(Arc::new(Node::Leaf {
754                summary: mem::replace(&mut self.leaf_summary, <T::Summary as Summary>::zero(cx)),
755                items: mem::take(&mut self.leaf_items),
756                item_summaries: mem::take(&mut self.leaf_item_summaries),
757            })),
758            cx,
759        );
760    }
761    fn push_item(
762        &mut self,
763        item: &T,
764        summary: &T::Summary,
765        cx: <T::Summary as Summary>::Context<'_>,
766    ) {
767        self.leaf_items.push(item.clone());
768        self.leaf_item_summaries.push(summary.clone());
769        Summary::add_summary(&mut self.leaf_summary, summary, cx);
770    }
771    fn push_tree(
772        &mut self,
773        tree: &SumTree<T>,
774        _: &T::Summary,
775        cx: <T::Summary as Summary>::Context<'_>,
776    ) {
777        self.tree.append(tree.clone(), cx);
778    }
779}
780
781impl<'a, T: Item, D> SeekAggregate<'a, T> for SummarySeekAggregate<D>
782where
783    D: Dimension<'a, T::Summary>,
784{
785    fn begin_leaf(&mut self) {}
786    fn end_leaf(&mut self, _: <T::Summary as Summary>::Context<'_>) {}
787    fn push_item(
788        &mut self,
789        _: &T,
790        summary: &'a T::Summary,
791        cx: <T::Summary as Summary>::Context<'_>,
792    ) {
793        self.0.add_summary(summary, cx);
794    }
795    fn push_tree(
796        &mut self,
797        _: &SumTree<T>,
798        summary: &'a T::Summary,
799        cx: <T::Summary as Summary>::Context<'_>,
800    ) {
801        self.0.add_summary(summary, cx);
802    }
803}
804
805struct End<D>(PhantomData<D>);
806
807impl<D> End<D> {
808    fn new() -> Self {
809        Self(PhantomData)
810    }
811}
812
813impl<'a, S: Summary, D: Dimension<'a, S>> SeekTarget<'a, S, D> for End<D> {
814    fn cmp(&self, _: &D, _: S::Context<'_>) -> Ordering {
815        Ordering::Greater
816    }
817}
818
819impl<D> fmt::Debug for End<D> {
820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821        f.debug_tuple("End").finish()
822    }
823}