1 use crate::ffi::{CStr, CString};
2 use crate::mem::MaybeUninit;
7 // Make sure to stay under 4096 so the compiler doesn't insert a probe frame:
8 // https://docs.rs/compiler_builtins/latest/compiler_builtins/probestack/index.html
9 #[cfg(not(target_os = "espidf"))]
10 const MAX_STACK_ALLOCATION: usize = 384;
11 #[cfg(target_os = "espidf")]
12 const MAX_STACK_ALLOCATION: usize = 32;
14 const NUL_ERR: io::Error =
15 io::const_io_error!(io::ErrorKind::InvalidInput, "file name contained an unexpected NUL byte");
18 pub fn run_path_with_cstr<T, F>(path: &Path, f: F) -> io::Result<T>
20 F: FnOnce(&CStr) -> io::Result<T>,
22 run_with_cstr(path.as_os_str().bytes(), f)
26 pub fn run_with_cstr<T, F>(bytes: &[u8], f: F) -> io::Result<T>
28 F: FnOnce(&CStr) -> io::Result<T>,
30 if bytes.len() >= MAX_STACK_ALLOCATION {
31 return run_with_cstr_allocating(bytes, f);
34 let mut buf = MaybeUninit::<[u8; MAX_STACK_ALLOCATION]>::uninit();
35 let buf_ptr = buf.as_mut_ptr() as *mut u8;
38 ptr::copy_nonoverlapping(bytes.as_ptr(), buf_ptr, bytes.len());
39 buf_ptr.add(bytes.len()).write(0);
42 match CStr::from_bytes_with_nul(unsafe { slice::from_raw_parts(buf_ptr, bytes.len() + 1) }) {
44 Err(_) => Err(NUL_ERR),
50 fn run_with_cstr_allocating<T, F>(bytes: &[u8], f: F) -> io::Result<T>
52 F: FnOnce(&CStr) -> io::Result<T>,
54 match CString::new(bytes) {
56 Err(_) => Err(NUL_ERR),