Skip to content

Commit 2fc246c

Browse files
bors[bot]otavio
andauthored
Merge #1127
1127: unistd: getcwd: Double the buffer when need, up to PATH_MAX as limit r=asomers a=otavio We now have a `reserve_double_buffer_size` method which reserves the double of buffer, up to a limit, allowing it to be reused on other methods in future. Signed-off-by: Otavio Salvador <[email protected]> Co-authored-by: Otavio Salvador <[email protected]>
2 parents ac5de6b + 035c69f commit 2fc246c

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/unistd.rs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use {Error, Result, NixPath};
55
use fcntl::{AtFlags, at_rawfd, fcntl, FdFlag, OFlag};
66
use fcntl::FcntlArg::F_SETFD;
77
use libc::{self, c_char, c_void, c_int, c_long, c_uint, size_t, pid_t, off_t,
8-
uid_t, gid_t, mode_t};
8+
uid_t, gid_t, mode_t, PATH_MAX};
99
use std::{fmt, mem, ptr};
1010
use std::ffi::{CString, CStr, OsString, OsStr};
1111
use std::os::unix::ffi::{OsStringExt, OsStrExt};
@@ -534,6 +534,21 @@ pub fn symlinkat<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
534534
Errno::result(res).map(drop)
535535
}
536536

537+
// Double the buffer capacity up to limit. In case it already has
538+
// reached the limit, return Errno::ERANGE.
539+
fn reserve_double_buffer_size<T>(buf: &mut Vec<T>, limit: usize) -> Result<()> {
540+
use std::cmp::min;
541+
542+
if buf.len() >= limit {
543+
return Err(Error::Sys(Errno::ERANGE))
544+
}
545+
546+
let capacity = min(buf.capacity() * 2, limit);
547+
buf.reserve(capacity);
548+
549+
Ok(())
550+
}
551+
537552
/// Returns the current directory as a `PathBuf`
538553
///
539554
/// Err is returned if the current user doesn't have the permission to read or search a component
@@ -576,11 +591,8 @@ pub fn getcwd() -> Result<PathBuf> {
576591
}
577592
}
578593

579-
// Trigger the internal buffer resizing logic of `Vec` by requiring
580-
// more space than the current capacity.
581-
let cap = buf.capacity();
582-
buf.set_len(cap);
583-
buf.reserve(1);
594+
// Trigger the internal buffer resizing logic.
595+
reserve_double_buffer_size(&mut buf, PATH_MAX as usize)?;
584596
}
585597
}
586598
}

0 commit comments

Comments
 (0)