Coverage Report

Created: 2025-07-18 06:49

/rust/registry/src/index.crates.io-6f17d22bba15001f/itertools-0.12.1/src/repeatn.rs
Line
Count
Source (jump to first uncovered line)
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
    pub(crate) elt: Option<A>,
10
    n: usize,
11
}
12
13
/// Create an iterator that produces `n` repetitions of `element`.
14
0
pub fn repeat_n<A>(element: A, n: usize) -> RepeatN<A>
15
0
where
16
0
    A: Clone,
17
0
{
18
0
    if n == 0 {
19
0
        RepeatN { elt: None, n }
20
    } else {
21
0
        RepeatN {
22
0
            elt: Some(element),
23
0
            n,
24
0
        }
25
    }
26
0
}
27
28
impl<A> Iterator for RepeatN<A>
29
where
30
    A: Clone,
31
{
32
    type Item = A;
33
34
0
    fn next(&mut self) -> Option<Self::Item> {
35
0
        if self.n > 1 {
36
0
            self.n -= 1;
37
0
            self.elt.as_ref().cloned()
38
        } else {
39
0
            self.n = 0;
40
0
            self.elt.take()
41
        }
42
0
    }
43
44
0
    fn size_hint(&self) -> (usize, Option<usize>) {
45
0
        (self.n, Some(self.n))
46
0
    }
47
48
0
    fn fold<B, F>(self, mut init: B, mut f: F) -> B
49
0
    where
50
0
        F: FnMut(B, Self::Item) -> B,
51
0
    {
52
0
        match self {
53
0
            Self { elt: Some(elt), n } => {
54
0
                debug_assert!(n > 0);
55
0
                init = (1..n).map(|_| elt.clone()).fold(init, &mut f);
56
0
                f(init, elt)
57
            }
58
0
            _ => init,
59
        }
60
0
    }
61
}
62
63
impl<A> DoubleEndedIterator for RepeatN<A>
64
where
65
    A: Clone,
66
{
67
    #[inline]
68
0
    fn next_back(&mut self) -> Option<Self::Item> {
69
0
        self.next()
70
0
    }
71
72
    #[inline]
73
0
    fn rfold<B, F>(self, init: B, f: F) -> B
74
0
    where
75
0
        F: FnMut(B, Self::Item) -> B,
76
0
    {
77
0
        self.fold(init, f)
78
0
    }
79
}
80
81
impl<A> ExactSizeIterator for RepeatN<A> where A: Clone {}
82
83
impl<A> FusedIterator for RepeatN<A> where A: Clone {}