gameServer2/src/protocol/mod.rs
changeset 14396 cc99f7c673c7
parent 14395 e5db279308d7
child 14397 c3ae3cac8fba
equal deleted inserted replaced
14395:e5db279308d7 14396:cc99f7c673c7
     1 use netbuf;
       
     2 use std::{
       
     3     io::{Read, Result}
       
     4 };
       
     5 use nom::{
       
     6     IResult, Err
       
     7 };
       
     8 
       
     9 pub mod messages;
       
    10 #[cfg(test)]
       
    11 pub mod test;
       
    12 mod parser;
       
    13 
       
    14 pub struct ProtocolDecoder {
       
    15     buf: netbuf::Buf,
       
    16     consumed: usize,
       
    17 }
       
    18 
       
    19 impl ProtocolDecoder {
       
    20     pub fn new() -> ProtocolDecoder {
       
    21         ProtocolDecoder {
       
    22             buf: netbuf::Buf::new(),
       
    23             consumed: 0,
       
    24         }
       
    25     }
       
    26 
       
    27     pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
       
    28         self.buf.read_from(stream)
       
    29     }
       
    30 
       
    31     pub fn extract_messages(&mut self) -> Vec<messages::HWProtocolMessage> {
       
    32         let parse_result = parser::extract_messages(&self.buf[..]);
       
    33         match parse_result {
       
    34             Ok((tail, msgs)) => {
       
    35                 self.consumed = self.buf.len() - self.consumed - tail.len();
       
    36                 msgs
       
    37             },
       
    38             Err(Err::Incomplete(_)) => unreachable!(),
       
    39             Err(Err::Error(_)) | Err(Err::Failure(_)) => unreachable!(),
       
    40         }
       
    41     }
       
    42 
       
    43     pub fn sweep(&mut self) {
       
    44         self.buf.consume(self.consumed);
       
    45         self.consumed = 0;
       
    46     }
       
    47 }