specmc_protocol/
lib.rs

1//! A library for parsing Minecraft protocol specification.
2
3pub mod base;
4pub mod enums;
5pub mod packets;
6#[cfg(feature = "spec")]
7pub mod spec;
8pub mod types;
9
10use specmc_base::parse::{Parse, ParseError};
11
12use enums::Enum;
13use packets::Packet;
14use types::CustomType;
15
16#[derive(Debug, Clone, PartialEq)]
17pub struct Protocol {
18    pub enums: Vec<Enum>,
19    pub types: Vec<CustomType>,
20    pub packets: Vec<Packet>,
21}
22impl Parse for Protocol {
23    fn parse(tokens: &mut Vec<String>) -> Result<Self, specmc_base::parse::ParseError> {
24        let mut enums: Vec<Enum> = vec![];
25        let mut types: Vec<CustomType> = vec![];
26        let mut packets: Vec<Packet> = vec![];
27        while !tokens.is_empty() {
28            match tokens.last().unwrap().as_str() {
29                "enum" => {
30                    enums.push(Enum::parse(tokens)?);
31                }
32                "type" => {
33                    types.push(CustomType::parse(tokens)?);
34                }
35                "packet" => {
36                    packets.push(Packet::parse(tokens)?);
37                }
38                token => {
39                    return Err(ParseError::InvalidToken {
40                        token: token.to_string(),
41                        error: "Expected \"enum\", \"type\" or \"packet\"".to_string(),
42                    });
43                }
44            }
45        }
46
47        Ok(Protocol {
48            enums,
49            types,
50            packets,
51        })
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    #[macro_export]
58    macro_rules! test_parse {
59        ($tokens:ident, $ty:ty, $value:expr) => {
60            assert_eq!(<$ty>::parse(&mut $tokens), $value);
61        }
62    }
63}