summaryrefslogtreecommitdiffstats
path: root/vendor/tabled/src/grid/records/into_records/limit_row_records.rs
blob: a461c66829345a48f04dfbb8bce31e754937b005 (plain)
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
53
54
55
56
57
58
59
//! The module contains [`LimitRows`] records iterator.

use crate::grid::records::IntoRecords;

/// [`LimitRows`] is an records iterator which limits amount of rows.
#[derive(Debug)]
pub struct LimitRows<I> {
    records: I,
    limit: usize,
}

impl LimitRows<()> {
    /// Creates new [`LimitRows`] iterator.
    pub fn new<I: IntoRecords>(records: I, limit: usize) -> LimitRows<I> {
        LimitRows { records, limit }
    }
}

impl<I> IntoRecords for LimitRows<I>
where
    I: IntoRecords,
{
    type Cell = I::Cell;
    type IterColumns = I::IterColumns;
    type IterRows = LimitRowsIter<<I::IterRows as IntoIterator>::IntoIter>;

    fn iter_rows(self) -> Self::IterRows {
        LimitRowsIter {
            iter: self.records.iter_rows().into_iter(),
            limit: self.limit,
        }
    }
}

/// A rows iterator for [`LimitRows`]
#[derive(Debug)]
pub struct LimitRowsIter<I> {
    iter: I,
    limit: usize,
}

impl<I> Iterator for LimitRowsIter<I>
where
    I: Iterator,
    I::Item: IntoIterator,
    <I::Item as IntoIterator>::Item: AsRef<str>,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if self.limit == 0 {
            return None;
        }

        self.limit -= 1;

        self.iter.next()
    }
}