sawp_file/
error.rs

1use crate::Version;
2
3pub type Result<T> = std::result::Result<T, Error>;
4
5#[derive(Debug)]
6pub enum ErrorKind {
7    IOError(std::io::Error),
8    Serialization(String),
9    // Failed to parse version string to integer.
10    VersionParse,
11    // Version did not match during deserialization (expected, actual).
12    VersionMismatch((Version, Version)),
13}
14#[derive(Debug)]
15pub struct Error {
16    kind: ErrorKind,
17}
18
19impl Error {
20    pub fn new(kind: ErrorKind) -> Self {
21        Self { kind }
22    }
23}
24
25impl std::fmt::Display for Error {
26    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
27        match &self.kind {
28            ErrorKind::IOError(err) => write!(fmt, "io error: {}", err),
29            ErrorKind::Serialization(err) => write!(fmt, "serialization error: {}", err),
30            ErrorKind::VersionParse => write!(fmt, "failed to parse version"),
31            ErrorKind::VersionMismatch((expected, actual)) => {
32                write!(fmt, "expected version {} got {}", expected, actual)
33            }
34        }
35    }
36}
37
38impl std::error::Error for Error {}
39
40impl From<std::io::Error> for Error {
41    fn from(other: std::io::Error) -> Self {
42        Self::new(ErrorKind::IOError(other))
43    }
44}
45
46impl std::convert::From<rmps::encode::Error> for Error {
47    fn from(other: rmps::encode::Error) -> Self {
48        Error::new(ErrorKind::Serialization(other.to_string()))
49    }
50}
51
52impl std::convert::From<rmps::decode::Error> for Error {
53    fn from(other: rmps::decode::Error) -> Self {
54        Error::new(ErrorKind::Serialization(other.to_string()))
55    }
56}