zero_formatter/
error.rs

1use std::io;
2use std::string::FromUtf8Error;
3use std::fmt;
4use std::error::Error;
5
6pub type ZeroFormatterResult<T> = Result<T, ZeroFormatterError>;
7
8#[derive(Debug)]
9pub enum ZeroFormatterError {
10    IoError(io::Error),
11    FromUtf8Error(FromUtf8Error),
12    InvalidBinary(u64)
13}
14
15impl ZeroFormatterError {
16    pub fn invalid_binary<T>(offset: u64) -> ZeroFormatterResult<T> {
17        Err(ZeroFormatterError::InvalidBinary(offset))
18    }
19}
20
21impl fmt::Display for ZeroFormatterError {
22    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
23        match *self {
24            ZeroFormatterError::IoError(_) | ZeroFormatterError::FromUtf8Error(_) => fmt::Debug::fmt(self, f),
25            ZeroFormatterError::InvalidBinary(ref offset) =>
26                write!(f, "[offset {}] Binary does not valid.", *offset)
27        }
28    }
29}
30
31impl Error for ZeroFormatterError {
32    fn description(&self) -> &str {
33        match self {
34            &ZeroFormatterError::IoError(ref e) => e.description(),
35            &ZeroFormatterError::FromUtf8Error(ref e) => e.description(),
36            &ZeroFormatterError::InvalidBinary(_) => "Binary does not valid."
37        }
38    }
39
40    fn cause(&self) -> Option<&Error> {
41        match self {
42            &ZeroFormatterError::IoError(ref e) => Some(e),
43            &ZeroFormatterError::FromUtf8Error(ref e) => Some(e),
44            &ZeroFormatterError::InvalidBinary(_) => None
45        }
46    }
47}
48
49impl From<io::Error> for ZeroFormatterError {
50    fn from(err: io::Error) -> Self {
51        ZeroFormatterError::IoError(err)
52    }
53}
54
55impl From<FromUtf8Error> for ZeroFormatterError {
56    fn from(err: FromUtf8Error) -> Self {
57        ZeroFormatterError::FromUtf8Error(err)
58    }
59}
60
61impl From<ZeroFormatterError> for io::Error {
62    fn from(err: ZeroFormatterError) -> Self {
63        match err {
64            ZeroFormatterError::IoError(e) => e,
65            e @ ZeroFormatterError::FromUtf8Error(_) => io::Error::new(io::ErrorKind::InvalidData, e),
66            e @ ZeroFormatterError::InvalidBinary(_) => io::Error::new(io::ErrorKind::InvalidData, e)
67        }
68    }
69}