Skip to main content

recognize_slice/
recognize_slice.rs

1use elyze::errors::ParseResult;
2use elyze::matcher::Match;
3use elyze::recognizer::recognize_slice;
4use elyze::scanner::Scanner;
5
6// define a structure to implement the `Match` trait
7struct Hello;
8
9// implement the `Match` trait
10impl Match<u8> for Hello {
11    fn is_matching(&self, data: &[u8]) -> (bool, usize) {
12        // define the pattern to match
13        let pattern = b"hello";
14        // check if the subslice of data matches the pattern
15        (&data[..pattern.len()] == pattern, pattern.len())
16    }
17
18    fn size(&self) -> usize {
19        5
20    }
21}
22
23fn main() -> ParseResult<()> {
24    let mut scanner = Scanner::new(b"hello world");
25    let hello_string = recognize_slice(Hello, &mut scanner)?;
26
27    println!("found: {}", String::from_utf8_lossy(hello_string)); // found: "hello"
28    print!(
29        "remaining: {:?}",
30        String::from_utf8_lossy(scanner.remaining())
31    ); // remaining: " world"
32
33    Ok(())
34}