Call `f` with a NUL-terminated copy of `s`.
(s: S, f: F)
| 4 | |
| 5 | /// Call `f` with a NUL-terminated copy of `s`. |
| 6 | pub(crate) fn with_cstr<S, F, R>(s: S, f: F) -> R |
| 7 | where |
| 8 | S: AsRef<OsStr>, |
| 9 | F: FnOnce(*const c_char) -> R, |
| 10 | { |
| 11 | #[cfg(unix)] |
| 12 | fn os_str_bytes(s: &OsStr) -> &[u8] { |
| 13 | use std::os::unix::prelude::OsStrExt; |
| 14 | s.as_bytes() |
| 15 | } |
| 16 | #[cfg(windows)] |
| 17 | fn os_str_bytes(s: &OsStr) -> &[u8] { |
| 18 | s.to_str().unwrap().as_bytes() |
| 19 | } |
| 20 | |
| 21 | let bytes = os_str_bytes(s.as_ref()); |
| 22 | let allocated; |
| 23 | let mut buffer = [0u8; 256]; |
| 24 | let ptr: *const c_char = if bytes.len() < buffer.len() { |
| 25 | buffer[0..bytes.len()].clone_from_slice(bytes); |
| 26 | buffer[bytes.len()] = 0; |
| 27 | buffer.as_ptr() as *const c_char |
| 28 | } else { |
| 29 | allocated = Some(CString::new(bytes).unwrap()); |
| 30 | allocated.as_ref().unwrap().as_ptr() |
| 31 | }; |
| 32 | f(ptr) |
| 33 | } |
| 34 | |
| 35 | /// Call `f` with a NUL-terminated copy of `s`, or a null pointer if `s` is None. |
| 36 | pub(crate) fn with_opt_cstr<S, F, R>(s: Option<S>, f: F) -> R |