From 1c6fa97eae3cbdee46c0878737d951f50061a316 Mon Sep 17 00:00:00 2001 From: Marco Thomas Date: Tue, 22 Apr 2025 10:49:38 +0900 Subject: [PATCH] ft: add error type instead of plain panic --- src/interpret.rs | 21 +++++++++++++++------ src/main.rs | 5 ++++- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/interpret.rs b/src/interpret.rs index 54acefd..743baec 100644 --- a/src/interpret.rs +++ b/src/interpret.rs @@ -1,6 +1,13 @@ use std::io::{self, Read}; -pub fn interpret(code: &str) -> Vec { +#[derive(Debug)] +pub enum BrainFuckError { + BracketMissing, + UserInput, + EmptyStack, +} + +pub fn interpret(code: &str) -> Result, BrainFuckError> { let mut memory = [0 as u8; 10_000]; let mut head = 0 as usize; let mut pc = 0 as usize; @@ -25,6 +32,8 @@ pub fn interpret(code: &str) -> Vec { let mut input_buf = [0u8; 1]; if io::stdin().read_exact(&mut input_buf).is_ok() { memory[head] = input_buf[0]; + } else { + return Err(BrainFuckError::UserInput); } log::debug!("Read user input: {}", input_buf[0]); } @@ -37,7 +46,7 @@ pub fn interpret(code: &str) -> Vec { while count_brackets > 0 { pc += 1; if pc >= code_bytes.len() { - panic!("Missing closing loop!"); + return Err(BrainFuckError::BracketMissing); } match code_bytes[pc] as char { // closing current loop @@ -62,7 +71,7 @@ pub fn interpret(code: &str) -> Vec { if let Some(start_pc) = loop_stack.last() { pc = *start_pc; } else { - panic!("Loop stack empty, but still called!") + return Err(BrainFuckError::EmptyStack); } // loop done, continue normally } else { @@ -76,7 +85,7 @@ pub fn interpret(code: &str) -> Vec { pc += 1; } print!("\n"); - return out; + Ok(out) } #[cfg(test)] @@ -86,14 +95,14 @@ mod tests { #[test] fn test_h() { let code = "+++++++++[>++++++++<-]>."; - let out = interpret(code); + let out = interpret(code).unwrap(); assert_eq!(std::str::from_utf8(&out).unwrap(), "H"); } #[test] fn test_hello() { let code = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; - let out = interpret(code); + let out = interpret(code).unwrap(); assert_eq!(std::str::from_utf8(&out).unwrap(), "Hello World!\n"); } } diff --git a/src/main.rs b/src/main.rs index ec41f64..62b3205 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,5 +18,8 @@ fn main() { }); println!("Running file {} with program {}", filename, code); - interpret(&code); + match interpret(&code) { + Ok(_) => {} + Err(err) => panic!("{:?}", err), + } }