Skip to main content

satx_core/
error.rs

1//! The error type of `satx-core`.
2
3/// Everything that can go wrong talking to a calculator.
4#[derive(Debug, thiserror::Error)]
5pub enum Error {
6    /// The link failed.
7    #[error("I/O error: {0}")]
8    Io(#[from] std::io::Error),
9    /// The serial port could not be opened or configured. The variant
10    /// exists in every build so that `native` stays additive (a match on
11    /// [`Error`] compiles with and without it); only `native` makes one.
12    #[error("serial port: {0}")]
13    Serial(#[source] SerialError),
14    /// The link address is not `tcp://host:port`, `saturnus://[MODEL@]ROM`
15    /// or a device path.
16    #[error(
17        "bad address {0:?}: expected a serial device path, tcp://host:port or saturnus://[MODEL@]ROM-PATH"
18    )]
19    Address(String),
20    /// The in-process emulator could not be started (missing ROM, wrong
21    /// size, no `saturnus` feature).
22    #[error("emulator: {0}")]
23    Emulator(String),
24    /// A host command got no reply in time. A `C` packet is sent only once
25    /// (resent, it would run again), so the command may still be running
26    /// on the calculator or may have run; the next connection resyncs
27    /// ([`Calculator::sync`](crate::Calculator::sync)).
28    #[error(
29        "no reply to host command {command:?}: it may still be running or may have run; the next connection resyncs"
30    )]
31    NoReply {
32        /// The command as given.
33        command: String,
34    },
35    /// The calculator sent a Kermit E packet (text translated from the HP
36    /// character set), e.g. `Undefined Name` for a GET of a missing variable.
37    #[error("calculator: {0}")]
38    Remote(String),
39    /// A Kermit failure other than an E packet: retries exhausted, protocol
40    /// violation, cancelled.
41    #[error("kermit: {0}")]
42    Kermit(kermit_proto::Error),
43    /// A Kermit transaction made no progress (no new packet accepted) for
44    /// longer than its retries take, while the peer kept the link busy
45    /// (a packet replayed over and over, noise): it was cancelled. The
46    /// duration is the limit that ran out.
47    #[error(
48        "kermit: no progress for {:.1} s (the line kept sending, but no new packet came); the transfer was cancelled",
49        .0.as_secs_f64()
50    )]
51    Stalled(crate::time::Duration),
52    /// An XModem transfer failed: no start within the start window, retries
53    /// exhausted, or cancelled by the calculator (two CANs).
54    #[error("xmodem: {0}")]
55    Xmodem(xmodem_proto::Error),
56    /// The calculator cannot do what was asked, e.g. XModem on a 48S/SX.
57    #[error("unsupported: {0}")]
58    Unsupported(String),
59    /// A host command ran but the calculator reported an error. `stack` is
60    /// what the calculator returned with it, level 1 first.
61    #[error("calculator error: {message}")]
62    Calculator {
63        /// The text after `Error: `, e.g. `Undefined Name`.
64        message: String,
65        /// Stack levels after the error, level 1 first.
66        stack: Vec<String>,
67    },
68    /// A host command does not fit in one Kermit C packet.
69    #[error(
70        "host command too long: {len} encoded bytes, at most {max} fit in one packet: {command}"
71    )]
72    CommandTooLong {
73        /// The command as given.
74        command: String,
75        /// Its encoded length.
76        len: usize,
77        /// The largest encoded length that fits.
78        max: usize,
79    },
80    /// A character has no code in the HP character set.
81    #[error("{0:?} has no code in the HP character set")]
82    Charset(char),
83    /// Not a valid calculator variable name.
84    #[error("invalid variable name {0:?}")]
85    Name(String),
86    /// A file or folder name whose `%XX` codes do not read back as UTF-8,
87    /// so it names no variable or directory ([`names`](crate::names)).
88    #[error("file name {0:?}: its %XX codes are not UTF-8")]
89    FileName(String),
90    /// A Filer job on an HP 100LX/200LX failed: the server refused a
91    /// request (a file-system code with its meaning), the name exists, or
92    /// the link broke ([`filer_proto::JobError`]).
93    #[error("palmtop: {0}")]
94    Filer(filer_proto::JobError),
95    /// The calculator's reply could not be understood.
96    #[error("unexpected reply: {0}")]
97    Reply(String),
98    /// A file is not a usable HP object.
99    #[error("bad object: {0}")]
100    Object(String),
101}
102
103/// `Result` with [`Error`].
104pub type Result<T> = std::result::Result<T, Error>;
105
106/// The serial port's error inside [`Error::Serial`]: a `serialport::Error`
107/// with the `native` feature; without it no value exists.
108#[derive(Debug)]
109pub struct SerialError {
110    #[cfg(feature = "native")]
111    inner: serialport::Error,
112    #[cfg(not(feature = "native"))]
113    never: std::convert::Infallible,
114}
115
116#[cfg(feature = "native")]
117impl SerialError {
118    /// The `serialport` error.
119    pub fn inner(&self) -> &serialport::Error {
120        &self.inner
121    }
122}
123
124impl std::fmt::Display for SerialError {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        #[cfg(feature = "native")]
127        return self.inner.fmt(f);
128        #[cfg(not(feature = "native"))]
129        {
130            let _ = f;
131            match self.never {}
132        }
133    }
134}
135
136impl std::error::Error for SerialError {}
137
138#[cfg(feature = "native")]
139impl From<serialport::Error> for Error {
140    fn from(inner: serialport::Error) -> Self {
141        Error::Serial(SerialError { inner })
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    /// `Error::Serial` exists with and without `native` (CI's clippy builds
150    /// the tests without default features), so a match stays exhaustive
151    /// whichever crate in the graph turns `native` on.
152    #[test]
153    fn the_serial_variant_exists_in_every_build() {
154        let e = Error::Address("x".into());
155        assert!(!matches!(e, Error::Serial(_)));
156    }
157
158    /// The text of a serial error is as before: the port's message after
159    /// `serial port: `.
160    #[cfg(feature = "native")]
161    #[test]
162    fn a_serialport_error_converts() {
163        let e = Error::from(serialport::Error::new(
164            serialport::ErrorKind::NoDevice,
165            "no such port",
166        ));
167        assert_eq!(e.to_string(), "serial port: no such port");
168        assert!(
169            matches!(&e, Error::Serial(s) if s.inner().kind() == serialport::ErrorKind::NoDevice)
170        );
171    }
172}