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: usize,
9 position: D,
10}
11
12impl<T: Item + fmt::Debug, D: fmt::Debug> fmt::Debug for StackEntry<'_, T, D> {
13 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14 f.debug_struct("StackEntry")
15 .field("index", &self.index)
16 .field("position", &self.position)
17 .finish()
18 }
19}
20
21#[derive(Clone)]
22pub struct Cursor<'a, T: Item, D> {
23 tree: &'a SumTree<T>,
24 stack: ArrayVec<StackEntry<'a, T, D>, 16>,
25 position: D,
26 did_seek: bool,
27 at_end: bool,
28 cx: &'a <T::Summary as Summary>::Context,
29}
30
31impl<T: Item + fmt::Debug, D: fmt::Debug> fmt::Debug for Cursor<'_, T, D>
32where
33 T::Summary: fmt::Debug,
34{
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.debug_struct("Cursor")
37 .field("tree", &self.tree)
38 .field("stack", &self.stack)
39 .field("position", &self.position)
40 .field("did_seek", &self.did_seek)
41 .field("at_end", &self.at_end)
42 .finish()
43 }
44}
45
46pub struct Iter<'a, T: Item> {
47 tree: &'a SumTree<T>,
48 stack: ArrayVec<StackEntry<'a, T, ()>, 16>,
49}
50
51impl<'a, T, D> Cursor<'a, T, D>
52where
53 T: Item,
54 D: Dimension<'a, T::Summary>,
55{
56 pub fn new(tree: &'a SumTree<T>, cx: &'a <T::Summary as Summary>::Context) -> Self {
57 Self {
58 tree,
59 stack: ArrayVec::new(),
60 position: D::zero(cx),
61 did_seek: false,
62 at_end: tree.is_empty(),
63 cx,
64 }
65 }
66
67 fn reset(&mut self) {
68 self.did_seek = false;
69 self.at_end = self.tree.is_empty();
70 self.stack.truncate(0);
71 self.position = D::zero(self.cx);
72 }
73
74 pub fn start(&self) -> &D {
75 &self.position
76 }
77
78 #[track_caller]
79 pub fn end(&self) -> D {
80 if let Some(item_summary) = self.item_summary() {
81 let mut end = self.start().clone();
82 end.add_summary(item_summary, self.cx);
83 end
84 } else {
85 self.start().clone()
86 }
87 }
88
89 /// Item is None, when the list is empty, or this cursor is at the end of the list.
90 #[track_caller]
91 pub fn item(&self) -> Option<&'a T> {
92 self.assert_did_seek();
93 if let Some(entry) = self.stack.last() {
94 match *entry.tree.0 {
95 Node::Leaf { ref items, .. } => {
96 if entry.index == items.len() {
97 None
98 } else {
99 Some(&items[entry.index])
100 }
101 }
102 _ => unreachable!(),
103 }
104 } else {
105 None
106 }
107 }
108
109 #[track_caller]
110 pub fn item_summary(&self) -> Option<&'a T::Summary> {
111 self.assert_did_seek();
112 if let Some(entry) = self.stack.last() {
113 match *entry.tree.0 {
114 Node::Leaf {
115 ref item_summaries, ..
116 } => {
117 if entry.index == item_summaries.len() {
118 None
119 } else {
120 Some(&item_summaries[entry.index])
121 }
122 }
123 _ => unreachable!(),
124 }
125 } else {
126 None
127 }
128 }
129
130 #[track_caller]
131 pub fn next_item(&self) -> Option<&'a T> {
132 self.assert_did_seek();
133 if let Some(entry) = self.stack.last() {
134 if entry.index == entry.tree.0.items().len() - 1 {
135 if let Some(next_leaf) = self.next_leaf() {
136 Some(next_leaf.0.items().first().unwrap())
137 } else {
138 None
139 }
140 } else {
141 match *entry.tree.0 {
142 Node::Leaf { ref items, .. } => Some(&items[entry.index + 1]),
143 _ => unreachable!(),
144 }
145 }
146 } else if self.at_end {
147 None
148 } else {
149 self.tree.first()
150 }
151 }
152
153 #[track_caller]
154 fn next_leaf(&self) -> Option<&'a SumTree<T>> {
155 for entry in self.stack.iter().rev().skip(1) {
156 if entry.index < entry.tree.0.child_trees().len() - 1 {
157 match *entry.tree.0 {
158 Node::Internal {
159 ref child_trees, ..
160 } => return Some(child_trees[entry.index + 1].leftmost_leaf()),
161 Node::Leaf { .. } => unreachable!(),
162 };
163 }
164 }
165 None
166 }
167
168 #[track_caller]
169 pub fn prev_item(&self) -> Option<&'a T> {
170 self.assert_did_seek();
171 if let Some(entry) = self.stack.last() {
172 if entry.index == 0 {
173 if let Some(prev_leaf) = self.prev_leaf() {
174 Some(prev_leaf.0.items().last().unwrap())
175 } else {
176 None
177 }
178 } else {
179 match *entry.tree.0 {
180 Node::Leaf { ref items, .. } => Some(&items[entry.index - 1]),
181 _ => unreachable!(),
182 }
183 }
184 } else if self.at_end {
185 self.tree.last()
186 } else {
187 None
188 }
189 }
190
191 #[track_caller]
192 fn prev_leaf(&self) -> Option<&'a SumTree<T>> {
193 for entry in self.stack.iter().rev().skip(1) {
194 if entry.index != 0 {
195 match *entry.tree.0 {
196 Node::Internal {
197 ref child_trees, ..
198 } => return Some(child_trees[entry.index - 1].rightmost_leaf()),
199 Node::Leaf { .. } => unreachable!(),
200 };
201 }
202 }
203 None
204 }
205
206 #[track_caller]
207 pub fn prev(&mut self) {
208 self.search_backward(|_| Ordering::Equal)
209 }
210
211 #[track_caller]
212 pub fn search_backward<F>(&mut self, mut filter_node: F)
213 where
214 F: FnMut(&T::Summary) -> Ordering,
215 {
216 if !self.did_seek {
217 self.did_seek = true;
218 self.at_end = true;
219 }
220
221 if self.at_end {
222 self.position = D::zero(self.cx);
223 self.at_end = self.tree.is_empty();
224 if !self.tree.is_empty() {
225 let position = if let Some(summary) = self.tree.0.summary() {
226 D::from_summary(summary, self.cx)
227 } else {
228 D::zero(self.cx)
229 };
230 self.stack.push(StackEntry {
231 tree: self.tree,
232 index: self.tree.0.child_summaries().len(),
233 position,
234 });
235 }
236 }
237
238 let mut descending = false;
239 while !self.stack.is_empty() {
240 if let Some(StackEntry { position, .. }) = self.stack.iter().rev().nth(1) {
241 self.position = position.clone();
242 } else {
243 self.position = D::zero(self.cx);
244 }
245
246 let entry = self.stack.last_mut().unwrap();
247 if !descending {
248 if entry.index == 0 {
249 self.stack.pop();
250 continue;
251 } else {
252 entry.index -= 1;
253 }
254 }
255
256 if entry.index != 0 {
257 self.position
258 .add_summary(&entry.tree.0.child_summaries()[entry.index - 1], self.cx);
259 }
260
261 entry.position = self.position.clone();
262
263 descending = filter_node(&entry.tree.0.child_summaries()[entry.index]).is_ge();
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() - 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(|_| Ordering::Equal)
287 }
288
289 #[track_caller]
290 pub fn search_forward<F>(&mut self, mut filter_node: F)
291 where
292 F: FnMut(&T::Summary) -> Ordering,
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 if entry.index < child_summaries.len() {
323 let index = child_summaries[entry.index..]
324 .partition_point(|item| filter_node(item).is_lt());
325
326 entry.index += index;
327
328 if let Some(summary) = child_summaries.get(entry.index) {
329 entry.position.add_summary(summary, self.cx);
330 self.position.add_summary(summary, self.cx);
331 }
332 }
333
334 child_trees.get(entry.index)
335 }
336 Node::Leaf { item_summaries, .. } => {
337 if !descend {
338 let item_summary = &item_summaries[entry.index];
339 entry.index += 1;
340 entry.position.add_summary(item_summary, self.cx);
341 self.position.add_summary(item_summary, self.cx);
342 }
343
344 if entry.index < item_summaries.len() {
345 let index = item_summaries[entry.index..]
346 .partition_point(|item| filter_node(item).is_lt());
347
348 entry.index += index;
349
350 if let Some(summary) = item_summaries.get(entry.index) {
351 entry.position.add_summary(summary, self.cx);
352 self.position.add_summary(summary, self.cx);
353 }
354 return;
355 } else {
356 None
357 }
358 }
359 }
360 };
361
362 if let Some(subtree) = new_subtree {
363 descend = true;
364 self.stack.push(StackEntry {
365 tree: subtree,
366 index: 0,
367 position: self.position.clone(),
368 });
369 } else {
370 descend = false;
371 self.stack.pop();
372 }
373 }
374
375 self.at_end = self.stack.is_empty();
376 debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf());
377 }
378
379 #[track_caller]
380 fn assert_did_seek(&self) {
381 assert!(
382 self.did_seek,
383 "Must call `seek`, `next` or `prev` before calling this method"
384 );
385 }
386}
387
388impl<'a, T, D> Cursor<'a, T, D>
389where
390 T: Item,
391 D: Dimension<'a, T::Summary>,
392{
393 #[track_caller]
394 pub fn seek<Target>(&mut self, pos: &Target, bias: Bias) -> bool
395 where
396 Target: SeekTarget<'a, T::Summary, D>,
397 {
398 self.reset();
399 self.seek_internal(pos, bias, &mut ())
400 }
401
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(),
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, T: Item, D> Iterator for Cursor<'a, 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, F, T: Item, D> {
638 cursor: Cursor<'a, T, D>,
639 filter_node: F,
640}
641
642impl<'a, F, T: Item, D> FilterCursor<'a, F, T, D>
643where
644 F: FnMut(&T::Summary) -> Ordering,
645 T: Item,
646 D: Dimension<'a, T::Summary>,
647{
648 pub fn new(
649 tree: &'a SumTree<T>,
650 cx: &'a <T::Summary as Summary>::Context,
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, F, T: Item, U> Iterator for FilterCursor<'a, F, T, U>
686where
687 F: FnMut(&T::Summary) -> Ordering,
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(&mut self, _: &SumTree<T>, _: &T::Summary, _: &<T::Summary as Summary>::Context) {}
737}
738
739impl<T: Item> SeekAggregate<'_, T> for SliceSeekAggregate<T> {
740 fn begin_leaf(&mut self) {}
741 fn end_leaf(&mut self, cx: &<T::Summary as Summary>::Context) {
742 self.tree.append(
743 SumTree(Arc::new(Node::Leaf {
744 items: mem::take(&mut self.leaf_items),
745 item_summaries: mem::take(&mut self.leaf_item_summaries),
746 })),
747 cx,
748 );
749 }
750 fn push_item(&mut self, item: &T, summary: &T::Summary, cx: &<T::Summary as Summary>::Context) {
751 self.leaf_items.push(item.clone());
752 self.leaf_item_summaries.push(summary.clone());
753 Summary::add_summary(&mut self.leaf_summary, summary, cx);
754 }
755 fn push_tree(
756 &mut self,
757 tree: &SumTree<T>,
758 _: &T::Summary,
759 cx: &<T::Summary as Summary>::Context,
760 ) {
761 self.tree.append(tree.clone(), cx);
762 }
763}
764
765impl<'a, T: Item, D> SeekAggregate<'a, T> for SummarySeekAggregate<D>
766where
767 D: Dimension<'a, T::Summary>,
768{
769 fn begin_leaf(&mut self) {}
770 fn end_leaf(&mut self, _: &<T::Summary as Summary>::Context) {}
771 fn push_item(&mut self, _: &T, summary: &'a T::Summary, cx: &<T::Summary as Summary>::Context) {
772 self.0.add_summary(summary, cx);
773 }
774 fn push_tree(
775 &mut self,
776 _: &SumTree<T>,
777 summary: &'a T::Summary,
778 cx: &<T::Summary as Summary>::Context,
779 ) {
780 self.0.add_summary(summary, cx);
781 }
782}
783
784struct End<D>(PhantomData<D>);
785
786impl<D> End<D> {
787 fn new() -> Self {
788 Self(PhantomData)
789 }
790}
791
792impl<'a, S: Summary, D: Dimension<'a, S>> SeekTarget<'a, S, D> for End<D> {
793 fn cmp(&self, _: &D, _: &S::Context) -> Ordering {
794 Ordering::Greater
795 }
796}
797
798impl<D> fmt::Debug for End<D> {
799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800 f.debug_tuple("End").finish()
801 }
802}