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