Guest User

Untitled

a guest
Oct 17th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. use std::io::{self, Read};
  2.  
  3. pub enum ProtocolError {
  4. InvalidBytes(Vec<u8>),
  5. Io(io::Error),
  6. }
  7.  
  8. pub struct Processor<R> {
  9. reader: R
  10. }
  11.  
  12. pub enum ProcessResult {
  13. Done,
  14. Error(ProtocolError),
  15. ProtocolValue(u32)
  16. }
  17.  
  18. impl<R: Read> Processor<R> {
  19. pub fn new(r : R) -> Self {
  20. Self { reader: r }
  21. }
  22.  
  23. pub fn process(&mut self) -> ProcessResult {
  24. let mut pos: usize = 0;
  25. let mut process_result: u32 = 0;
  26.  
  27. loop {
  28. let mut buf = [0; 4096];
  29. let length;
  30.  
  31. match self.reader.read(&mut buf) {
  32. Ok(n) => {
  33. if n == 0 {
  34. return ProcessResult::Done;
  35. }
  36. length = n;
  37. },
  38. Err(e) => {
  39. return ProcessResult::Error(ProtocolError::Io(e));
  40. }
  41. }
  42. let mut failed = false;
  43. while pos < length {
  44. let byte = buf[pos];
  45.  
  46. process_result += (byte as u32) * 2 + 3;
  47. if process_result < 128 || process_result > 256 {
  48. failed = true;
  49. break;
  50. }
  51. pos += 1;
  52. }
  53. if failed {
  54. let v = buf[0..pos].to_vec();
  55. ProcessResult::Error(ProtocolError::InvalidBytes(v));
  56. } else {
  57. ProcessResult::ProtocolValue(process_result);
  58. }
  59. }
  60. }
  61. }
Add Comment
Please, Sign In to add comment