safe_libc/posix/
string.rs

1//
2// Created:  Fri 17 Apr 2020 11:55:31 PM PDT
3// Modified: Tue 25 Nov 2025 03:44:25 PM PST
4//
5// Copyright (C) 2020 Robert Gill <rtgill82@gmail.com>
6//
7// Permission is hereby granted, free of charge, to any person obtaining a copy
8// of this software and associated documentation files (the "Software"), to
9// deal in the Software without restriction, including without limitation the
10// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11// sell copies of the Software, and to permit persons to whom the Software is
12// furnished to do so, subject to the following conditions:
13//
14// The above copyright notice and this permission notice shall be included in
15// all copies of the Software, its documentation and marketing & publicity
16// materials, and acknowledgment shall be given in the documentation, materials
17// and software packages that this Software was used.
18//
19// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22// THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
23// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25//
26
27use std::ffi::CString;
28use std::{ptr,slice};
29use libc::c_void;
30
31use crate::stdlib::realloc;
32use crate::errno::{Error,Result};
33use crate::errno;
34
35const BUF_SIZE: usize = 512;
36
37macro_rules! rv2errnum {
38    ($rv:ident) => {
39        match $rv {
40             0 => 0,
41            -1 => errno::errno(),
42            _  => $rv
43        }
44    }
45}
46
47pub fn strerror(errnum: i32) -> Result<String> {
48    unsafe {
49        let mut buflen = BUF_SIZE;
50        let buf = ptr::null_mut();
51
52        loop {
53            let buf = realloc(buf, buflen)?;
54            let rv = libc::strerror_r(errnum, buf as *mut i8, buflen);
55            let errnum = rv2errnum!(rv);
56
57            if errnum == 0 { // success
58                let string = c_void2string(buf)?;
59                return Ok(string);
60            }
61
62            if errnum == libc::EINVAL {
63                let string = c_void2string(buf)?;
64                return Err(Error::new_msg(errnum, string));
65            }
66
67            // reallocate and try again
68            buflen *= 2;
69        }
70    }
71}
72
73// strerror with static buffer
74pub(crate) fn strerror_s(errnum: i32) -> Result<String> {
75    let mut buf: [u8; BUF_SIZE] = [0; BUF_SIZE];
76
77    let rv = unsafe {
78        libc::strerror_r(errnum, buf.as_mut_ptr() as *mut i8, BUF_SIZE)
79    };
80
81    let errnum = rv2errnum!(rv);
82    if errnum == libc::ERANGE {
83        buf[BUF_SIZE - 1] = 0;
84    }
85
86    let string = String::from_utf8_lossy(&buf).to_string();
87    if errnum == libc::EINVAL {
88        return Err(Error::new_msg(errnum, string));
89    }
90    Ok(string)
91}
92
93unsafe fn c_void2string(buf: *mut c_void) -> Result<String> {
94    let len = libc::strlen(buf as *mut i8) + 1;
95    let buf = buf as *const u8;
96    let vec: Vec<u8> = slice::from_raw_parts(buf, len).into();
97    let string = CString::from_vec_with_nul(vec)?
98        .to_string_lossy().to_string();
99
100    libc::free(buf as *mut c_void);
101    Ok(string)
102}
103
104#[cfg(test)]
105mod tests {
106    use super::strerror;
107    use crate::errno::Error;
108
109    #[test]
110    fn test_strerror() {
111        let msg = strerror(libc::EACCES);
112        assert_eq!(msg, Ok(String::from("Permission denied")));
113    }
114
115    #[test]
116    fn test_strerror_invalid() {
117        let msg = strerror(1234567890);
118        assert_eq!(msg, Err(Error::new(libc::EINVAL)));
119    }
120}