| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
use core::str; |
| 16 |
use libc::{self, c_int, size_t, strerror_r, strlen}; |
| 17 |
|
| 18 |
use crate::Errno; |
| 19 |
|
| 20 |
fn from_utf8_lossy(input: &[u8]) -> &str { |
| 21 |
match str::from_utf8(input) { |
| 22 |
Ok(valid) => valid, |
| 23 |
Err(error) => unsafe { str::from_utf8_unchecked(&input[..error.valid_up_to()]) }, |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
pub fn with_description<F, T>(err: Errno, callback: F) -> T |
| 28 |
where |
| 29 |
F: FnOnce(Result<&str, Errno>) -> T, |
| 30 |
{ |
| 31 |
let mut buf = [0u8; 1024]; |
| 32 |
let c_str = unsafe { |
| 33 |
let rc = strerror_r(err.0, buf.as_mut_ptr() as *mut _, buf.len() as size_t); |
| 34 |
if rc != 0 { |
| 35 |
let fm_err = Errno(rc); |
| 36 |
if fm_err != Errno(libc::ERANGE) { |
| 37 |
return callback(Err(fm_err)); |
| 38 |
} |
| 39 |
} |
| 40 |
let c_str_len = strlen(buf.as_ptr() as *const _); |
| 41 |
&buf[..c_str_len] |
| 42 |
}; |
| 43 |
callback(Ok(from_utf8_lossy(c_str))) |
| 44 |
} |
| 45 |
|
| 46 |
pub const STRERROR_NAME: &str = "strerror_r"; |
| 47 |
|
| 48 |
pub fn errno() -> Errno { |
| 49 |
unsafe { Errno(*__errno_location()) } |
| 50 |
} |
| 51 |
|
| 52 |
pub fn set_errno(Errno(new_errno): Errno) { |
| 53 |
unsafe { |
| 54 |
*__errno_location() = new_errno; |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
extern "C" { |
| 59 |
fn __errno_location() -> *mut c_int; |
| 60 |
} |