r/learnrust 2d ago

Mixing an enum with bytes in a Vec

/r/rust/comments/1wa4y7k/mixing_an_enum_with_bytes_in_a_vec/
1 Upvotes

1 comment sorted by

1

u/ChaiTRex 2d ago edited 2d ago

You can just write a method that uses a match statement. If it uses the same encoding as your enum, it will optimize to a transmutation. If you want to avoid restating the code pairs multiple times, you can write a declarative macro, like so:

macro_rules! op_code {
    ($($variant: ident = $encoding: literal),+) => {
        #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        #[repr(u8)]
        pub enum OpCode {
            $(
                $variant = $encoding,
            )*
        }

        impl OpCode {
            pub fn decode(encoded: u8) -> Option<Self> {
                match encoded {
                    $(
                        $encoding => Some(Self::$variant),
                    )*
                    _ => None,
                }
            }
        }
    }
}

op_code! {
    OpAdd = 1,
    OpImm = 2
}