Skip to content

Commit

Permalink
do-core1: Move Instruction to the do-core crate
Browse files Browse the repository at this point in the history
Signed-off-by: Samuel Ortiz <[email protected]>
  • Loading branch information
Samuel Ortiz authored and Samuel Ortiz committed Feb 26, 2022
1 parent 1426e9b commit 89e27af
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 37 deletions.
33 changes: 32 additions & 1 deletion do-core/src/instruction.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::Error;
use crate::{Error, MAX_REGISTER_INDEX};

#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq)]
Expand All @@ -20,3 +20,34 @@ impl OpCode {
}
}
}

#[derive(Debug)]
pub struct Instruction {
opcode: OpCode,
op0: u8,
op1: u8,
}

impl Instruction {
// Instruction constructor, a.k.a. disassembler.
pub fn disassemble(insn: u32) -> Result<Instruction, Error> {
// Keep the first 6 bits only
let opcode = OpCode::from_u8((insn & 0x3f) as u8)?;

// Shift right by 6, keep only the first 5 bits.
let op0 = ((insn >> 6) & 0x1f) as u8;

// Shift right by 11, keep only the first 5 bits.
let op1: u8 = ((insn >> 11) & 0x1f) as u8;

if op0 > MAX_REGISTER_INDEX {
return Err(Error::Op0OutOfRange);
}

if op1 > MAX_REGISTER_INDEX {
return Err(Error::Op1OutOfRange);
}

Ok(Instruction { opcode, op0, op1 })
}
}
3 changes: 3 additions & 0 deletions do-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ pub enum Error {
AdditionOverflow(u32, u32),
}

// do-core1 register indexes range from 0 to 31.
pub const MAX_REGISTER_INDEX: u8 = 31;

pub mod instruction;
38 changes: 2 additions & 36 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use clap::Parser;
use do_core::instruction::OpCode;
use do_core::Error;
use do_core::instruction::{Instruction, OpCode};
use do_core::{Error, MAX_REGISTER_INDEX};

#[derive(Parser)]
#[clap(version, author)]
Expand All @@ -10,40 +10,6 @@ struct DoCoreOpts {
insn: String,
}

#[derive(Debug)]
struct Instruction {
opcode: OpCode,
op0: u8,
op1: u8,
}

// do-core1 register indexes range from 0 to 31.
const MAX_REGISTER_INDEX: u8 = 31;

impl Instruction {
// Instruction constructor, a.k.a. disassembler.
fn disassemble(insn: u32) -> Result<Instruction, Error> {
// Keep the first 6 bits only
let opcode = OpCode::from_u8((insn & 0x3f) as u8)?;

// Shift right by 6, keep only the first 5 bits.
let op0 = ((insn >> 6) & 0x1f) as u8;

// Shift right by 11, keep only the first 5 bits.
let op1: u8 = ((insn >> 11) & 0x1f) as u8;

if op0 > MAX_REGISTER_INDEX {
return Err(Error::Op0OutOfRange);
}

if op1 > MAX_REGISTER_INDEX {
return Err(Error::Op1OutOfRange);
}

Ok(Instruction { opcode, op0, op1 })
}
}

fn add(op0: u32, op1: u32) -> Result<u32, Error> {
op0.checked_add(op1)
.ok_or(Error::AdditionOverflow(op0, op1))
Expand Down

0 comments on commit 89e27af

Please sign in to comment.