about summary refs log tree commit diff
path: root/src/libstd/sys
diff options
context:
space:
mode:
authorBarosl Lee <vcs@barosl.com>2015-08-26 21:27:32 +0900
committerBarosl Lee <vcs@barosl.com>2015-08-28 04:48:03 +0900
commit6065678e627643cc3275c677408d11f48802595e (patch)
treeb9fdd3cbaad37da03cdaa6b7730746239c0673e2 /src/libstd/sys
parent7723550fdd7fe29bee9dcbd45bdef4f209a7e1f1 (diff)
downloadrust-6065678e627643cc3275c677408d11f48802595e.tar.gz
rust-6065678e627643cc3275c677408d11f48802595e.zip
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.
Diffstat (limited to 'src/libstd/sys')
-rw-r--r--src/libstd/sys/unix/os.rs12
1 files changed, 7 insertions, 5 deletions
diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs
index 2b6b50a1a56..fa31ac682d4 100644
--- a/src/libstd/sys/unix/os.rs
+++ b/src/libstd/sys/unix/os.rs
@@ -30,7 +30,6 @@ use sys::c;
 use sys::fd;
 use vec;
 
-const GETCWD_BUF_BYTES: usize = 2048;
 const TMPBUF_SZ: usize = 128;
 
 /// Returns the platform-specific value of errno
@@ -94,11 +93,9 @@ pub fn error_string(errno: i32) -> String {
 }
 
 pub fn getcwd() -> io::Result<PathBuf> {
-    let mut buf = Vec::new();
-    let mut n = GETCWD_BUF_BYTES;
+    let mut buf = Vec::with_capacity(512);
     loop {
         unsafe {
-            buf.reserve(n);
             let ptr = buf.as_mut_ptr() as *mut libc::c_char;
             if !libc::getcwd(ptr, buf.capacity() as libc::size_t).is_null() {
                 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> {
                     return Err(error);
                 }
             }
-            n *= 2;
+
+            // Trigger the internal buffer resizing logic of `Vec` by requiring
+            // more space than the current capacity.
+            let cap = buf.capacity();
+            buf.set_len(cap);
+            buf.reserve(1);
         }
     }
 }