Skip to main content

hello_world_acceptance/
hello_world_acceptance.rs

1use elyze::errors::ParseResult;
2use elyze::matcher::Match;
3use elyze::recognizer::recognize;
4use elyze::scanner::Scanner;
5use elyze::visitor::Visitor;
6
7struct Hello;
8struct Space;
9struct World;
10
11impl Match<u8> for Hello {
12    fn is_matching(&self, data: &[u8]) -> (bool, usize) {
13        (&data[..5] == b"hello", 5)
14    }
15
16    fn size(&self) -> usize {
17        5
18    }
19}
20
21impl Match<u8> for Space {
22    fn is_matching(&self, data: &[u8]) -> (bool, usize) {
23        (data[0] as char == ' ', 1)
24    }
25
26    fn size(&self) -> usize {
27        1
28    }
29}
30
31impl Match<u8> for World {
32    fn is_matching(&self, data: &[u8]) -> (bool, usize) {
33        (&data[..5] == b"world", 5)
34    }
35
36    fn size(&self) -> usize {
37        5
38    }
39}
40
41// define a structure to implement the `Visitor` trait
42#[derive(Debug)]
43struct HelloWorld;
44
45impl<'a> Visitor<'a, u8> for HelloWorld {
46    fn accept(scanner: &mut Scanner<'a, u8>) -> ParseResult<Self> {
47        recognize(Hello, scanner)?; // recognize the word "hello"
48        recognize(Space, scanner)?; // recognize the space character
49        recognize(World, scanner)?; // recognize the word "world"
50        // return the `HelloWorld` object
51        Ok(HelloWorld)
52    }
53}
54
55fn main() {
56    let data = b"hello world";
57    let mut scanner = elyze::scanner::Scanner::new(data);
58    let result = HelloWorld::accept(&mut scanner);
59    println!("{:?}", result); // Ok(HelloWorld)
60}