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
use std::error::Error as StdError;
use std::ffi::CStr;
use std::fmt;
use std::result::Result as StdResult;
use libc::{c_int};
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub struct Error {
repr: Repr,
message: String,
}
#[derive(Debug)]
enum Repr {
LibRaw(c_int),
Os(i32),
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> StdResult<(), fmt::Error> {
fmt.write_str(&self.message)
}
}
impl StdError for Error {
fn description(&self) -> &str {
&self.message
}
}
#[doc(hidden)]
pub fn from_libraw(error: c_int) -> Error {
let message = String::from_utf8_lossy(unsafe {
CStr::from_ptr(::libraw::libraw_strerror(error))
}.to_bytes()).into_owned();
Error {
repr: Repr::LibRaw(error),
message: message,
}
}
#[doc(hidden)]
pub fn from_raw_os_error(errno: i32) -> Error {
Error {
repr: Repr::Os(errno),
message: os::error_string(errno),
}
}
pub mod os {
use std::ffi::CStr;
use std::str;
use libc::{c_char,c_int,size_t};
const TMPBUF_SZ: usize = 128;
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "freebsd"))]
unsafe fn errno_location() -> *mut c_int {
extern { fn __error() -> *mut c_int; }
__error()
}
#[cfg(target_os = "bitrig")]
fn errno_location() -> *mut c_int {
extern {
fn __errno() -> *mut c_int;
}
unsafe {
__errno()
}
}
#[cfg(target_os = "dragonfly")]
unsafe fn errno_location() -> *mut c_int {
extern { fn __dfly_error() -> *mut c_int; }
__dfly_error()
}
#[cfg(target_os = "openbsd")]
unsafe fn errno_location() -> *mut c_int {
extern { fn __errno() -> *mut c_int; }
__errno()
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe fn errno_location() -> *mut c_int {
extern { fn __errno_location() -> *mut c_int; }
__errno_location()
}
pub fn errno() -> i32 {
unsafe {
(*errno_location()) as i32
}
}
pub fn clear_errno() {
unsafe {
(*errno_location()) = 0;
}
}
pub fn error_string(errno: i32) -> String {
#[cfg(target_os = "linux")]
extern {
#[link_name = "__xpg_strerror_r"]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: size_t) -> c_int;
}
#[cfg(not(target_os = "linux"))]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: size_t) -> c_int;
}
let mut buf = [0 as c_char; TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno as c_int, p, buf.len() as size_t) < 0 {
panic!("strerror_r failure");
}
let p = p as *const _;
str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_string()
}
}
}