rust/hedgewars-server/src/protocol.rs
changeset 14420 06672690d71b
parent 14380 cc99f7c673c7
child 14462 98ef2913ec73
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rust/hedgewars-server/src/protocol.rs	Mon Dec 10 22:44:46 2018 +0100
@@ -0,0 +1,47 @@
+use netbuf;
+use std::{
+    io::{Read, Result}
+};
+use nom::{
+    IResult, Err
+};
+
+pub mod messages;
+#[cfg(test)]
+pub mod test;
+mod parser;
+
+pub struct ProtocolDecoder {
+    buf: netbuf::Buf,
+    consumed: usize,
+}
+
+impl ProtocolDecoder {
+    pub fn new() -> ProtocolDecoder {
+        ProtocolDecoder {
+            buf: netbuf::Buf::new(),
+            consumed: 0,
+        }
+    }
+
+    pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
+        self.buf.read_from(stream)
+    }
+
+    pub fn extract_messages(&mut self) -> Vec<messages::HWProtocolMessage> {
+        let parse_result = parser::extract_messages(&self.buf[..]);
+        match parse_result {
+            Ok((tail, msgs)) => {
+                self.consumed = self.buf.len() - self.consumed - tail.len();
+                msgs
+            },
+            Err(Err::Incomplete(_)) => unreachable!(),
+            Err(Err::Error(_)) | Err(Err::Failure(_)) => unreachable!(),
+        }
+    }
+
+    pub fn sweep(&mut self) {
+        self.buf.consume(self.consumed);
+        self.consumed = 0;
+    }
+}