burritos/src/simulator/loader.rs

65 lines
2.0 KiB
Rust
Raw Normal View History

2023-02-15 17:20:10 +01:00
use crate::Machine;
use std::fs;
use std::io;
use std::io::BufRead;
2023-03-27 18:10:11 +02:00
use std::io::Read;
2023-02-15 17:20:10 +01:00
/// Load a file into a new machine
///
/// `panic!` when size is not 1, 2, 4 or 8
/// `panic!` when the text does not represents instructions in hexadecimal
///
/// ### Parameters
///
/// - **path** the path of the file to load
/// - **size** the number of bytes to write (1, 2, 4 or 8)
2023-03-27 18:10:11 +02:00
#[deprecated]
2023-03-10 11:03:54 +01:00
pub fn _load(path : &str, instruction_size: i32) -> Machine {
2023-02-15 17:20:10 +01:00
let file = fs::File::open(path).expect("Wrong filename");
let reader = io::BufReader::new(file);
let mut machine = Machine::init_machine();
2023-02-15 17:20:10 +01:00
for (i,line) in reader.lines().enumerate() {
let res = u64::from_str_radix(&line.unwrap(), 16);
match res {
Ok(value) => {
2023-03-01 15:11:35 +01:00
Machine::write_memory(&mut machine, instruction_size, i*instruction_size as usize, value);
2023-02-15 17:20:10 +01:00
},
_ => panic!()
}
}
2023-02-15 18:09:18 +01:00
println!("{:x}", Machine::read_memory(& mut machine, 4, 0));
2023-02-15 17:20:10 +01:00
machine
2023-03-27 18:10:11 +02:00
}
/// load a 32-bits binary file into the machine
///
/// ### Parameters
///
/// - **path** path of the file to load
/// - **machine** the machine where the bin file will be loaded
/// - **start_index** at which index of machine memory you want to start to load the program
///
/// Returns in a Result any io error
pub fn load(path: &str, machine: &mut Machine, start_index: usize) -> Result<(), std::io::Error> {
let mut file = fs::File::open(path)?;
let mut instructions: Vec<u32> = Default::default();
loop {
let mut buf: [u8; 4] = [0; 4];
let res = file.read(&mut buf)?;
if res == 0 {
break; // eof
} else {
instructions.push(u32::from_le_bytes(buf));
}
}
for i in 0..instructions.len() {
machine.write_memory(4, 4 * i + start_index, instructions[i] as u64);
}
// #[cfg(debug_assertions)]
// println!("{:04x?}", instructions); // only print loaded program in debug build
2023-03-27 18:10:11 +02:00
Ok(())
2023-02-15 17:20:10 +01:00
}