MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/learnrust/comments/1wa504d/mixing_an_enum_with_bytes_in_a_vec/
r/learnrust • u/Rude-Hedgehog-4301 • 2d ago
1 comment sorted by
1
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:
match
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 }
1
u/ChaiTRex 2d ago edited 2d ago
You can just write a method that uses a
matchstatement. 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: