brainfuck_exe/
error.rs

1//! module containing the [`Error`] enum and corresponding [`Result`] typealias for this crate
2
3use std::{
4    fmt,
5    io::Error as IoError,
6};
7
8/// Error enum for brainfuck runtime errors
9#[derive(Debug)]
10pub enum Error {
11    /// returned when the amount of `[` in the code does not equal the amount of `]`
12    MismatchedBrackets {
13        /// the amount of `[` in the code
14        opening: usize,
15        /// the amount of `]` in the code
16        closing: usize,
17    },
18    /// propogated from opening or reading files for the brainfuck source code
19    /// to be interpreted, in [`crate::Brainfuck::from_file`]
20    FileReadError(
21        /// the propogated error
22        IoError
23    ),
24    /// propogated from `.` and `,` I/O operations
25    IoError(
26        /// the propogated error
27        IoError
28    ),
29    /// returned when the amount of instructions executed
30    /// reaches the limit of instructions to be executed that is set
31    MaxInstructionsExceeded(
32        /// the instructions limit that was set
33        usize
34    ),
35}
36
37impl From<IoError> for Error {
38    fn from(err: IoError) -> Self {
39        Self::IoError(err)
40    }
41}
42
43impl fmt::Display for Error {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str(
46            match self {
47                Self::MismatchedBrackets { opening, closing } =>
48                    format!("Mismatched brackets; there were {opening} '[' found but only {closing} ']' found"),
49                Self::FileReadError(err) =>
50                    format!("Failed to read the provided file:\n{err}"),
51                Self::IoError(err) =>
52                    format!("An I/O error occured:\n{err}"),
53                Self::MaxInstructionsExceeded(cap) =>
54                    format!("The amount of instructions executed has reached the set limit of `{cap}`"),
55            }
56            .as_str()
57        )
58    }
59}
60
61impl std::error::Error for Error {}
62
63/// result type alias for [`Error`]
64pub type Result<T, E = Error> = std::result::Result<T, E>;