diff --git a/helloworld b/helloworld.obj similarity index 100% rename from helloworld rename to helloworld.obj diff --git a/src/main.rs b/src/main.rs index f057cf6..69cb6e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,7 @@ use core::panic; // use std::fs; // use std::io; // use std::io::Read; -use std::u16; +use std::{env, u16}; use mem::Memory; const PC_START: u16 = 0x300; @@ -133,28 +133,11 @@ impl VM { fn main() { - - - - - - - - - - - // let args: Vec = env::args().collect(); - // let path = args.get(1).expect("enter a file please!"); - // let file = fs::File::open(path).expect("couldnt open file"); - // let mut reader = io::BufReader::new(file); - // let mut values = Vec::new(); - // let mut buffer:[u8;2] = [0;2]; - // while reader.read_exact(&mut buffer).is_ok() { - // let instruction = u16::from_be_bytes(buffer); - // values.push(instruction); - // } - // println!("data: {:?}\n", values); - // for data in values{ - // println!("hex data: {:#06X}", data); - // } + let mut lc3 = VM::new(); + let args: Vec = env::args().collect(); + let path = args.get(1).expect("a file must be specified"); + lc3.memory.read(path.to_string()); + for addr in 0x3000..0x3007 { + println!("the instruction is {:#b} at address {:#x}", lc3.memory.data[addr], addr); + } } diff --git a/src/mem.rs b/src/mem.rs index 84e35ce..bc87a8a 100644 --- a/src/mem.rs +++ b/src/mem.rs @@ -1,9 +1,11 @@ #![allow(dead_code)] +use std::{fs, io::{self, Read}}; + pub const MEM_SIZE: usize = u16::MAX as usize; pub struct Memory { - data: [u16; MEM_SIZE], + pub data: [u16; MEM_SIZE], } impl Memory { @@ -19,4 +21,30 @@ impl Memory { pub fn get(&mut self, addr: u16) { self.data[addr as usize]; } + + pub fn read(&mut self, path: String) { + // don't need byteorder crate!! + let file = fs::File::open(path).expect("could not open file"); + let mut reader = io::BufReader::new(file); + let mut buffer: [u8;2] = [0, 2]; + let _ = reader.read_exact(&mut buffer).expect("could not read file"); + let base_addr = u16::from_be_bytes(buffer); + let mut addr = base_addr; + loop { + match reader.read_exact(&mut buffer) { + Ok(()) => { + let instruction = u16::from_be_bytes(buffer); + self.set(addr, instruction as u16); + addr += 1; + } + Err(e) => { + if e.kind() == std::io::ErrorKind::UnexpectedEof { + break; + } else { + panic!("could not read instruction {:?}", e); + } + } + } + } + } }