1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#![cfg_attr(feature = "nightly", feature(try_from))]
#[cfg(feature = "nightly")]
use std::convert::TryFrom;
use std::fmt;
use std::io;

#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct OsError {
    code: i32,
}

#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub struct NoOsError;

impl OsError {
    /// Creates a new instance of an `OsError` from a particular OS error code.
    ///
    /// # Examples
    ///
    /// On Linux:
    ///
    /// ```
    /// # if cfg!(target_os = "linux") {
    /// use std::io;
    ///
    /// let error = os_error::OsError::new(98);
    /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
    /// # }
    /// ```
    ///
    /// On Windows:
    ///
    /// ```
    /// # if cfg!(windows) {
    /// use std::io;
    ///
    /// let error = os_error::OsError::new(10048);
    /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
    /// # }
    /// ```
    pub fn new(code: i32) -> OsError {
        OsError { code: code }
    }

    /// Returns an error representing the last OS error which occurred.
    ///
    /// This function reads the value of `errno` for the target platform (e.g.
    /// `GetLastError` on Windows) and will return a corresponding instance of
    /// `OsError` for the error code.
    ///
    /// # Examples
    ///
    /// ```
    /// use os_error::OsError;
    ///
    /// println!("last OS error: {:?}", OsError::last_os_error());
    /// ```
    pub fn last_os_error() -> OsError {
        OsError::new(io::Error::last_os_error().raw_os_error().unwrap())
    }

    /// Returns the OS error that this error represents.
    ///
    /// # Examples
    ///
    /// ```
    /// use os_error::OsError;
    ///
    /// fn main() {
    ///     // Will print "raw OS error: ...".
    ///     println!("raw OS error: {:?}", OsError::last_os_error().code());
    /// }
    /// ```
    pub fn code(&self) -> i32 {
        self.code
    }

    /// Returns the corresponding `ErrorKind` for this error.
    ///
    /// # Examples
    ///
    /// ```
    /// use os_error::OsError;
    ///
    /// fn main() {
    ///     // Will print "No inner error".
    ///     println!("{:?}", OsError::last_os_error());
    /// }
    /// ```
    pub fn kind(&self) -> io::ErrorKind {
        self.to_error().kind()
    }

    fn to_error(&self) -> io::Error {
        io::Error::from_raw_os_error(self.code)
    }
}

impl fmt::Debug for OsError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let error: io::Error = self.to_error();

        fmt.debug_struct("OsError")
            .field("code", &self.code)
            .field("kind", &error.kind())
            .finish()
    }
}

impl fmt::Display for OsError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", &self.to_error())
    }
}

#[cfg(feature = "nightly")]
impl TryFrom<io::Error> for OsError {
    type Error = NoOsError;

    fn try_from(error: io::Error) -> Result<OsError, NoOsError> {
        match error.raw_os_error() {
            Some(code) => Ok(OsError { code }),
            None => Err(NoOsError),
        }
    }
}

impl Into<io::Error> for OsError {
    fn into(self) -> io::Error {
        self.to_error()
    }
}

#[cfg(test)]
mod tests {
    use std::io;
    use super::OsError;
    #[cfg(feature = "nightly")]
    use super::NoOsError;
    #[cfg(feature = "nightly")]
    use std::convert::TryFrom;
    #[cfg(feature = "nightly")]
    use std::convert::TryInto;

    const CODE: i32 = 6;

    #[test]
    fn test_fmt_display() {
        let err = OsError::new(CODE);
        let io_error = io::Error::from_raw_os_error(CODE);

        assert_eq!(format!("{}", err), format!("{}", io_error));
    }

    #[test]
    fn test_fmt_debug() {
        let kind = io::ErrorKind::Other;
        let err = OsError::new(CODE);

        let expected = format!("OsError {{ code: {:?}, kind: {:?} }}", CODE, kind);
        assert_eq!(format!("{:?}", err), expected);
    }

    #[test]
    #[cfg(feature = "nightly")]
    fn from_io_error() {
        let os_error = OsError::try_from(io::Error::from_raw_os_error(CODE));
        assert_eq!(os_error, Ok(OsError{ code: CODE }));

        let os_error = OsError::try_from(io::Error::new(io::ErrorKind::AddrInUse, "NoOsError"));
        assert_eq!(os_error, Err(NoOsError));
    }

    #[test]
    #[cfg(feature = "nightly")]
    fn into_os_error() {
        let os_error: Result<OsError, _> = io::Error::from_raw_os_error(CODE).try_into();
        assert_eq!(os_error, Ok(OsError{ code: CODE }));

        let os_error: Result<OsError, _> =
            io::Error::new(io::ErrorKind::AddrInUse, "NoOsError").try_into();
        assert_eq!(os_error, Err(NoOsError));
    }
}