Skip to content

Commit

Permalink
Making use of enum_primitive_derive
Browse files Browse the repository at this point in the history
This simplifies converting back from a u8 to the OpCodes enum
  • Loading branch information
patbuc committed Nov 2, 2023
1 parent ea8e60b commit 0065b1f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 18 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ edition = "2021"

[dependencies]
colored = "2.0.4"
enum-primitive-derive = "0.2.2"
num-traits = "0.2.17"

[features]
disassemble = []
27 changes: 9 additions & 18 deletions src/vm/block.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
use crate::vm::constants::Constants;
use std::convert::TryFrom;

#[derive(Debug)]
pub enum OpCode {
Constant,
Return,
}

impl TryFrom<u8> for OpCode {
type Error = ();
use enum_primitive_derive::Primitive;
use num_traits::FromPrimitive;

fn try_from(value: u8) -> Result<Self, Self::Error> {
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)]
Expand Down Expand Up @@ -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);
Expand All @@ -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),
Expand Down

0 comments on commit 0065b1f

Please sign in to comment.