rascal_bytecode 0.1.2

Rascal programming language bytecode.
Documentation
use core::convert::TryFrom;

#[derive(Debug, Clone)]
pub enum Op {
    Constant,
    Add,
    Subtract,
    Multiply,
    Divide,
    Negate,
    Return,
}
impl From<Op> for u8 {
    fn from(item: Op) -> Self {
        item as u8
    }
}
impl TryFrom<u8> for Op {
    type Error = &'static str;
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        /* match value { // Unsafe but maybe faster than the big match statement?
            0..=Op::MAX => Ok(unsafe { std::mem::transmute(value) }),
            _ => Err("Byte out of bounds of Opcode range"),
        } */
        match value {
            x if x == Op::Constant as u8 => Ok(Op::Constant),
            x if x == Op::Add as u8 => Ok(Op::Add),
            x if x == Op::Subtract as u8 => Ok(Op::Subtract),
            x if x == Op::Multiply as u8 => Ok(Op::Multiply),
            x if x == Op::Divide as u8 => Ok(Op::Divide),
            x if x == Op::Negate as u8 => Ok(Op::Negate),
            x if x == Op::Return as u8 => Ok(Op::Return),
            _ => Err("Byte out of bounds of Opcode range"),
        }
    }
}