1use std::error;
6use std::fmt::{self, Display};
7use std::io;
8use std::result;
9
10use libc::__errno_location;
11
12#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct Error(i32);
16pub type Result<T> = result::Result<T, Error>;
17
18impl Error {
19 pub fn new(e: i32) -> Error {
21 Error(e)
22 }
23
24 pub fn last() -> Error {
29 Error(unsafe { *__errno_location() })
30 }
31
32 pub fn errno(&self) -> i32 {
34 self.0
35 }
36}
37
38impl From<io::Error> for Error {
39 fn from(e: io::Error) -> Self {
40 Error::new(e.raw_os_error().unwrap_or_default())
41 }
42}
43
44impl error::Error for Error {
45 fn description(&self) -> &str {
46 "System returned an error code"
47 }
48}
49
50impl Display for Error {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 write!(f, "Error: {}", self.errno())
53 }
54}
55
56pub fn errno_result<T>() -> Result<T> {
58 Err(Error::last())
59}
60
61#[cfg(test)]
65pub fn set_errno(e: i32) {
66 unsafe {
67 *__errno_location() = e;
68 }
69}