graphql_toolkit_parser/
pos.rs

1use std::str::Chars;
2
3use graphql_toolkit_ast::Pos;
4use pest::{iterators::Pair, RuleType};
5
6pub(crate) struct PositionCalculator<'a> {
7    input: Chars<'a>,
8    pos: usize,
9    line: usize,
10    column: usize,
11}
12
13impl<'a> PositionCalculator<'a> {
14    pub(crate) fn new(input: &'a str) -> PositionCalculator<'a> {
15        Self {
16            input: input.chars(),
17            pos: 0,
18            line: 1,
19            column: 1,
20        }
21    }
22
23    pub(crate) fn step<R: RuleType>(&mut self, pair: &Pair<R>) -> Pos {
24        let pos = pair.as_span().start();
25        debug_assert!(pos >= self.pos);
26        for _ in 0..pos - self.pos {
27            match self.input.next() {
28                Some('\r') => {
29                    self.column = 1;
30                }
31                Some('\n') => {
32                    self.line += 1;
33                    self.column = 1;
34                }
35                Some(_) => {
36                    self.column += 1;
37                }
38                None => break,
39            }
40        }
41        self.pos = pos;
42        Pos {
43            line: self.line,
44            column: self.column,
45        }
46    }
47}