sandwich/src/main.rs

68 lines
1.6 KiB
Rust
Raw Normal View History

2021-02-03 21:19:11 +00:00
use std::fs;
use std::env;
2021-02-03 21:48:11 +00:00
use std::fmt;
2021-02-03 21:54:13 +00:00
use std::usize;
2021-02-03 21:48:11 +00:00
struct Program {
data: Vec<String>,
2021-02-03 21:54:13 +00:00
pc: usize
2021-02-03 21:48:11 +00:00
}
impl Program {
fn from_string(program: String) -> Program {
let mut op_list: Vec<String> = Vec::new();
for opcode in program.split(" ").collect::<Vec<&str>>() {
let mut new_op = opcode.to_owned();
new_op = new_op.replace("\n", "");
if new_op.len() != 0 {
op_list.push(new_op.to_owned());
}
}
return Program{ data: op_list, pc: 0 };
}
2021-02-04 17:45:53 +00:00
fn eval(&self, instruction: &String) {
let instruction_vec: Vec<char> = instruction.chars().collect();
let opcode = instruction_vec[0];
let arguments = &instruction[1..];
match opcode {
'p' => println!("{}", arguments),
_ => panic!("SyntaxError at opcode {}!", self.pc)
}
}
2021-02-03 21:54:13 +00:00
fn run(&mut self) {
2021-02-03 21:48:11 +00:00
println!("{}", self);
2021-02-03 21:54:13 +00:00
while self.pc < self.data.len() {
2021-02-03 22:04:58 +00:00
let instruction = &self.data[self.pc];
2021-02-03 21:54:13 +00:00
2021-02-04 17:45:53 +00:00
self.eval(instruction);
2021-02-03 21:54:13 +00:00
self.pc = self.pc + 1;
}
2021-02-03 21:48:11 +00:00
}
}
impl fmt::Display for Program {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Program ({:?})", self.data)
}
}
2021-02-03 21:19:11 +00:00
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
panic!("You must provide an argument!");
}
let filename = &args[1];
2021-02-03 21:48:11 +00:00
2021-02-03 21:19:11 +00:00
let contents = fs::read_to_string(filename).expect("Something went wrong reading the file");
2021-02-03 21:54:13 +00:00
let mut prog = Program::from_string(contents);
2021-02-03 21:48:11 +00:00
prog.run();
2021-02-03 21:19:11 +00:00
}