Skip to content

Commit 0f0c0d8

Browse files
committed
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.
1 parent 7cb357a commit 0f0c0d8

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

library/std/src/path.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -1526,11 +1526,13 @@ impl PathBuf {
15261526
self.inner.truncate(end_file_stem.wrapping_sub(start));
15271527

15281528
// add the new extension, if any
1529-
let new = extension;
1529+
let new = extension.as_encoded_bytes();
15301530
if !new.is_empty() {
15311531
self.inner.reserve_exact(new.len() + 1);
1532-
self.inner.push(OsStr::new("."));
1533-
self.inner.push(new);
1532+
self.inner.push(".");
1533+
// SAFETY: Since a UTF-8 string was just pushed, it is not possible
1534+
// for the buffer to end with a surrogate half.
1535+
unsafe { self.inner.extend_from_slice_unchecked(new) };
15341536
}
15351537

15361538
true
@@ -1587,7 +1589,7 @@ impl PathBuf {
15871589
Some(f) => f.as_encoded_bytes(),
15881590
};
15891591

1590-
let new = extension;
1592+
let new = extension.as_encoded_bytes();
15911593
if !new.is_empty() {
15921594
// truncate until right after the file name
15931595
// this is necessary for trimming the trailing slash
@@ -1597,8 +1599,10 @@ impl PathBuf {
15971599

15981600
// append the new extension
15991601
self.inner.reserve_exact(new.len() + 1);
1600-
self.inner.push(OsStr::new("."));
1601-
self.inner.push(new);
1602+
self.inner.push(".");
1603+
// SAFETY: Since a UTF-8 string was just pushed, it is not possible
1604+
// for the buffer to end with a surrogate half.
1605+
unsafe { self.inner.extend_from_slice_unchecked(new) };
16021606
}
16031607

16041608
true

0 commit comments

Comments
 (0)