Skip to main content

rustici/
error.rs

1//! Error types for rustici.
2use std::{fmt, io, string::FromUtf8Error};
3
4/// A convenient result alias.
5pub type Result<T, E = Error> = std::result::Result<T, E>;
6
7/// Errors that may occur while encoding/decoding or doing IO.
8#[derive(Debug)]
9pub enum Error {
10    /// Underlying I/O error.
11    Io(io::Error),
12    /// Protocol violation / unexpected packet type or invalid structure.
13    Protocol(&'static str),
14    /// The remote reported an unknown command.
15    UnknownCommand(String),
16    /// Too large message/field.
17    TooLong(&'static str),
18    /// UTF-8 conversion failed (when interpreting bytes as a String).
19    Utf8(FromUtf8Error),
20    /// Operation timed out.
21    Timeout,
22}
23
24impl From<io::Error> for Error {
25    fn from(e: io::Error) -> Self {
26        Error::Io(e)
27    }
28}
29
30impl From<FromUtf8Error> for Error {
31    fn from(e: FromUtf8Error) -> Self {
32        Error::Utf8(e)
33    }
34}
35
36impl fmt::Display for Error {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Error::Io(e) => write!(f, "io error: {e}"),
40            Error::Protocol(s) => write!(f, "protocol error: {s}"),
41            Error::UnknownCommand(cmd) => write!(f, "unknown command: {cmd}"),
42            Error::TooLong(what) => write!(f, "value too long: {what}"),
43            Error::Utf8(e) => write!(f, "utf-8 error: {e}"),
44            Error::Timeout => write!(f, "operation timed out"),
45        }
46    }
47}
48
49impl std::error::Error for Error {}