Skip to main content

peek

Function peek 

Source
pub fn peek<'a, T, S, E, P: Peekable<'a, T, S, E>>(
    peekable: P,
    scanner: &mut Scanner<'a, T>,
) -> ParseResult<Option<Peeking<'a, T, S, E>>>
Expand description

Attempt to match a Peekable against the current position of a Scanner.

This function will temporarily advance the position of the Scanner to find a match. If a match is found, the Scanner is rewound to the original position and a Peeking is returned. If no match is found, the Scanner is rewound to the original position and an Err is returned.

§Arguments

  • peekable - The Peekable to attempt to match.
  • scanner - The Scanner to use when matching.

§Returns

A Peeking if the Peekable matches the current position of the Scanner, or an Err otherwise.

Examples found in repository?
examples/delimited_group.rs (line 7)
4fn main() {
5    let data = b"(2 * 3)";
6    let mut scanner = noa_parser::scanner::Scanner::new(data);
7    let result = peek(GroupKind::Parenthesis, &mut scanner)
8        .expect("failed to parse")
9        .expect("failed to peek");
10    println!(
11        "{}",
12        String::from_utf8_lossy(result.peeked_slice()) // 2 * 3
13    );
14}
More examples
Hide additional examples
examples/expression.rs (line 167)
164    fn accept(scanner: &mut Scanner<'a, u8>) -> ParseResult<Self> {
165        OptionalWhitespaces::accept(scanner)?;
166        // Check if there is a parenthesis
167        let result = peek(GroupKind::Parenthesis, scanner)?;
168
169        match result {
170            Some(peeked) => {
171                // Parse the inner expression
172                let mut inner_scanner = Scanner::new(peeked.peeked_slice());
173                let inner_result = Expression::accept(&mut inner_scanner)?;
174                scanner.bump_by(peeked.end_slice);
175                Ok(inner_result)
176            }
177            None => {
178                // Parse the reduced expression or the right expression
179                let accepted = Acceptor::new(scanner)
180                    .try_or(ExpressionInternal::RightExpression)?
181                    .try_or(ExpressionInternal::Reducted)?
182                    .finish()
183                    .ok_or(ParseError::UnexpectedToken)?;
184
185                Ok(accepted.into())
186            }
187        }
188    }