#[cfg(any(feature = "system", feature = "network"))]
use std::ffi::{OsStr, OsString};
#[cfg(any(feature = "system", feature = "network"))]
use std::os::unix::ffi::OsStrExt;
#[cfg(any(feature = "disk", feature = "system"))]
pub(crate) fn c_buf_to_utf8_str(buf: &[libc::c_char]) -> Option<&str> {
unsafe {
let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len());
std::str::from_utf8(if let Some(pos) = buf.iter().position(|x| *x == 0) {
&buf[..pos]
} else {
buf
})
.ok()
}
}
#[cfg(any(feature = "disk", feature = "system"))]
pub(crate) fn c_buf_to_utf8_string(buf: &[libc::c_char]) -> Option<String> {
c_buf_to_utf8_str(buf).map(|s| s.to_owned())
}
#[cfg(any(feature = "system", feature = "network"))]
pub(crate) fn c_buf_to_os_str(buf: &[libc::c_char]) -> &OsStr {
unsafe {
let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len());
OsStr::from_bytes(if let Some(pos) = buf.iter().position(|x| *x == 0) {
&buf[..pos]
} else {
buf
})
}
}
#[cfg(any(feature = "system", feature = "network"))]
pub(crate) fn c_buf_to_os_string(buf: &[libc::c_char]) -> OsString {
c_buf_to_os_str(buf).to_owned()
}
#[cfg(feature = "system")]
pub(crate) unsafe fn from_cstr_array(ptr: *const *const libc::c_char) -> Vec<OsString> {
if ptr.is_null() {
return Vec::new();
}
let mut max = 0;
loop {
unsafe {
let ptr = ptr.add(max);
if (*ptr).is_null() {
break;
}
}
max += 1;
}
if max == 0 {
return Vec::new();
}
let mut ret = Vec::with_capacity(max);
for pos in 0..max {
unsafe {
let p = ptr.add(pos);
ret.push(OsStr::from_bytes(std::ffi::CStr::from_ptr(*p).to_bytes()).to_os_string());
}
}
ret
}