Skip to content

30x performance improvement in with_nix_path #1655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
syntax: glob
Cargo.lock
target
.idea
*.diff
*.rej
*.orig
Expand Down
22 changes: 15 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,9 @@ pub mod unistd;

use libc::PATH_MAX;

use std::result;
use std::{ptr, result, slice};
use std::ffi::{CStr, OsStr};
use std::mem::MaybeUninit;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -260,15 +261,22 @@ impl NixPath for [u8] {
}

fn with_nix_path<T, F>(&self, f: F) -> Result<T>
where F: FnOnce(&CStr) -> T {
let mut buf = [0u8; PATH_MAX as usize];

where
F: FnOnce(&CStr) -> T,
{
if self.len() >= PATH_MAX as usize {
return Err(Errno::ENAMETOOLONG)
return Err(Errno::ENAMETOOLONG);
}

let mut buf = MaybeUninit::<[u8; PATH_MAX as usize]>::uninit();
let buf_ptr = buf.as_mut_ptr() as *mut u8;

unsafe {
ptr::copy_nonoverlapping(self.as_ptr(), buf_ptr, self.len());
buf_ptr.add(self.len()).write(0);
}

buf[..self.len()].copy_from_slice(self);
match CStr::from_bytes_with_nul(&buf[..=self.len()]) {
match CStr::from_bytes_with_nul(unsafe { slice::from_raw_parts(buf_ptr, self.len() + 1) }) {
Ok(s) => Ok(f(s)),
Err(_) => Err(Errno::EINVAL),
}
Expand Down