Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::convert::From;
- #[derive(Copy, Clone, Debug)]
- enum Keypress {
- Left,
- Right,
- Down,
- Up,
- Enter,
- }
- macro_rules! enum_from_bytes{
- (@enumerate $type:ident, $bytes:ident, $index:expr, (($current_variant:ident)); $($arms:tt)+) => ({
- const $current_variant: u8 = $index;
- match $bytes[0] {
- $($arms)*
- $current_variant => $current_expression,
- _ => panic!(concat!("No valid enum of type ", stringify!($type), " could be constructed from {} (max index is {})"), $bytes[0], $current_variant),
- }
- });
- (@enumerate $type:ident, $bytes:ident, $index:expr, (($current_variant:ident), $($variant:tt)+); $($arms:tt)*) => ({
- const $current_variant: u8 = $index;
- enum_from_bytes!(@enumerate $type, $bytes, $index + 1, ($($variant),+); $($arms)* $current_variant => $current_expression,)
- });
- ($type:ident => {$($variant:tt)+}) => ({
- impl<'a> From<&'a [u8]> for $type {
- #[allow(non_upper_case_globals)]
- fn from(bytes: &'a [u8]) -> Self {
- enum_from_bytes!(@enumerate $type, bytes, 0, ($($variant)+) ;)
- }
- }
- });
- ($type:ident => [$($variant:ident),+]) => ({
- impl<'a> From<&'a [u8]> for $type {
- fn from(bytes: &'a [u8]) -> Self {
- [$($type::$variant),+][bytes[0] as usize]
- }
- }
- })
- }
- fn main() {
- enum_from_bytes!(Keypress => {
- (Left)
- (Right)
- (Down)
- (Up)
- (Enter)
- });
- println!("{:?}", Keypress::from(&[1, 4][..]));
- }
Add Comment
Please, Sign In to add comment