Skip to content

Commit 64c5deb

Browse files
committed
Auto merge of #96314 - AronParker:issue-96297-fix, r=thomcc
Reduce allocations for path conversions on Windows Previously, UTF-8 to UTF-16 Path conversions on Windows unnecessarily allocate twice, as described in #96297. This commit fixes that issue.
2 parents 8834629 + 6cfdeaf commit 64c5deb

File tree

1 file changed

+7
-1
lines changed
  • library/std/src/sys/windows

1 file changed

+7
-1
lines changed

library/std/src/sys/windows/mod.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,13 @@ pub fn unrolled_find_u16s(needle: u16, haystack: &[u16]) -> Option<usize> {
156156

157157
pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> {
158158
fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> {
159-
let mut maybe_result: Vec<u16> = s.encode_wide().collect();
159+
// Most paths are ASCII, so reserve capacity for as much as there are bytes
160+
// in the OsStr plus one for the null-terminating character. We are not
161+
// wasting bytes here as paths created by this function are primarily used
162+
// in an ephemeral fashion.
163+
let mut maybe_result = Vec::with_capacity(s.len() + 1);
164+
maybe_result.extend(s.encode_wide());
165+
160166
if unrolled_find_u16s(0, &maybe_result).is_some() {
161167
return Err(crate::io::const_io_error!(
162168
ErrorKind::InvalidInput,

0 commit comments

Comments
 (0)