1use crate::io;
23pub struct LineColIterator<I> {
4 iter: I,
56/// Index of the current line. Characters in the first line of the input
7 /// (before the first newline character) are in line 1.
8line: usize,
910/// Index of the current column. The first character in the input and any
11 /// characters immediately following a newline character are in column 1.
12 /// The column is 0 immediately after a newline character has been read.
13col: usize,
1415/// Byte offset of the start of the current line. This is the sum of lengths
16 /// of all previous lines. Keeping track of things this way allows efficient
17 /// computation of the current line, column, and byte offset while only
18 /// updating one of the counters in `next()` in the common case.
19start_of_line: usize,
20}
2122impl<I> LineColIterator<I>
23where
24I: Iterator<Item = io::Result<u8>>,
25{
26pub fn new(iter: I) -> LineColIterator<I> {
27 LineColIterator {
28 iter,
29 line: 1,
30 col: 0,
31 start_of_line: 0,
32 }
33 }
3435pub fn line(&self) -> usize {
36self.line
37 }
3839pub fn col(&self) -> usize {
40self.col
41 }
4243pub fn byte_offset(&self) -> usize {
44self.start_of_line + self.col
45 }
46}
4748impl<I> Iterator for LineColIterator<I>
49where
50I: Iterator<Item = io::Result<u8>>,
51{
52type Item = io::Result<u8>;
5354fn next(&mut self) -> Option<io::Result<u8>> {
55match self.iter.next() {
56None => None,
57Some(Ok(b'\n')) => {
58self.start_of_line += self.col + 1;
59self.line += 1;
60self.col = 0;
61Some(Ok(b'\n'))
62 }
63Some(Ok(c)) => {
64self.col += 1;
65Some(Ok(c))
66 }
67Some(Err(e)) => Some(Err(e)),
68 }
69 }
70}