From 41c9be12ed724b792f870ccecfff2adc699caaa6 Mon Sep 17 00:00:00 2001 From: iximeow Date: Fri, 3 Jan 2020 19:52:15 -0800 Subject: match changes in arch to have Resulty decode, instead of Option --- src/lib.rs | 46 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 7dc4872..523a8df 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,8 @@ extern crate yaxpeax_arch; use yaxpeax_arch::{Arch, Decoder, LengthedInstruction}; +use std::fmt; + #[derive(Debug)] pub enum Opcode { NOP @@ -29,24 +31,51 @@ impl LengthedInstruction for Instruction { } } +#[derive(Debug, PartialEq)] +pub enum DecodeError { + ExhaustedInput, + InvalidOpcode, + InvalidOperand, +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + DecodeError::ExhaustedInput => write!(f, "exhausted input"), + DecodeError::InvalidOpcode => write!(f, "invalid opcode"), + DecodeError::InvalidOperand => write!(f, "invalid operand"), + } + } +} + +impl yaxpeax_arch::DecodeError for DecodeError { + fn data_exhausted(&self) -> bool { self == &DecodeError::ExhaustedInput } + fn bad_opcode(&self) -> bool { self == &DecodeError::InvalidOpcode } + fn bad_operand(&self) -> bool { self == &DecodeError::InvalidOperand } +} + +impl yaxpeax_arch::Instruction for Instruction { + // TODO: this is wrong!! + fn well_defined(&self) -> bool { true } +} + #[derive(Default, Debug)] pub struct InstDecoder {} impl Decoder for InstDecoder { - fn decode>(&self, bytes: T) -> Option { + type Error = DecodeError; + + fn decode>(&self, bytes: T) -> Result { let mut blank = Instruction { opcode: Opcode::NOP }; - match self.decode_into(&mut blank, bytes) { - Some(_) => Some(blank), - None => None - } + self.decode_into(&mut blank, bytes).map(|_: ()| blank) } - fn decode_into>(&self, instr: &mut Instruction, bytes: T) -> Option<()> { + fn decode_into>(&self, instr: &mut Instruction, bytes: T) -> Result<(), Self::Error> { match bytes.into_iter().next() { Some(0x00) => { instr.opcode = Opcode::NOP; - Some(()) + Ok(()) }, - _ => None + _ => Err(DecodeError::ExhaustedInput) } } } @@ -62,6 +91,7 @@ pub struct PIC24; impl Arch for PIC24 { type Address = u32; type Instruction = Instruction; + type DecodeError = DecodeError; type Decoder = InstDecoder; type Operand = (); } -- cgit v1.1