1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use crate::LendingIterator;

/// A Lending iterator that only lends the first `n` iterations of `iter`.
#[derive(Clone, Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Take<I> {
    iter: I,
    n: usize,
}

impl<I> Take<I>
where
    I: LendingIterator,
{
    pub(crate) fn new(iter: I, n: usize) -> Take<I> {
        Take { iter, n }
    }
}

impl<I> LendingIterator for Take<I>
where
    I: LendingIterator,
{
    type Item<'a> = I::Item<'a> where I: 'a;

    #[inline]
    #[allow(clippy::if_not_else)]
    fn next(&mut self) -> Option<Self::Item<'_>> {
        if self.n != 0 {
            self.n -= 1;
            self.iter.next()
        } else {
            None
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::ToLendingIterator;
    #[test]
    fn test() {
        assert_eq!(
            std::iter::repeat(())
                .into_lending()
                .take(5)
                .fold(0, |count, ()| { count + 1 }),
            5
        );
    }
}