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
//! 包装OS的错误码, 统一错误码的查询和获取接口
//! 1. fn errno() -> i32;
//! 2. fn set_errno(i32);
//! 3. unsafe fn errmsg(i32) -> &str;
//!
//! 封装i32为Error
//!
//! # Example
//! ```rust
//! use hierr::*;
//!
//! set_errno(100);
//! let err = Error::last_error();
//! assert_eq!(err, 100.into());
//! ```

#![no_std]

use core::fmt;
use core::slice;
use core::str;

#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Error {
    pub errno: i32,
}

impl Error {
    pub const fn new(errno: i32) -> Self {
        Self { errno }
    }
    pub fn last_error() -> Self {
        Self { errno: errno() }
    }
}

impl Default for Error {
    fn default() -> Self {
        Error::new(-1)
    }
}

impl From<i32> for Error {
    fn from(i32: i32) -> Self {
        Self::new(i32)
    }
}

impl From<Error> for Result<(), Error> {
    fn from(err: Error) -> Self {
        if err.errno == 0 {
            Ok(())
        } else {
            Err(err)
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{}, {}", self.errno, unsafe { errmsg(self.errno) })
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{}, {}", self.errno, unsafe { errmsg(self.errno) })
    }
}

cfg_if::cfg_if! {
    if #[cfg(unix)] {
        #[link(name = "c")]
        extern "C" {
            #[cfg(any(
                target_os = "linux",
                target_os = "redox",
                target_os = "dragonfly",
                target_os = "fuchsia"
            ))]
            #[link_name = "__errno_location"]
            fn errno_location() -> *mut i32;

            #[cfg(any(target_os = "android", target_os = "netbsd", target_os = "openbsd"))]
            #[link_name = "__errno"]
            fn errno_location() -> *mut i32;

            #[cfg(any(target_os = "ios", target_os = "macos", target_os = "freebsd"))]
            #[link_name = "__error"]
            fn errno_location() -> *mut i32;

            #[cfg(any(target_os = "illumos", target_os = "solaris"))]
            #[link_name = "___errno"]
            fn errno_location() -> *mut i32;

            #[cfg(any(target_os = "haiku"))]
            #[link_name = "_errnop"]
            fn errno_location() -> *mut i32;

            fn strerror(errno: i32) -> *const u8;
            fn strlen(s: *const u8) -> usize;
        }

        pub fn errno() -> i32 {
            // # Safety
            // errno_location总是返回有效地址
            unsafe { *errno_location() }
        }

        pub fn set_errno(errno: i32) {
            // # Safety
            // errno_location总是返回有效地址
            unsafe { *errno_location() = errno };
        }

        /// # Safety
        /// strerror不支持重入, 其内容可能被后续调用修改
        pub unsafe fn errmsg<'a>(errno: i32) -> &'a str {
            let s = strerror(errno);
            let len = strlen(s);
            str::from_utf8_unchecked(slice::from_raw_parts(s, len))
        }

    } else if #[cfg(windows)] {
        pub fn errmsg<'a>(errno: i32) -> &'a str {
            "unknown"
        }

        #[link(name = "Kernel32")]
        extern "C" {
            #[link_name = "GetLastError"]
            pub fn errno() -> i32;
            #[link_name = "SetLastError"]
            pub fn set_errno(errno: i32);
        }
    }
}

pub mod prelude {
    pub const EPERM: i32 = 1;
    pub const ENOENT: i32 = 2;
    pub const EAGAIN: i32 = 11;
    pub const ENOMEM: i32 = 12;
    pub const EEXIST: i32 = 17;
    pub const EINVAL: i32 = 22;
    pub const ERANGE: i32 = 34;
    pub const ETIMEDOUT: i32 = 110;
    pub const ECANCELED: i32 = 125;
}