You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.0 KiB
43 lines
1.0 KiB
use clap::Parser;
|
|
use std::{error::Error, fs::File, io::Read, path::PathBuf};
|
|
use toy_cpu_4bit::cpu::Cpu;
|
|
|
|
/// ToyCPU-4bit Virtual Machine
|
|
#[derive(Parser)]
|
|
#[clap(version, about, long_about = None)]
|
|
struct Args {
|
|
/// Visualize every CPU tick
|
|
#[clap(short, long)]
|
|
trace: bool,
|
|
/// Path to 256-byte file with code for CPU
|
|
code: PathBuf,
|
|
}
|
|
|
|
fn read_code(path: PathBuf) -> Result<[u8; 256], Box<dyn Error>> {
|
|
let mut file = File::open(path)?;
|
|
match file.metadata()?.len() {
|
|
x if x != 256 => {
|
|
Err(format!("Wrong code file size, expected: 256, provided: {}", x).into())
|
|
}
|
|
_ => {
|
|
let mut buf = [0u8; 256];
|
|
file.read_exact(&mut buf)?;
|
|
Ok(buf)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let args = Args::parse();
|
|
let code = read_code(args.code)?;
|
|
let mut cpu = Cpu::new(&code);
|
|
loop {
|
|
if cpu.step() {
|
|
break;
|
|
}
|
|
if args.trace {
|
|
cpu.visualize();
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|