token_read/
iter.rs

1use std::{io::BufRead, marker::PhantomData};
2
3use crate::{FromTokens, LineCount, ReadTokensError, TokenReader};
4
5/// An iterator returned from [`TokenReader::take`].
6#[derive(Debug)]
7pub struct Take<'a, T, R, S> {
8    reader: &'a mut TokenReader<R>,
9    remaining: S,
10    _phantom: PhantomData<T>,
11}
12
13impl<'a, T, R, S> Take<'a, T, R, S>
14where
15    R: BufRead,
16    T: FromTokens,
17    S: LineCount,
18{
19    /// Creates a new [`Take`] iterator. It's recommended to use [`TokenReader::take`] instead.
20    pub fn new(reader: &'a mut TokenReader<R>, count: S) -> Self {
21        Take {
22            reader,
23            remaining: count,
24            _phantom: PhantomData::default(),
25        }
26    }
27}
28
29impl<'a, T, R, S> Iterator for Take<'a, T, R, S>
30where
31    R: BufRead,
32    T: FromTokens,
33    S: LineCount,
34{
35    type Item = Result<T, ReadTokensError<T::Error>>;
36
37    fn next(&mut self) -> Option<Self::Item> {
38        if !self.remaining.empty() {
39            self.remaining.decrement();
40
41            Some(self.reader.line())
42        } else {
43            None
44        }
45    }
46}