Skip to main content

recognizable/
recognizable.rs

1use elyze::matcher::Match;
2use elyze::recognizer::Recognizable;
3use elyze::scanner::Scanner;
4
5// define a structure to implement the `Match` trait
6struct UntilFirstSpace;
7
8// implement the `Match` trait
9impl Match<u8> for UntilFirstSpace {
10    fn is_matching(&self, data: &[u8]) -> (bool, usize) {
11        let mut pos = 0;
12        while pos < data.len() && data[pos] != b' ' {
13            pos += 1;
14        }
15        (pos > 0, pos)
16    }
17
18    // The size of the object is unknown
19    fn size(&self) -> usize {
20        0
21    }
22}
23
24fn main() {
25    let mut scanner = Scanner::new(b"hello world");
26    let result = UntilFirstSpace
27        .recognize_slice(&mut scanner)
28        .expect("failed to parse");
29    println!("{:?}", result.map(|s| String::from_utf8_lossy(s))); // Some("hello")
30
31    let mut scanner = Scanner::new(b"loooooooooong string");
32    let result = UntilFirstSpace
33        .recognize_slice(&mut scanner)
34        .expect("failed to parse");
35    println!("{:?}", result.map(|s| String::from_utf8_lossy(s))); // Some("loooooooooong")
36}