From 9a9d5534f04d81afc6fcdbe13fda490fcf595c60 Mon Sep 17 00:00:00 2001 From: Aron Parker Date: Fri, 22 Apr 2022 11:02:04 +0200 Subject: [PATCH 1/2] 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. --- library/std/src/sys/windows/mod.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/mod.rs b/library/std/src/sys/windows/mod.rs index 31c7208bbf1..8e1450e4d29 100644 --- a/library/std/src/sys/windows/mod.rs +++ b/library/std/src/sys/windows/mod.rs @@ -156,7 +156,13 @@ pub fn unrolled_find_u16s(needle: u16, haystack: &[u16]) -> Option { pub fn to_u16s>(s: S) -> crate::io::Result> { fn inner(s: &OsStr) -> crate::io::Result> { - let mut maybe_result: Vec = s.encode_wide().collect(); + // Most paths are ASCII, so reserve capacity for as much as there are bytes + // in the OsStr plus one for the null-terminating character. We are not + // wasting bytes here as paths created by this function are primarily used + // in an ephemeral fashion. + let mut maybe_result: Vec = Vec::with_capacity(s.len() + 1); + maybe_result.extend(s.encode_wide()); + if unrolled_find_u16s(0, &maybe_result).is_some() { return Err(crate::io::const_io_error!( ErrorKind::InvalidInput, From 6cfdeaf1a198a63e65817f12e93b5a29fdddfda8 Mon Sep 17 00:00:00 2001 From: Aron Parker Date: Fri, 22 Apr 2022 11:42:53 +0200 Subject: [PATCH 2/2] Remove redundant type annotation --- library/std/src/sys/windows/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/windows/mod.rs b/library/std/src/sys/windows/mod.rs index 8e1450e4d29..5923638a43b 100644 --- a/library/std/src/sys/windows/mod.rs +++ b/library/std/src/sys/windows/mod.rs @@ -160,7 +160,7 @@ pub fn to_u16s>(s: S) -> crate::io::Result> { // in the OsStr plus one for the null-terminating character. We are not // wasting bytes here as paths created by this function are primarily used // in an ephemeral fashion. - let mut maybe_result: Vec = Vec::with_capacity(s.len() + 1); + let mut maybe_result = Vec::with_capacity(s.len() + 1); maybe_result.extend(s.encode_wide()); if unrolled_find_u16s(0, &maybe_result).is_some() {