refactor: remove ~duplicate function branch
This commit is contained in:
parent
f7fdda37f4
commit
f5eb252266
1 changed files with 9 additions and 17 deletions
26
src/main.rs
26
src/main.rs
|
@ -2,19 +2,11 @@ use std::collections::HashMap;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{self, BufRead, BufReader};
|
use std::io::{self, BufRead, BufReader};
|
||||||
|
|
||||||
fn retrieve(memory: &HashMap<String, i64>, ops: &[String]) -> i64 {
|
fn retrieve(labels: &HashMap<String, usize>, ops: &[String]) -> i64 {
|
||||||
if ops.len() >= 3 {
|
if ops.len() >= 3 {
|
||||||
*memory.get(&ops[2]).unwrap_or(&0)
|
*labels.get(&ops[2]).unwrap_or(&0) as i64
|
||||||
} else {
|
} else {
|
||||||
*memory.get(&ops[1]).unwrap_or(&0)
|
*labels.get(&ops[1]).unwrap_or(&0) as i64
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn branch(labels: &HashMap<String, usize>, ops: &[String]) -> usize {
|
|
||||||
if ops.len() >= 3 {
|
|
||||||
*labels.get(&ops[2]).unwrap_or(&0)
|
|
||||||
} else {
|
|
||||||
*labels.get(&ops[1]).unwrap_or(&0)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -39,31 +31,31 @@ fn process(
|
||||||
memory.insert(key.clone(), *accumulator);
|
memory.insert(key.clone(), *accumulator);
|
||||||
}
|
}
|
||||||
Some("LDA") => {
|
Some("LDA") => {
|
||||||
*accumulator = retrieve(memory, &ops);
|
*accumulator = retrieve(labels, &ops);
|
||||||
}
|
}
|
||||||
Some("ADD") => {
|
Some("ADD") => {
|
||||||
if let Ok(value) = ops[1].parse::<i64>() {
|
if let Ok(value) = ops[1].parse::<i64>() {
|
||||||
*accumulator += value;
|
*accumulator += value;
|
||||||
} else {
|
} else {
|
||||||
*accumulator += retrieve(memory, &ops);
|
*accumulator += retrieve(labels, &ops);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some("SUB") => {
|
Some("SUB") => {
|
||||||
if let Ok(value) = ops[1].parse::<i64>() {
|
if let Ok(value) = ops[1].parse::<i64>() {
|
||||||
*accumulator -= value;
|
*accumulator -= value;
|
||||||
} else {
|
} else {
|
||||||
*accumulator -= retrieve(memory, &ops);
|
*accumulator -= retrieve(labels, &ops);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some("BRA") => return branch(labels, &ops),
|
Some("BRA") => return retrieve(labels, &ops) as usize,
|
||||||
Some("BRP") => {
|
Some("BRP") => {
|
||||||
if *accumulator >= 0 {
|
if *accumulator >= 0 {
|
||||||
return branch(labels, &ops);
|
return retrieve(labels, &ops) as usize;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some("BRZ") => {
|
Some("BRZ") => {
|
||||||
if *accumulator == 0 {
|
if *accumulator == 0 {
|
||||||
return branch(labels, &ops);
|
return retrieve(labels, &ops) as usize;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some("HLT") => std::process::exit(0),
|
Some("HLT") => std::process::exit(0),
|
||||||
|
|
Loading…
Reference in a new issue