]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | |
2 | /// An iterator that produces *n* repetitions of an element. | |
3 | /// | |
4 | /// See [`repeat_n()`](../fn.repeat_n.html) for more information. | |
5 | pub struct RepeatN<A> { | |
6 | elt: Option<A>, | |
7 | n: usize, | |
8 | } | |
9 | ||
10 | /// Create an iterator that produces `n` repetitions of `element`. | |
11 | pub fn repeat_n<A>(element: A, n: usize) -> RepeatN<A> | |
12 | where A: Clone, | |
13 | { | |
14 | if n == 0 { | |
15 | RepeatN { elt: None, n: n, } | |
16 | } else { | |
17 | RepeatN { elt: Some(element), n: n, } | |
18 | } | |
19 | } | |
20 | ||
21 | impl<A> Iterator for RepeatN<A> | |
22 | where A: Clone | |
23 | { | |
24 | type Item = A; | |
25 | ||
26 | fn next(&mut self) -> Option<Self::Item> { | |
27 | if self.n > 1 { | |
28 | self.n -= 1; | |
29 | self.elt.as_ref().cloned() | |
30 | } else { | |
31 | self.n = 0; | |
32 | self.elt.take() | |
33 | } | |
34 | } | |
35 | ||
36 | fn size_hint(&self) -> (usize, Option<usize>) { | |
37 | (self.n, Some(self.n)) | |
38 | } | |
39 | } | |
40 | ||
41 | impl<A> DoubleEndedIterator for RepeatN<A> | |
42 | where A: Clone | |
43 | { | |
44 | #[inline] | |
45 | fn next_back(&mut self) -> Option<Self::Item> { | |
46 | self.next() | |
47 | } | |
48 | } | |
49 | ||
50 | impl<A> ExactSizeIterator for RepeatN<A> | |
51 | where A: Clone | |
52 | {} |