#Matching over a repr u8 enum

7 messages · Page 1 of 1 (latest)

bronze ginkgo
#

I have an enum like so:

#[repr(u8)]
enum OpCode {
    Return = 0,
}

And some data:

let code= vec![0u8];

Is it possible to mathc using a syntax like:

    match code.get(0).unwrap().clone() {
        OpCode::Return as u8 => {
            println!("Return")
        }
        x => {}
    }

Instead of

    match code.get(0).unwrap().clone() {
        x if x == OpCode::Return as u8 => {
            println!("Return")
        }
  }
pine zenith
#

Write the conversion function, once:

impl OpCode {
    fn from_byte(code: u8) -> Option<Self> {
        Some(match code {
            0 => OpCode::Return,
            1 => OpCode::WhateverElse,
            ...
            _ => return None,
        })
    }
}

and then use it in all your matches

    match OpCode::from_byte(*code.get(0).unwrap()) {
        Some(OpCode::Return) => {
            println!("Return")
        }
        x => {}
    }
bronze ginkgo
#

Wouldn't that get really inefficient when executing large chunks of bytecode?

#

Cause I might as well do that:

const OP_CODE_RETURN = 0u8;
pine zenith
#

It will likely get inlined and become equivalent to the original match.

bronze ginkgo
#

Thanks!

ebon anchor