SHARE
TWEET

Untitled

a guest Sep 18th, 2019 95 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #[derive(Debug, Default)]
  2. struct Checksum(Option<(u8, u8)>);
  3.  
  4. impl Checksum {
  5.     fn push(&mut self, data: u8) {
  6.         let (ck_a, ck_b) = self.0.get_or_insert((0, 0));
  7.         *ck_a = ck_a.wrapping_add(data);
  8.         *ck_b = ck_b.wrapping_add(*ck_a);
  9.     }
  10.  
  11.     fn take(&mut self) -> (u8, u8) {
  12.         self.0.take().unwrap_or((0, 0))
  13.     }
  14. }
  15.  
  16. pub fn calculate_checksum(buf: &[u8], offset: usize) -> (u8, u8) {
  17.     let mut ck_a: u8 = 0;
  18.     let mut ck_b: u8 = 0;
  19.  
  20.     let len = buf.len() - 2;
  21.  
  22.     for i in buf.iter().take(len).skip(offset) {
  23.         ck_a = ck_a.wrapping_add(*i);
  24.         ck_b = ck_b.wrapping_add(ck_a);
  25.     }
  26.     (ck_a, ck_b)
  27. }
  28.  
  29. fn main() {
  30.     let vals: Vec<u8> = (0..100).collect();
  31.    
  32.     let ck0 = {
  33.         let mut ckobj = Checksum::default();
  34.         for v in &vals[..vals.len()-2] {
  35.             ckobj.push(*v);
  36.         }
  37.         ckobj.take()
  38.     };
  39.    
  40.     // current method
  41.     let ck1 = calculate_checksum(&vals, 0);
  42.     assert_eq!(ck0, ck1);
  43. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top