1 | use std::iter::Peekable; |
2 | use std::ops::Deref; |
3 | |
4 | pub struct Delimited<I: Iterator> { |
5 | is_first: bool, |
6 | iter: Peekable<I>, |
7 | } |
8 | |
9 | pub trait IterDelimited: Iterator + Sized { |
10 | fn delimited(self) -> Delimited<Self> { |
11 | Delimited { |
12 | is_first: true, |
13 | iter: self.peekable(), |
14 | } |
15 | } |
16 | } |
17 | |
18 | impl<I: Iterator> IterDelimited for I {} |
19 | |
20 | pub struct IteratorItem<T> { |
21 | value: T, |
22 | pub is_first: bool, |
23 | pub is_last: bool, |
24 | } |
25 | |
26 | impl<I: Iterator> Iterator for Delimited<I> { |
27 | type Item = IteratorItem<I::Item>; |
28 | |
29 | fn next(&mut self) -> Option<Self::Item> { |
30 | let item: IteratorItem<::Item> = IteratorItem { |
31 | value: self.iter.next()?, |
32 | is_first: self.is_first, |
33 | is_last: self.iter.peek().is_none(), |
34 | }; |
35 | self.is_first = false; |
36 | Some(item) |
37 | } |
38 | } |
39 | |
40 | impl<T> Deref for IteratorItem<T> { |
41 | type Target = T; |
42 | |
43 | fn deref(&self) -> &Self::Target { |
44 | &self.value |
45 | } |
46 | } |
47 | |