diff --git a/src/main.rs b/src/main.rs index 53f7c14..4ebb377 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,10 +2,7 @@ use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; -fn retrieve( - memory: &mut HashMap, - ops: Vec -) -> i64 { +fn retrieve(memory: &mut HashMap, ops: Vec) -> i64 { if ops.len() >= 3 { return *memory.get(&ops[2]).unwrap_or(&0); } else { @@ -28,57 +25,57 @@ fn process( } else { options = vec![ops[0].as_str()]; } - + for op in options { - match op { - "INP" => { - let mut s = String::new(); - io::stdin().read_line(&mut s).unwrap(); - *accumulator = s.trim().parse::().unwrap(); - } - "OUT" => println!("{}", accumulator), - "STA" => { - if ops.len() >= 3 { - memory.insert(ops[2].clone(), *accumulator); - } else { - memory.insert(ops[1].clone(), *accumulator); + match op { + "INP" => { + let mut s = String::new(); + io::stdin().read_line(&mut s).unwrap(); + *accumulator = s.trim().parse::().unwrap(); } - } - "LDA" => { - *accumulator = retrieve(memory, ops.clone()); - } - "ADD" => { - if let Ok(value) = ops[1].parse::() { - *accumulator += value; - } else { - *accumulator += retrieve(memory, ops.clone()); + "OUT" => println!("{}", accumulator), + "STA" => { + if ops.len() >= 3 { + memory.insert(ops[2].clone(), *accumulator); + } else { + memory.insert(ops[1].clone(), *accumulator); + } } - } - "SUB" => { - if let Ok(value) = ops[1].parse::() { - *accumulator -= value; - } else { - *accumulator -= retrieve(memory, ops.clone()); + "LDA" => { + *accumulator = retrieve(memory, ops.clone()); } - } - "BRA" => { - if ops.len() >= 3 { - *pc = *labels.get(&ops[2]).unwrap(); - } else { - *pc = *labels.get(&ops[1]).unwrap(); + "ADD" => { + if let Ok(value) = ops[1].parse::() { + *accumulator += value; + } else { + *accumulator += retrieve(memory, ops.clone()); + } } - } - "HLT" => std::process::exit(0), - _ => { - if ops.len() > 1 && ops[1] == "DAT" { - memory.insert( - ops[0].clone(), - ops.get(2).and_then(|s| s.parse::().ok()).unwrap_or(0), - ); + "SUB" => { + if let Ok(value) = ops[1].parse::() { + *accumulator -= value; + } else { + *accumulator -= retrieve(memory, ops.clone()); + } + } + "BRA" => { + if ops.len() >= 3 { + *pc = *labels.get(&ops[2]).unwrap(); + } else { + *pc = *labels.get(&ops[1]).unwrap(); + } + } + "HLT" => std::process::exit(0), + _ => { + if ops.len() > 1 && ops[1] == "DAT" { + memory.insert( + ops[0].clone(), + ops.get(2).and_then(|s| s.parse::().ok()).unwrap_or(0), + ); + } } } } -} return 0; } @@ -108,7 +105,13 @@ fn main() -> io::Result<()> { let mut pc: usize = 0; while pc < code.len() { let line = &code[pc]; - let next_pc = process(line.to_string(), &mut accumulator, &mut memory, &labels, &mut pc); + let next_pc = process( + line.to_string(), + &mut accumulator, + &mut memory, + &labels, + &mut pc, + ); if next_pc != 0 { pc = next_pc; } else {