gameServer2/src/protocol.rs
changeset 14420 06672690d71b
parent 14419 6843c4551cde
child 14421 96624a6cdb93
equal deleted inserted replaced
14419:6843c4551cde 14420:06672690d71b
     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 }