Skip to main content

hello_world_acceptance2/
hello_world_acceptance2.rs

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