|
| 1 | +use crate::series::Series; |
| 2 | +use crate::{Event, Pattern}; |
| 3 | +use jiff::civil::DateTime; |
| 4 | + |
| 5 | +/// An iterator over the events of a [`Series`]. |
| 6 | +/// |
| 7 | +/// This struct is created by the [`.iter()`][Series::iter] method of a `Series`. See its |
| 8 | +/// documentation for more. |
| 9 | +#[derive(Debug, Clone)] |
| 10 | +pub struct Iter<'a, P> { |
| 11 | + series: &'a Series<P>, |
| 12 | + first: bool, |
| 13 | + cursor_front: Option<DateTime>, |
| 14 | + cursor_back: Option<DateTime>, |
| 15 | +} |
| 16 | + |
| 17 | +impl<'a, P: Pattern> Iter<'a, P> { |
| 18 | + pub(crate) fn new(series: &'a Series<P>) -> Iter<'a, P> { |
| 19 | + Iter { |
| 20 | + series, |
| 21 | + first: true, |
| 22 | + cursor_front: Some(series.start()), |
| 23 | + cursor_back: Some(series.end()), |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl<P> Iterator for Iter<'_, P> |
| 29 | +where |
| 30 | + P: Pattern, |
| 31 | +{ |
| 32 | + type Item = Event; |
| 33 | + |
| 34 | + fn next(&mut self) -> Option<Self::Item> { |
| 35 | + let cursor = self.cursor_front.take()?; |
| 36 | + let event = if self.first { |
| 37 | + self.first = false; |
| 38 | + self.series.first_event()? |
| 39 | + } else { |
| 40 | + self.series.get_event_after(cursor)? |
| 41 | + }; |
| 42 | + |
| 43 | + self.cursor_front = Some(event.start()); |
| 44 | + Some(event) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl<P> DoubleEndedIterator for Iter<'_, P> |
| 49 | +where |
| 50 | + P: Pattern, |
| 51 | +{ |
| 52 | + fn next_back(&mut self) -> Option<Self::Item> { |
| 53 | + let cursor = self.cursor_back.take()?; |
| 54 | + let event = self.series.get_event_before(cursor)?; |
| 55 | + self.cursor_back = Some(event.start()); |
| 56 | + Some(event) |
| 57 | + } |
| 58 | +} |
0 commit comments