1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
mod context;
mod data;
mod expr;
mod key;
mod parse;
mod render;
mod spec;

pub use context::Context;
pub use data::Data;
pub use expr::Expr;
pub use key::Key;
pub use render::render;
pub use render::Render;
pub use render::Renderable;
pub use spec::Spec;

pub enum Endian {
    Little,
    Big,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sample() {
        let bytes = render((
            1234u64,
            50000u16,
        ));
        let spec = Spec::st(vec![
            Spec::le_magic_u64(1234),
            Spec::le_uint(1),
            Spec::le_uint(1),
        ]);

        let data = spec.parse(&bytes).unwrap();

        assert_eq!(data, Data::Struct(vec![
            Data::Int(1234),
            Data::Int(80),
            Data::Int(195),
        ]));
        assert_eq!(50000, (195 << 8) + 80);
    }

    #[test]
    fn alternatives() {
        let bytes = render((
            1234u64,
            50000u16,
        ));
        let spec = Spec::en(vec![
            ("big", Spec::st(vec![
                Spec::be_magic_u64(1234),
                Spec::be_uint(1),
                Spec::be_uint(1),
            ])),
            ("little", Spec::st(vec![
                Spec::le_magic_u64(1234),
                Spec::le_uint(1),
                Spec::le_uint(1),
            ])),
        ]);

        let data = spec.parse(&bytes).unwrap();

        assert_eq!(data, Data::Enum(
            "little".into(),
            Data::Struct(vec![
                Data::Int(1234),
                Data::Int(80),
                Data::Int(195),
            ]).into(),
        ));
        assert_eq!(50000, (195 << 8) + 80);
    }
}