Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::{self, Read};
- pub enum ProtocolError {
- InvalidBytes(Vec<u8>),
- Io(io::Error),
- }
- pub struct Processor<R> {
- reader: R
- }
- pub enum ProcessResult {
- Done,
- Error(ProtocolError),
- ProtocolValue(u32)
- }
- impl<R: Read> Processor<R> {
- pub fn new(r : R) -> Self {
- Self { reader: r }
- }
- pub fn process(&mut self) -> ProcessResult {
- let mut pos: usize = 0;
- let mut process_result: u32 = 0;
- loop {
- let mut buf = [0; 4096];
- let length;
- match self.reader.read(&mut buf) {
- Ok(n) => {
- if n == 0 {
- return ProcessResult::Done;
- }
- length = n;
- },
- Err(e) => {
- return ProcessResult::Error(ProtocolError::Io(e));
- }
- }
- let mut failed = false;
- while pos < length {
- let byte = buf[pos];
- process_result += (byte as u32) * 2 + 3;
- if process_result < 128 || process_result > 256 {
- failed = true;
- break;
- }
- pos += 1;
- }
- if failed {
- let v = buf[0..pos].to_vec();
- ProcessResult::Error(ProtocolError::InvalidBytes(v));
- } else {
- ProcessResult::ProtocolValue(process_result);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment