use crate::{Mode, Target};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ByteRegister(u8);
impl ByteRegister {
pub fn from_code(code: u8) -> Option<Self> {
if code < 16 {
Some(Self(code))
} else {
None
}
}
pub fn code(self) -> u8 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Instruction {
Nop,
Sleep,
Rts,
Rte,
AddByte {
source: ByteRegister,
destination: ByteRegister,
},
MovByte {
source: ByteRegister,
destination: ByteRegister,
},
Branch {
condition: u8,
displacement: i8,
},
BranchSubroutine {
displacement: i8,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DecodedInstruction {
pub instruction: Instruction,
pub len: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DecodeError {
UnsupportedTarget,
Truncated,
UnsupportedEncoding,
}
pub fn decode(bytes: &[u8], target: Target, mode: Mode) -> Result<DecodedInstruction, DecodeError> {
if target != Target::H8_300 || mode != Mode::Normal {
return Err(DecodeError::UnsupportedTarget);
}
let (&high, rest) = bytes.split_first().ok_or(DecodeError::Truncated)?;
let &low = rest.first().ok_or(DecodeError::Truncated)?;
let registers = || (ByteRegister(low >> 4), ByteRegister(low & 0x0f));
let instruction = match (high, low) {
(0x00, 0x00) => Instruction::Nop,
(0x01, 0x80) => Instruction::Sleep,
(0x54, 0x70) => Instruction::Rts,
(0x56, 0x70) => Instruction::Rte,
(0x08, _) => {
let (source, destination) = registers();
Instruction::AddByte {
source,
destination,
}
}
(0x0c, _) => {
let (source, destination) = registers();
Instruction::MovByte {
source,
destination,
}
}
(0x40..=0x4f, displacement) if displacement & 1 == 0 => Instruction::Branch {
condition: high & 0x0f,
displacement: displacement as i8,
},
(0x55, displacement) if displacement & 1 == 0 => Instruction::BranchSubroutine {
displacement: displacement as i8,
},
_ => return Err(DecodeError::UnsupportedEncoding),
};
Ok(DecodedInstruction {
instruction,
len: 2,
})
}