Skip to main content

peek_from_visitor/
peek_from_visitor.rs

1use elyze::errors::ParseResult;
2use elyze::matcher::Match;
3use elyze::peek::{peek, DefaultPeekableImplementation, PeekableImplementation};
4use elyze::scanner::Scanner;
5
6#[derive(Default)]
7struct CloseParentheses;
8
9impl Match<u8> for CloseParentheses {
10    fn is_matching(&self, data: &[u8]) -> (bool, usize) {
11        if data[0] == b')' {
12            (true, 1)
13        } else {
14            (false, 0)
15        }
16    }
17
18    fn size(&self) -> usize {
19        1
20    }
21}
22
23impl PeekableImplementation for CloseParentheses {
24    type Type = DefaultPeekableImplementation;
25}
26
27fn main() -> ParseResult<()> {
28    let data = b"7 * ( 1 + 2 )";
29    let mut scanner = Scanner::new(data);
30    scanner.bump_by(5); // consumes : 7 * (
31    let result = peek(CloseParentheses, &scanner)?;
32    if let Some(peeking) = result {
33        println!(
34            "{:?}",
35            // the peek_slice method returns the slice of recognized without the end element
36            String::from_utf8_lossy(peeking.peeked_slice()) // 1 + 2
37        );
38    } else {
39        println!("not found");
40    }
41    println!(
42        "scanner: {:?}",
43        // the scanner itself remains unchanged
44        String::from_utf8_lossy(scanner.remaining()) // scanner: " 1 + 2 )"
45    );
46    Ok(())
47}