1use std::ffi::{CStr, CString, OsStr};
2use std::io::Result;
3
4use libc::{c_char, c_int};
5
6use std::os::unix::prelude::*;
7
8pub unsafe fn ptr_to_os_str<'a>(ptr: *const c_char) -> Option<&'a OsStr> {
9 if ptr.is_null() {
10 return None;
11 }
12
13 Some(ptr_to_os_str_unchecked(ptr))
14}
15
16pub unsafe fn ptr_to_os_str_unchecked<'a>(ptr: *const c_char) -> &'a OsStr {
17 OsStr::from_bytes(slice:CStr::from_ptr(ptr).to_bytes())
18}
19
20pub fn os_str_to_cstring<T: AsRef<OsStr>>(s: T) -> Result<CString> {
21 match CString::new(s.as_ref().as_bytes()) {
22 Ok(s: CString) => Ok(s),
23 Err(_) => Err(std::io::Error::from_raw_os_error(code:libc::EINVAL)),
24 }
25}
26
27pub fn errno_to_result(errno: c_int) -> Result<()> {
28 match errno {
29 x: i32 if x >= 0 => Ok(()),
30 e: i32 => Err(std::io::Error::from_raw_os_error(-e)),
31 }
32}
33