Optional parameters parsing function
authorunc0rr
Wed, 11 Jan 2017 17:39:21 +0300
changeset 12134 109e6765b1fc
parent 12133 81df2e1f9ae9
child 12135 23ee939ba66a
Optional parameters parsing function
gameServer2/src/protocol/parser.rs
--- a/gameServer2/src/protocol/parser.rs	Sun Jan 08 23:57:45 2017 +0300
+++ b/gameServer2/src/protocol/parser.rs	Wed Jan 11 17:39:21 2017 +0300
@@ -7,8 +7,8 @@
 
 named!(end_of_message, tag!("\n\n"));
 named!(a_line<&[u8], &str>, map_res!(not_line_ending, str::from_utf8));
-//fn number_line<T>(input: &[u8]) -> IResult<&[u8], T> {
-//}
+named!(opt_param<&[u8], Option<&str> >, opt!(flat_map!(preceded!(eol, a_line), non_empty)));
+
 named!(basic_message<&[u8], HWProtocolMessage>, alt!(
     do_parse!(tag!("PING") >> (Ping))
     | do_parse!(tag!("PONG") >> (Pong))
@@ -26,6 +26,7 @@
 named!(one_param_message<&[u8], HWProtocolMessage>, alt!(
     do_parse!(tag!("NICK") >> eol >> n: a_line >> (Nick(n)))
     | do_parse!(tag!("PROTO") >> eol >> d: map_res!(a_line, FromStr::from_str) >> (Proto(d)))
+    | do_parse!(tag!("QUIT") >> msg: opt_param >> (Quit(msg)))
 ));
 
 named!(message<&[u8],HWProtocolMessage>, terminated!(alt!(
@@ -33,12 +34,13 @@
     | one_param_message
 ), end_of_message));
 
-named!(messages<&[u8], Vec<HWProtocolMessage> >, many0!(message));
 
 #[test]
 fn parse_test() {
-    assert_eq!(message(b"PING\n\n"), IResult::Done(&b""[..], Ping));
-    assert_eq!(message(b"START_GAME\n\n"), IResult::Done(&b""[..], StartGame));
+    assert_eq!(message(b"PING\n\n"),          IResult::Done(&b""[..], Ping));
+    assert_eq!(message(b"START_GAME\n\n"),    IResult::Done(&b""[..], StartGame));
     assert_eq!(message(b"NICK\nit's me\n\n"), IResult::Done(&b""[..], Nick("it's me")));
-    assert_eq!(message(b"PROTO\n51\n\n"), IResult::Done(&b""[..], Proto(51)));
+    assert_eq!(message(b"PROTO\n51\n\n"),     IResult::Done(&b""[..], Proto(51)));
+    assert_eq!(message(b"QUIT\nbye-bye\n\n"), IResult::Done(&b""[..], Quit(Some("bye-bye"))));
+    assert_eq!(message(b"QUIT\n\n"),          IResult::Done(&b""[..], Quit(None)));
 }