1 | use std::iter::{Enumerate, Peekable}; |
2 | |
3 | pub struct TemplateLoop<I> |
4 | where |
5 | I: Iterator, |
6 | { |
7 | iter: Peekable<Enumerate<I>>, |
8 | } |
9 | |
10 | impl<I> TemplateLoop<I> |
11 | where |
12 | I: Iterator, |
13 | { |
14 | #[inline ] |
15 | pub fn new(iter: I) -> Self { |
16 | TemplateLoop { |
17 | iter: iter.enumerate().peekable(), |
18 | } |
19 | } |
20 | } |
21 | |
22 | impl<I> Iterator for TemplateLoop<I> |
23 | where |
24 | I: Iterator, |
25 | { |
26 | type Item = (<I as Iterator>::Item, LoopItem); |
27 | |
28 | #[inline ] |
29 | fn next(&mut self) -> Option<(<I as Iterator>::Item, LoopItem)> { |
30 | self.iter.next().map(|(index: usize, item: ::Item)| { |
31 | ( |
32 | item, |
33 | LoopItem { |
34 | index, |
35 | first: index == 0, |
36 | last: self.iter.peek().is_none(), |
37 | }, |
38 | ) |
39 | }) |
40 | } |
41 | } |
42 | |
43 | #[derive (Copy, Clone)] |
44 | pub struct LoopItem { |
45 | pub index: usize, |
46 | pub first: bool, |
47 | pub last: bool, |
48 | } |
49 | |