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
use std::ffi::CStr;
use std::fmt;
use std::str;
use libc::{self, c_char, c_int};
#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Debug)]
pub struct Errno(pub c_int);
impl fmt::Display for Errno {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut buf = [0 as c_char; 1024];
unsafe {
if strerror_r(self.0, buf.as_mut_ptr(), buf.len() as libc::size_t) < 0 {
let Errno(fm_err) = errno();
if fm_err != libc::ERANGE {
return write!(fmt,
"OS Error {} (strerror_r returned error {})",
self.0, fm_err);
}
}
}
let c_str = unsafe { CStr::from_ptr(buf.as_ptr()) };
fmt.write_str(str::from_utf8(c_str.to_bytes()).unwrap())
}
}
pub fn errno() -> Errno {
unsafe {
Errno(*errno_location())
}
}
pub fn set_errno(Errno(errno): Errno) {
unsafe {
*errno_location() = errno;
}
}
extern {
#[cfg_attr(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"),
link_name = "__error")]
#[cfg_attr(target_os = "dragonfly",
link_name = "__dfly_error")]
#[cfg_attr(any(target_os = "openbsd", target_os = "bitrig", target_os = "android"),
link_name = "__errno")]
#[cfg_attr(target_os = "linux",
link_name = "__errno_location")]
fn errno_location() -> *mut c_int;
#[cfg_attr(target_os = "linux", link_name = "__xpg_strerror_r")]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}