SHARE
TWEET

Untitled

a guest Jul 12th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::mem;
  2. #[derive(Debug)]
  3. struct Foo {
  4.     a: u8,
  5.     b: u8,
  6. }
  7. #[macro_export]
  8. macro_rules! parse_bytes {
  9.     ( $buf:expr; ) => {};
  10.     ( $buf:expr; $( $t:tt => $field:expr ),+ ) => {
  11.         let mut index: usize = 0;
  12.         $(
  13.             _parse_field!($t => $buf; $field; index);
  14.         )+
  15.     }
  16. }
  17.  
  18. macro_rules! _parse_field {
  19.     ( u8 => $buf:expr; $field:expr; $index:expr ) => {
  20.         $field = u8::from_le_bytes([$buf[$index]]);
  21.         $index += 1;
  22.     };
  23.     ( u16 => $buf:expr; $field:expr; $index:expr ) => {
  24.         $field = u16::from_le_bytes([$buf[$index], $buf[$index+1]]);
  25.         $index += 2;
  26.     };
  27.     ( u32 => $buf:expr; $field:expr; $index:expr ) => {
  28.         $field = u16::from_le_bytes([$buf[$index], $buf[$index+1], $buf[$index+2], $buf[$index+3]]);
  29.         $index += 4;
  30.     };
  31. }
  32.  
  33. fn main() {
  34.     let mut x = Foo {a:0, b:0};
  35.     let buf: &[u8] = &[1, 2];
  36.     parse_bytes!{buf;
  37.         u8 => x.a,
  38.         u8 => x.b
  39.     }
  40.     println!("{:?}", x);
  41. }
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