Reduce monomorphisation bloat in small_c_string

This commit is contained in:
David Thomas 2024-02-14 17:41:45 +00:00 committed by GnomedDev
parent 8b21296b5d
commit 8daf137543
No known key found for this signature in database
GPG key ID: 9BF10F8372B254D1
2 changed files with 16 additions and 8 deletions

View file

@ -17,20 +17,27 @@ const NUL_ERR: io::Error =
#[inline]
pub fn run_path_with_cstr<T, F>(path: &Path, f: F) -> io::Result<T>
where
F: FnOnce(&CStr) -> io::Result<T>,
F: FnMut(&CStr) -> io::Result<T>,
{
run_with_cstr(path.as_os_str().as_encoded_bytes(), f)
}
#[inline]
pub fn run_with_cstr<T, F>(bytes: &[u8], f: F) -> io::Result<T>
pub fn run_with_cstr<T, F>(bytes: &[u8], mut f: F) -> io::Result<T>
where
F: FnOnce(&CStr) -> io::Result<T>,
F: FnMut(&CStr) -> io::Result<T>,
{
if bytes.len() >= MAX_STACK_ALLOCATION {
return run_with_cstr_allocating(bytes, f);
run_with_cstr_allocating(bytes, &mut f)
} else {
unsafe { run_with_cstr_stack(bytes, &mut f) }
}
}
unsafe fn run_with_cstr_stack<T>(
bytes: &[u8],
f: &mut dyn FnMut(&CStr) -> io::Result<T>,
) -> io::Result<T> {
let mut buf = MaybeUninit::<[u8; MAX_STACK_ALLOCATION]>::uninit();
let buf_ptr = buf.as_mut_ptr() as *mut u8;
@ -47,10 +54,10 @@ where
#[cold]
#[inline(never)]
fn run_with_cstr_allocating<T, F>(bytes: &[u8], f: F) -> io::Result<T>
where
F: FnOnce(&CStr) -> io::Result<T>,
{
fn run_with_cstr_allocating<T>(
bytes: &[u8],
f: &mut dyn FnMut(&CStr) -> io::Result<T>,
) -> io::Result<T> {
match CString::new(bytes) {
Ok(s) => f(&s),
Err(_) => Err(NUL_ERR),

View file

@ -11,6 +11,7 @@ LL | let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode a
= note: inside `std::sys::pal::PLATFORM::cvt_r::<i32, {closure@std::sys::pal::PLATFORM::fs::File::open_c::{closure#0}}>` at RUSTLIB/std/src/sys/pal/PLATFORM/mod.rs:LL:CC
= note: inside `std::sys::pal::PLATFORM::fs::File::open_c` at RUSTLIB/std/src/sys/pal/PLATFORM/fs.rs:LL:CC
= note: inside closure at RUSTLIB/std/src/sys/pal/PLATFORM/fs.rs:LL:CC
= note: inside `std::sys::pal::PLATFORM::small_c_string::run_with_cstr_stack::<std::sys::pal::PLATFORM::fs::File>` at RUSTLIB/std/src/sys/pal/PLATFORM/small_c_string.rs:LL:CC
= note: inside `std::sys::pal::PLATFORM::small_c_string::run_with_cstr::<std::sys::pal::PLATFORM::fs::File, {closure@std::sys::pal::PLATFORM::fs::File::open::{closure#0}}>` at RUSTLIB/std/src/sys/pal/PLATFORM/small_c_string.rs:LL:CC
= note: inside `std::sys::pal::PLATFORM::small_c_string::run_path_with_cstr::<std::sys::pal::PLATFORM::fs::File, {closure@std::sys::pal::PLATFORM::fs::File::open::{closure#0}}>` at RUSTLIB/std/src/sys/pal/PLATFORM/small_c_string.rs:LL:CC
= note: inside `std::sys::pal::PLATFORM::fs::File::open` at RUSTLIB/std/src/sys/pal/PLATFORM/fs.rs:LL:CC