Skip to main content

saturnus_host/
error.rs

1//! The one error type of this crate's operations. Every front end shows it
2//! to the user as it is ([`std::fmt::Display`]); a host that must react
3//! to a halted CPU matches [`Error::Halted`] instead of reading the text,
4//! and one that waits for the ROM to set up its memory matches
5//! [`Error::Objects`] ([`saturnus_objects::Error::is_not_set_up`]).
6
7use saturnus_core::Halt;
8
9/// What went wrong.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub enum Error {
12    /// The CPU met an undefined opcode and stopped; it runs again after a
13    /// reset or a state load.
14    Halted(Halt),
15    /// The core refused a request: a ROM of the wrong size, an unusable
16    /// saved state, a key the model lacks, an unknown model name.
17    Machine(saturnus_core::Error),
18    /// Reading user memory, the command line or an object failed: a model
19    /// without a memory view, memory the ROM has not set up, an object
20    /// that does not decode or encode. Shown with its whole chain
21    /// (`stack level 1: object truncated at nibble 5`).
22    Objects(saturnus_objects::Error),
23    /// Anything else (an unknown key or verb, text the model cannot type),
24    /// as a message for the user.
25    Message(String),
26}
27
28/// This crate's result type.
29pub type Result<T, E = Error> = std::result::Result<T, E>;
30
31impl std::fmt::Display for Error {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            Error::Halted(h) => write!(f, "CPU halted: {h}"),
35            Error::Machine(e) => e.fmt(f),
36            Error::Objects(e) => write!(f, "{e:#}"),
37            Error::Message(m) => f.write_str(m),
38        }
39    }
40}
41
42impl std::error::Error for Error {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        match self {
45            Error::Machine(e) => Some(e),
46            // The text already holds the objects error's chain.
47            Error::Halted(_) | Error::Objects(_) | Error::Message(_) => None,
48        }
49    }
50}
51
52impl From<Halt> for Error {
53    fn from(h: Halt) -> Self {
54        Self::Halted(h)
55    }
56}
57
58impl From<saturnus_core::Error> for Error {
59    fn from(e: saturnus_core::Error) -> Self {
60        Self::Machine(e)
61    }
62}
63
64impl From<saturnus_objects::Error> for Error {
65    fn from(e: saturnus_objects::Error) -> Self {
66        Self::Objects(e)
67    }
68}
69
70impl From<saturnus_objects::DecodeError> for Error {
71    fn from(e: saturnus_objects::DecodeError) -> Self {
72        Self::Objects(e.into())
73    }
74}
75
76impl From<String> for Error {
77    fn from(message: String) -> Self {
78        Self::Message(message)
79    }
80}
81
82impl From<&str> for Error {
83    fn from(message: &str) -> Self {
84        Self::Message(message.to_string())
85    }
86}