hotfix: better support for three-code lines

This commit is contained in:
Muhammad Nauman Raza 2025-01-26 09:33:41 +00:00
parent 8f0da8a7f7
commit a40eba6f8d
Signed by: devraza
GPG key ID: 91EAD6081011574B

View file

@ -2,6 +2,17 @@ use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
fn retrieve(
memory: &mut HashMap<String, i64>,
ops: Vec<String>
) -> i64 {
if ops.len() >= 3 {
return *memory.get(&ops[2]).unwrap_or(&0);
} else {
return *memory.get(&ops[1]).unwrap_or(&0);
}
}
fn process(
line: String,
accumulator: &mut i64,
@ -12,7 +23,7 @@ fn process(
let ops: Vec<String> = line.trim().split_whitespace().map(String::from).collect();
let options: Vec<&str>;
if ops.len() > 1 {
if ops.len() >= 3 {
options = vec![ops[0].as_str(), ops[1].as_str()];
} else {
options = vec![ops[0].as_str()];
@ -27,32 +38,36 @@ fn process(
}
"OUT" => println!("{}", accumulator),
"STA" => {
if ops.len() >= 3 {
memory.insert(ops[2].clone(), *accumulator);
} else {
memory.insert(ops[1].clone(), *accumulator);
}
"LDA" => {
if ops.len() > 1 {
*accumulator = *memory.get(&ops[2]).unwrap_or(&0);
} else {
*accumulator = *memory.get(&ops[1]).unwrap_or(&0);
}
"LDA" => {
*accumulator = retrieve(memory, ops.clone());
}
"ADD" => {
if let Ok(value) = ops[1].parse::<i64>() {
*accumulator += value;
} else {
*accumulator += *memory.get(&ops[1]).unwrap_or(&0);
*accumulator += retrieve(memory, ops.clone());
}
}
"SUB" => {
if let Ok(value) = ops[1].parse::<i64>() {
*accumulator -= value;
} else {
*accumulator -= *memory.get(&ops[1]).unwrap_or(&0);
*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" {