Skip to main content

oni_comb_parser_rs/core/
parse_state.rs

1/// A struct representing the current parsing state.
2#[derive(Clone)]
3pub struct ParseState<'a, I> {
4  input: &'a [I],
5  offset: usize,
6}
7
8impl<'a, I> ParseState<'a, I> {
9  /// Creates a new parsing state with the given input and offset.
10  pub fn new(input: &'a [I], offset: usize) -> Self {
11    Self { input, offset }
12  }
13
14  /// Returns the offset of the previous position, or None if at the beginning.
15  pub fn last_offset(&self) -> Option<usize> {
16    if self.offset > 0 {
17      Some(self.offset - 1)
18    } else {
19      None
20    }
21  }
22
23  /// Returns the current offset.
24  pub fn current_offset(&self) -> usize {
25    self.offset
26  }
27
28  /// Creates a new parse state with an offset increased by the specified number of characters.
29  pub fn advance_by(&self, num_chars: usize) -> ParseState<'a, I> {
30    Self::new(self.input, self.offset + num_chars)
31  }
32
33  /// Returns the slice of input starting from the current offset.
34  pub fn input(&self) -> &'a [I] {
35    &self.input[self.offset..]
36  }
37
38  /// Returns a slice of the input with a specified length starting from the current offset.
39  pub fn slice_with_len(&self, n: usize) -> &'a [I] {
40    &self.input[self.offset..self.offset + n]
41  }
42}