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
386impl<'a, 'b, T, D> Cursor<'a, 'b, T, D>
387where
388    T: Item,
389    D: Dimension<'a, T::Summary>,
390{
391    /// Returns whether we found the item you were seeking for.
392    #[track_caller]
393    pub fn seek<Target>(&mut self, pos: &Target, bias: Bias) -> bool
394    where
395        Target: SeekTarget<'a, T::Summary, D>,
396    {
397        self.reset();
398        self.seek_internal(pos, bias, &mut ())
399    }
400
401    /// Returns whether we found the item you were seeking for.
402    #[track_caller]
403    pub fn seek_forward<Target>(&mut self, pos: &Target, bias: Bias) -> bool
404    where
405        Target: SeekTarget<'a, T::Summary, D>,
406    {
407        self.seek_internal(pos, bias, &mut ())
408    }
409
410    /// Advances the cursor and returns traversed items as a tree.
411    #[track_caller]
412    pub fn slice<Target>(&mut self, end: &Target, bias: Bias) -> SumTree<T>
413    where
414        Target: SeekTarget<'a, T::Summary, D>,
415    {
416        let mut slice = SliceSeekAggregate {
417            tree: SumTree::new(self.cx),
418            leaf_items: ArrayVec::new(),
419            leaf_item_summaries: ArrayVec::new(),
420            leaf_summary: <T::Summary as Summary>::zero(self.cx),
421        };
422        self.seek_internal(end, bias, &mut slice);
423        slice.tree
424    }
425
426    #[track_caller]
427    pub fn suffix(&mut self) -> SumTree<T> {
428        self.slice(&End::new(), Bias::Right)
429    }
430
431    #[track_caller]
432    pub fn summary<Target, Output>(&mut self, end: &Target, bias: Bias) -> Output
433    where
434        Target: SeekTarget<'a, T::Summary, D>,
435        Output: Dimension<'a, T::Summary>,
436    {
437        let mut summary = SummarySeekAggregate(Output::zero(self.cx));
438        self.seek_internal(end, bias, &mut summary);
439        summary.0
440    }
441
442    /// Returns whether we found the item you were seeking for.
443    #[track_caller]
444    fn seek_internal(
445        &mut self,
446        target: &dyn SeekTarget<'a, T::Summary, D>,
447        bias: Bias,
448        aggregate: &mut dyn SeekAggregate<'a, T>,
449    ) -> bool {
450        assert!(
451            target.cmp(&self.position, self.cx) >= Ordering::Equal,
452            "cannot seek backward",
453        );
454
455        if !self.did_seek {
456            self.did_seek = true;
457            self.stack.push(StackEntry {
458                tree: self.tree,
459                index: 0,
460                position: D::zero(self.cx),
461            });
462        }
463
464        let mut ascending = false;
465        'outer: while let Some(entry) = self.stack.last_mut() {
466            match *entry.tree.0 {
467                Node::Internal {
468                    ref child_summaries,
469                    ref child_trees,
470                    ..
471                } => {
472                    if ascending {
473                        entry.index += 1;
474                        entry.position = self.position.clone();
475                    }
476
477                    for (child_tree, child_summary) in child_trees[entry.index()..]
478                        .iter()
479                        .zip(&child_summaries[entry.index()..])
480                    {
481                        let mut child_end = self.position.clone();
482                        child_end.add_summary(child_summary, self.cx);
483
484                        let comparison = target.cmp(&child_end, self.cx);
485                        if comparison == Ordering::Greater
486                            || (comparison == Ordering::Equal && bias == Bias::Right)
487                        {
488                            self.position = child_end;
489                            aggregate.push_tree(child_tree, child_summary, self.cx);
490                            entry.index += 1;
491                            entry.position = self.position.clone();
492                        } else {
493                            self.stack.push(StackEntry {
494                                tree: child_tree,
495                                index: 0,
496                                position: self.position.clone(),
497                            });
498                            ascending = false;
499                            continue 'outer;
500                        }
501                    }
502                }
503                Node::Leaf {
504                    ref items,
505                    ref item_summaries,
506                    ..
507                } => {
508                    aggregate.begin_leaf();
509
510                    for (item, item_summary) in items[entry.index()..]
511                        .iter()
512                        .zip(&item_summaries[entry.index()..])
513                    {
514                        let mut child_end = self.position.clone();
515                        child_end.add_summary(item_summary, self.cx);
516
517                        let comparison = target.cmp(&child_end, self.cx);
518                        if comparison == Ordering::Greater
519                            || (comparison == Ordering::Equal && bias == Bias::Right)
520                        {
521                            self.position = child_end;
522                            aggregate.push_item(item, item_summary, self.cx);
523                            entry.index += 1;
524                        } else {
525                            aggregate.end_leaf(self.cx);
526                            break 'outer;
527                        }
528                    }
529
530                    aggregate.end_leaf(self.cx);
531                }
532            }
533
534            self.stack.pop();
535            ascending = true;
536        }
537
538        self.at_end = self.stack.is_empty();
539        debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf());
540
541        let mut end = self.position.clone();
542        if bias == Bias::Left
543            && let Some(summary) = self.item_summary()
544        {
545            end.add_summary(summary, self.cx);
546        }
547
548        target.cmp(&end, self.cx) == Ordering::Equal
549    }
550}
551
552impl<'a, T: Item> Iter<'a, T> {
553    pub(crate) fn new(tree: &'a SumTree<T>) -> Self {
554        Self {
555            tree,
556            stack: Default::default(),
557        }
558    }
559}
560
561impl<'a, T: Item> Iterator for Iter<'a, T> {
562    type Item = &'a T;
563
564    fn next(&mut self) -> Option<Self::Item> {
565        let mut descend = false;
566
567        if self.stack.is_empty() {
568            self.stack.push(StackEntry {
569                tree: self.tree,
570                index: 0,
571                position: (),
572            });
573            descend = true;
574        }
575
576        while !self.stack.is_empty() {
577            let new_subtree = {
578                let entry = self.stack.last_mut().unwrap();
579                match entry.tree.0.as_ref() {
580                    Node::Internal { child_trees, .. } => {
581                        if !descend {
582                            entry.index += 1;
583                        }
584                        child_trees.get(entry.index())
585                    }
586                    Node::Leaf { items, .. } => {
587                        if !descend {
588                            entry.index += 1;
589                        }
590
591                        if let Some(next_item) = items.get(entry.index()) {
592                            return Some(next_item);
593                        } else {
594                            None
595                        }
596                    }
597                }
598            };
599
600            if let Some(subtree) = new_subtree {
601                descend = true;
602                self.stack.push(StackEntry {
603                    tree: subtree,
604                    index: 0,
605                    position: (),
606                });
607            } else {
608                descend = false;
609                self.stack.pop();
610            }
611        }
612
613        None
614    }
615}
616
617impl<'a, 'b, T: Item, D> Iterator for Cursor<'a, 'b, T, D>
618where
619    D: Dimension<'a, T::Summary>,
620{
621    type Item = &'a T;
622
623    fn next(&mut self) -> Option<Self::Item> {
624        if !self.did_seek {
625            self.next();
626        }
627
628        if let Some(item) = self.item() {
629            self.next();
630            Some(item)
631        } else {
632            None
633        }
634    }
635}
636
637pub struct FilterCursor<'a, 'b, F, T: Item, D> {
638    cursor: Cursor<'a, 'b, T, D>,
639    filter_node: F,
640}
641
642impl<'a, 'b, F, T: Item, D> FilterCursor<'a, 'b, F, T, D>
643where
644    F: FnMut(&T::Summary) -> bool,
645    T: Item,
646    D: Dimension<'a, T::Summary>,
647{
648    pub fn new(
649        tree: &'a SumTree<T>,
650        cx: <T::Summary as Summary>::Context<'b>,
651        filter_node: F,
652    ) -> Self {
653        let cursor = tree.cursor::<D>(cx);
654        Self {
655            cursor,
656            filter_node,
657        }
658    }
659
660    pub fn start(&self) -> &D {
661        self.cursor.start()
662    }
663
664    pub fn end(&self) -> D {
665        self.cursor.end()
666    }
667
668    pub fn item(&self) -> Option<&'a T> {
669        self.cursor.item()
670    }
671
672    pub fn item_summary(&self) -> Option<&'a T::Summary> {
673        self.cursor.item_summary()
674    }
675
676    pub fn next(&mut self) {
677        self.cursor.search_forward(&mut self.filter_node);
678    }
679
680    pub fn prev(&mut self) {
681        self.cursor.search_backward(&mut self.filter_node);
682    }
683}
684
685impl<'a, 'b, F, T: Item, U> Iterator for FilterCursor<'a, 'b, F, T, U>
686where
687    F: FnMut(&T::Summary) -> bool,
688    U: Dimension<'a, T::Summary>,
689{
690    type Item = &'a T;
691
692    fn next(&mut self) -> Option<Self::Item> {
693        if !self.cursor.did_seek {
694            self.next();
695        }
696
697        if let Some(item) = self.item() {
698            self.cursor.search_forward(&mut self.filter_node);
699            Some(item)
700        } else {
701            None
702        }
703    }
704}
705
706trait SeekAggregate<'a, T: Item> {
707    fn begin_leaf(&mut self);
708    fn end_leaf(&mut self, cx: <T::Summary as Summary>::Context<'_>);
709    fn push_item(
710        &mut self,
711        item: &'a T,
712        summary: &'a T::Summary,
713        cx: <T::Summary as Summary>::Context<'_>,
714    );
715    fn push_tree(
716        &mut self,
717        tree: &'a SumTree<T>,
718        summary: &'a T::Summary,
719        cx: <T::Summary as Summary>::Context<'_>,
720    );
721}
722
723struct SliceSeekAggregate<T: Item> {
724    tree: SumTree<T>,
725    leaf_items: ArrayVec<T, { 2 * TREE_BASE }>,
726    leaf_item_summaries: ArrayVec<T::Summary, { 2 * TREE_BASE }>,
727    leaf_summary: T::Summary,
728}
729
730struct SummarySeekAggregate<D>(D);
731
732impl<T: Item> SeekAggregate<'_, T> for () {
733    fn begin_leaf(&mut self) {}
734    fn end_leaf(&mut self, _: <T::Summary as Summary>::Context<'_>) {}
735    fn push_item(&mut self, _: &T, _: &T::Summary, _: <T::Summary as Summary>::Context<'_>) {}
736    fn push_tree(
737        &mut self,
738        _: &SumTree<T>,
739        _: &T::Summary,
740        _: <T::Summary as Summary>::Context<'_>,
741    ) {
742    }
743}
744
745impl<T: Item> SeekAggregate<'_, T> for SliceSeekAggregate<T> {
746    fn begin_leaf(&mut self) {}
747    fn end_leaf(&mut self, cx: <T::Summary as Summary>::Context<'_>) {
748        self.tree.append(
749            SumTree(Arc::new(Node::Leaf {
750                summary: mem::replace(&mut self.leaf_summary, <T::Summary as Summary>::zero(cx)),
751                items: mem::take(&mut self.leaf_items),
752                item_summaries: mem::take(&mut self.leaf_item_summaries),
753            })),
754            cx,
755        );
756    }
757    fn push_item(
758        &mut self,
759        item: &T,
760        summary: &T::Summary,
761        cx: <T::Summary as Summary>::Context<'_>,
762    ) {
763        self.leaf_items.push(item.clone());
764        self.leaf_item_summaries.push(summary.clone());
765        Summary::add_summary(&mut self.leaf_summary, summary, cx);
766    }
767    fn push_tree(
768        &mut self,
769        tree: &SumTree<T>,
770        _: &T::Summary,
771        cx: <T::Summary as Summary>::Context<'_>,
772    ) {
773        self.tree.append(tree.clone(), cx);
774    }
775}
776
777impl<'a, T: Item, D> SeekAggregate<'a, T> for SummarySeekAggregate<D>
778where
779    D: Dimension<'a, T::Summary>,
780{
781    fn begin_leaf(&mut self) {}
782    fn end_leaf(&mut self, _: <T::Summary as Summary>::Context<'_>) {}
783    fn push_item(
784        &mut self,
785        _: &T,
786        summary: &'a T::Summary,
787        cx: <T::Summary as Summary>::Context<'_>,
788    ) {
789        self.0.add_summary(summary, cx);
790    }
791    fn push_tree(
792        &mut self,
793        _: &SumTree<T>,
794        summary: &'a T::Summary,
795        cx: <T::Summary as Summary>::Context<'_>,
796    ) {
797        self.0.add_summary(summary, cx);
798    }
799}
800
801struct End<D>(PhantomData<D>);
802
803impl<D> End<D> {
804    fn new() -> Self {
805        Self(PhantomData)
806    }
807}
808
809impl<'a, S: Summary, D: Dimension<'a, S>> SeekTarget<'a, S, D> for End<D> {
810    fn cmp(&self, _: &D, _: S::Context<'_>) -> Ordering {
811        Ordering::Greater
812    }
813}
814
815impl<D> fmt::Debug for End<D> {
816    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
817        f.debug_tuple("End").finish()
818    }
819}