Skip to content

Commit 4ab6a39

Browse files
committed
[update] better file handling
1 parent 97dd74e commit 4ab6a39

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

src/memory.rs

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ impl Chip8 {
5858
}
5959
}
6060

61-
// file and memory related management
61+
// file & memory management
6262
impl Chip8 {
6363

6464
pub fn load_font(&mut self) -> [u8; RAM_SIZE]{
@@ -70,43 +70,34 @@ impl Chip8 {
7070
}
7171

7272
pub fn load_rom(&mut self, filename: &String) {
73-
74-
let mut rom_file = File::open(filename)
75-
.expect("[err] error");
73+
const MAX_SIZE_FOR_ROM_DATA: u16 = (RAM_SIZE - 0x200) as u16;
7674

75+
let mut rom_file = File::open(filename).unwrap();
7776
self.load_font();
7877

7978
let mut rom_raw_data = Vec::new();
8079
rom_file.read_to_end(&mut rom_raw_data).unwrap();
8180

81+
if rom_raw_data.len() as u16 > MAX_SIZE_FOR_ROM_DATA {
82+
panic!("File {} is too big for be loaded into the emulator, exiting...", filename);
83+
}
84+
8285
let last_addr = 0x200 + rom_raw_data.len() as usize;
8386
self.memory[0x200..last_addr].copy_from_slice(&rom_raw_data);
8487
}
8588
}
8689

8790
// stack management
8891
impl Chip8 {
92+
93+
// note: there's no need to check for overflow and underflow
94+
// condition because it is handled in opcode's section
8995
pub fn stack_push(&mut self, value: u16) {
90-
const OVERFLOW_INDEX: usize = STACK_SIZE + 1;
91-
92-
match self.stack_pointer {
93-
OVERFLOW_INDEX => self.stack_pointer = 0,
94-
_ => {
95-
self.stack[self.stack_pointer] = value;
96-
self.stack_pointer += 1;
97-
},
98-
}
96+
self.stack[self.stack_pointer] = value;
97+
self.stack_pointer += 1;
9998
}
10099

101100
pub fn stack_pop(&mut self) -> u16 {
102-
103-
if self.stack_pointer == 0 {
104-
println!("[wrn] stack_pop() tried to pop at index 0");
105-
println!("[wrn] stack_pointer will reset to 0");
106-
107-
self.stack_pointer = 1;
108-
}
109-
110101
self.stack_pointer -= 1;
111102
self.stack[self.stack_pointer as usize]
112103
}

0 commit comments

Comments
 (0)