use crate::Machine; use std::fs; use std::io; use std::io::BufRead; use std::io::Read; /// 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) #[deprecated] pub fn _load(path : &str, instruction_size: i32) -> Machine { let file = fs::File::open(path).expect("Wrong filename"); let reader = io::BufReader::new(file); let mut machine = Machine::init_machine(); for (i,line) in reader.lines().enumerate() { let res = u64::from_str_radix(&line.unwrap(), 16); match res { Ok(value) => { Machine::write_memory(&mut machine, instruction_size, i*instruction_size as usize, value); }, _ => panic!() } } println!("{:x}", Machine::read_memory(& mut machine, 4, 0)); machine } /// 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 = 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 Ok(()) }