about summary refs log tree commit diff
path: root/library/std/src/path.rs
diff options
context:
space:
mode:
authorThalia Archibald <thalia@archibald.dev>2025-04-22 03:31:45 -0700
committerThalia Archibald <thalia@archibald.dev>2025-04-30 23:56:39 -0700
commit0f0c0d8b16b265ac57cac9fd50f1dcfe78719a6a (patch)
treeff3b348905832feb969e629d4ef31c82058632bf /library/std/src/path.rs
parent7cb357a36b96781f9ff85f8a4168382243352ba1 (diff)
downloadrust-0f0c0d8b16b265ac57cac9fd50f1dcfe78719a6a.tar.gz
rust-0f0c0d8b16b265ac57cac9fd50f1dcfe78719a6a.zip
Avoid redundant WTF-8 checks in `PathBuf`
Eliminate checks for WTF-8 boundaries in `PathBuf::set_extension` and
`add_extension`, where joining WTF-8 surrogate halves is impossible.
Don't convert the `str` to `OsStr`, because `OsString::push` specializes
to skip the joining when given strings.
Diffstat (limited to 'library/std/src/path.rs')
-rw-r--r--library/std/src/path.rs16
1 files changed, 10 insertions, 6 deletions
diff --git a/library/std/src/path.rs b/library/std/src/path.rs
index ae18891ad47..32a86e9f7b4 100644
--- a/library/std/src/path.rs
+++ b/library/std/src/path.rs
@@ -1526,11 +1526,13 @@ impl PathBuf {
         self.inner.truncate(end_file_stem.wrapping_sub(start));
 
         // add the new extension, if any
-        let new = extension;
+        let new = extension.as_encoded_bytes();
         if !new.is_empty() {
             self.inner.reserve_exact(new.len() + 1);
-            self.inner.push(OsStr::new("."));
-            self.inner.push(new);
+            self.inner.push(".");
+            // SAFETY: Since a UTF-8 string was just pushed, it is not possible
+            // for the buffer to end with a surrogate half.
+            unsafe { self.inner.extend_from_slice_unchecked(new) };
         }
 
         true
@@ -1587,7 +1589,7 @@ impl PathBuf {
             Some(f) => f.as_encoded_bytes(),
         };
 
-        let new = extension;
+        let new = extension.as_encoded_bytes();
         if !new.is_empty() {
             // truncate until right after the file name
             // this is necessary for trimming the trailing slash
@@ -1597,8 +1599,10 @@ impl PathBuf {
 
             // append the new extension
             self.inner.reserve_exact(new.len() + 1);
-            self.inner.push(OsStr::new("."));
-            self.inner.push(new);
+            self.inner.push(".");
+            // SAFETY: Since a UTF-8 string was just pushed, it is not possible
+            // for the buffer to end with a surrogate half.
+            unsafe { self.inner.extend_from_slice_unchecked(new) };
         }
 
         true