From 0065b1fb9d4fc7a2b801aac34d7c9c3139b4c9ca Mon Sep 17 00:00:00 2001 From: Patric Bucher Date: Thu, 2 Nov 2023 22:21:45 +0100 Subject: [PATCH] Making use of enum_primitive_derive This simplifies converting back from a u8 to the OpCodes enum --- Cargo.toml | 2 ++ src/vm/block.rs | 27 +++++++++------------------ 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8453b46..22c2f67 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,8 @@ edition = "2021" [dependencies] colored = "2.0.4" +enum-primitive-derive = "0.2.2" +num-traits = "0.2.17" [features] disassemble = [] \ No newline at end of file diff --git a/src/vm/block.rs b/src/vm/block.rs index 51a5ca8..5d9f9a7 100644 --- a/src/vm/block.rs +++ b/src/vm/block.rs @@ -1,22 +1,13 @@ use crate::vm::constants::Constants; -use std::convert::TryFrom; -#[derive(Debug)] -pub enum OpCode { - Constant, - Return, -} - -impl TryFrom for OpCode { - type Error = (); +use enum_primitive_derive::Primitive; +use num_traits::FromPrimitive; - fn try_from(value: u8) -> Result { - match value { - 0 => Ok(OpCode::Constant), - 1 => Ok(OpCode::Return), - _ => Err(()), - } - } +#[repr(u8)] +#[derive(Debug, Primitive)] +pub enum OpCode { + Constant = 0x00, + Return = 0x01, } #[allow(dead_code)] @@ -64,7 +55,7 @@ impl BlockDbg for Block { let mut offset: usize = 0; while offset < self.instructions.len() { - offset += self.disassemble_instruction(offset); + offset = self.disassemble_instruction(offset); } println!("=== ===", self.name); @@ -73,7 +64,7 @@ impl BlockDbg for Block { fn disassemble_instruction(&self, offset: usize) -> usize { print!("{:04x} ", offset); - let instruction = OpCode::try_from(self.instructions[offset]).unwrap(); + let instruction = OpCode::from_u8(self.instructions[offset]).unwrap(); return match instruction { OpCode::Constant => self.constant_instruction(OpCode::Constant, offset), OpCode::Return => self.simple_instruction(OpCode::Return, offset),