use std::ffi::CString;
use std::{ptr,slice};
use libc::c_void;
use crate::stdlib::realloc;
use crate::errno::{Error,Result};
use crate::errno;
const BUF_SIZE: usize = 512;
macro_rules! rv2errnum {
($rv:ident) => {
match $rv {
0 => 0,
-1 => errno::errno(),
_ => $rv
}
}
}
pub fn strerror(errnum: i32) -> Result<String> {
unsafe {
let mut buflen = BUF_SIZE;
let buf = ptr::null_mut();
loop {
let buf = realloc(buf, buflen)?;
let rv = libc::strerror_r(errnum, buf as *mut i8, buflen);
let errnum = rv2errnum!(rv);
if errnum == 0 { let string = c_void2string(buf)?;
return Ok(string);
}
if errnum == libc::EINVAL {
let string = c_void2string(buf)?;
return Err(Error::with_msg(errnum, string));
}
buflen *= 2;
}
}
}
pub(crate) fn strerror_s(errnum: i32) -> Result<String> {
let mut buf: [u8; BUF_SIZE] = [0; BUF_SIZE];
let rv = unsafe {
libc::strerror_r(errnum, buf.as_mut_ptr() as *mut i8, BUF_SIZE)
};
let errnum = rv2errnum!(rv);
if errnum == libc::ERANGE {
buf[BUF_SIZE - 1] = 0;
}
let string = String::from_utf8_lossy(&buf).to_string();
if errnum == libc::EINVAL {
return Err(Error::with_msg(errnum, string));
}
Ok(string)
}
unsafe fn c_void2string(buf: *mut c_void) -> Result<String> {
let len = libc::strlen(buf as *mut i8) + 1;
let buf = buf as *const u8;
let vec: Vec<u8> = slice::from_raw_parts(buf, len).into();
let string = CString::from_vec_with_nul(vec)?
.to_string_lossy().to_string();
libc::free(buf as *mut c_void);
Ok(string)
}
#[cfg(test)]
mod tests {
use super::strerror;
use crate::errno::Error;
#[test]
fn test_strerror() {
let msg = strerror(libc::EACCES);
assert_eq!(msg, Ok(String::from("Permission denied")));
}
#[test]
fn test_strerror_invalid() {
let msg = strerror(1234567890);
assert_eq!(msg, Err(Error::new(libc::EINVAL)));
}
}