Skip to content

Commit 6065678

Browse files
committed
Use a different buffer doubling logic for std::sys::os::getcwd
Make `std::sys::os::getcwd` call `Vec::reserve(1)` followed by `Vec::set_len` to double the buffer. This is to align with other similar functions, such as: - `std::sys_common::io::read_to_end_uninitialized` - `std::sys::fs::readlink` Also, reduce the initial buffer size from 2048 to 512. The previous size was introduced with 4bc26ce in 2013, but it seems a bit excessive. This is probably because buffer doubling was not implemented back then.
1 parent 7723550 commit 6065678

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/libstd/sys/unix/os.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ use sys::c;
3030
use sys::fd;
3131
use vec;
3232

33-
const GETCWD_BUF_BYTES: usize = 2048;
3433
const TMPBUF_SZ: usize = 128;
3534

3635
/// Returns the platform-specific value of errno
@@ -94,11 +93,9 @@ pub fn error_string(errno: i32) -> String {
9493
}
9594

9695
pub fn getcwd() -> io::Result<PathBuf> {
97-
let mut buf = Vec::new();
98-
let mut n = GETCWD_BUF_BYTES;
96+
let mut buf = Vec::with_capacity(512);
9997
loop {
10098
unsafe {
101-
buf.reserve(n);
10299
let ptr = buf.as_mut_ptr() as *mut libc::c_char;
103100
if !libc::getcwd(ptr, buf.capacity() as libc::size_t).is_null() {
104101
let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
@@ -111,7 +108,12 @@ pub fn getcwd() -> io::Result<PathBuf> {
111108
return Err(error);
112109
}
113110
}
114-
n *= 2;
111+
112+
// Trigger the internal buffer resizing logic of `Vec` by requiring
113+
// more space than the current capacity.
114+
let cap = buf.capacity();
115+
buf.set_len(cap);
116+
buf.reserve(1);
115117
}
116118
}
117119
}

0 commit comments

Comments
 (0)