Guest User

Untitled

a guest
Oct 22nd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. use std::convert::From;
  2.  
  3.  
  4. #[derive(Copy, Clone, Debug)]
  5. enum Keypress {
  6. Left,
  7. Right,
  8. Down,
  9. Up,
  10. Enter,
  11. }
  12.  
  13.  
  14. macro_rules! enum_from_bytes{
  15. (@enumerate $type:ident, $bytes:ident, $index:expr, (($current_variant:ident)); $($arms:tt)+) => ({
  16. const $current_variant: u8 = $index;
  17. match $bytes[0] {
  18. $($arms)*
  19. $current_variant => $current_expression,
  20. _ => panic!(concat!("No valid enum of type ", stringify!($type), " could be constructed from {} (max index is {})"), $bytes[0], $current_variant),
  21. }
  22. });
  23. (@enumerate $type:ident, $bytes:ident, $index:expr, (($current_variant:ident), $($variant:tt)+); $($arms:tt)*) => ({
  24. const $current_variant: u8 = $index;
  25. enum_from_bytes!(@enumerate $type, $bytes, $index + 1, ($($variant),+); $($arms)* $current_variant => $current_expression,)
  26. });
  27. ($type:ident => {$($variant:tt)+}) => ({
  28. impl<'a> From<&'a [u8]> for $type {
  29. #[allow(non_upper_case_globals)]
  30. fn from(bytes: &'a [u8]) -> Self {
  31. enum_from_bytes!(@enumerate $type, bytes, 0, ($($variant)+) ;)
  32. }
  33. }
  34. });
  35. ($type:ident => [$($variant:ident),+]) => ({
  36. impl<'a> From<&'a [u8]> for $type {
  37. fn from(bytes: &'a [u8]) -> Self {
  38. [$($type::$variant),+][bytes[0] as usize]
  39. }
  40. }
  41. })
  42. }
  43.  
  44. fn main() {
  45. enum_from_bytes!(Keypress => {
  46. (Left)
  47. (Right)
  48. (Down)
  49. (Up)
  50. (Enter)
  51. });
  52.  
  53. println!("{:?}", Keypress::from(&[1, 4][..]));
  54. }
Add Comment
Please, Sign In to add comment