1 | use std::iter::FusedIterator; |
2 | |
3 | /// An iterator that produces *n* repetitions of an element. |
4 | /// |
5 | /// See [`repeat_n()`](crate::repeat_n) for more information. |
6 | #[must_use = "iterators are lazy and do nothing unless consumed" ] |
7 | #[derive (Clone, Debug)] |
8 | pub struct RepeatN<A> { |
9 | elt: Option<A>, |
10 | n: usize, |
11 | } |
12 | |
13 | /// Create an iterator that produces `n` repetitions of `element`. |
14 | pub fn repeat_n<A>(element: A, n: usize) -> RepeatN<A> |
15 | where A: Clone, |
16 | { |
17 | if n == 0 { |
18 | RepeatN { elt: None, n, } |
19 | } else { |
20 | RepeatN { elt: Some(element), n, } |
21 | } |
22 | } |
23 | |
24 | impl<A> Iterator for RepeatN<A> |
25 | where A: Clone |
26 | { |
27 | type Item = A; |
28 | |
29 | fn next(&mut self) -> Option<Self::Item> { |
30 | if self.n > 1 { |
31 | self.n -= 1; |
32 | self.elt.as_ref().cloned() |
33 | } else { |
34 | self.n = 0; |
35 | self.elt.take() |
36 | } |
37 | } |
38 | |
39 | fn size_hint(&self) -> (usize, Option<usize>) { |
40 | (self.n, Some(self.n)) |
41 | } |
42 | } |
43 | |
44 | impl<A> DoubleEndedIterator for RepeatN<A> |
45 | where A: Clone |
46 | { |
47 | #[inline ] |
48 | fn next_back(&mut self) -> Option<Self::Item> { |
49 | self.next() |
50 | } |
51 | } |
52 | |
53 | impl<A> ExactSizeIterator for RepeatN<A> |
54 | where A: Clone |
55 | {} |
56 | |
57 | impl<A> FusedIterator for RepeatN<A> |
58 | where A: Clone |
59 | {} |
60 | |