Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 19, 2023 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/21b59503624daa7aa435962eba2f920b to your computer and use it in GitHub Desktop.
Save rust-play/21b59503624daa7aa435962eba2f920b to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
pub struct Cpu {
pub memory: Vec<u8>,
pub v: Vec<u8>,
pub i: u16,
pub dt: u8,
pub st: u8,
pub pc: u16,
pub sp: u8,
pub stack: Vec<u16>,
}
// impl Default and a bunch of methods omitted...
enum Instruction {
CLS,
RET,
JMP(u16),
CALL(u16),
SE(u16),
SNE(u16),
// etc, etc...
}
#[derive(Debug)]
enum DecodeError {
OpcodeNotRecognized(u16),
}
// impl Error and fmt::Display omitted...
impl Instruction {
pub fn decode(cpu: &Cpu) -> Result<Instruction, DecodeError> {
let first_byte: u16 = cpu.memory[usize::from(cpu.pc)].into();
let second_byte: u16 = cpu.memory[usize::from(cpu.pc + 0x01)].into();
let opcode: u16 = first_byte << 8 | second_byte;
match opcode & 0xF000 {
0x0000 => match opcode & 0x000F {
0x0000 => Ok(Instruction::CLS),
0x000E => Ok(Instruction::RET),
_ => Err(DecodeError::OpcodeNotRecognized(opcode)),
},
// bunch of other opcode/instruction matches here...
_ => Err(Decode::Error::OpcodeNotRecognized(opcode)),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment