Skip to content

Commit 40916ef

Browse files
committed
Add notes and examples about non-intuitive PathBuf::set_extension behavior
Basically, passing the empty string will actually remove the extension instead of setting it to the empty string. This might change what is considered to be an extension. Additionally, passing an extension that contains dots will make the path only consider the last part of it to be the new extension.
1 parent 742d3f0 commit 40916ef

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

library/std/src/path.rs

+30-3
Original file line numberDiff line numberDiff line change
@@ -1411,14 +1411,29 @@ impl PathBuf {
14111411
self.push(file_name);
14121412
}
14131413

1414-
/// Updates [`self.extension`] to `extension`.
1414+
/// Updates [`self.extension`] to `Some(extension)` or to `None` if
1415+
/// `extension` is empty.
14151416
///
14161417
/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
14171418
/// returns `true` and updates the extension otherwise.
14181419
///
14191420
/// If [`self.extension`] is [`None`], the extension is added; otherwise
14201421
/// it is replaced.
14211422
///
1423+
/// If `extension` is the empty string, [`self.extension`] will be [`None`]
1424+
/// afterwards, not `Some("")`.
1425+
///
1426+
/// # Caveats
1427+
///
1428+
/// The new `extension` may contain dots and will be used in its entirety,
1429+
/// but only the part after the final dot will be reflected in
1430+
/// [`self.extension`].
1431+
///
1432+
/// If the file stem contains internal dots and `extension` is empty, part
1433+
/// of the old file stem will be considered the new [`self.extension`].
1434+
///
1435+
/// See the examples below.
1436+
///
14221437
/// [`self.file_name`]: Path::file_name
14231438
/// [`self.extension`]: Path::extension
14241439
///
@@ -1432,8 +1447,20 @@ impl PathBuf {
14321447
/// p.set_extension("force");
14331448
/// assert_eq!(Path::new("/feel/the.force"), p.as_path());
14341449
///
1435-
/// p.set_extension("dark_side");
1436-
/// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1450+
/// p.set_extension("dark.side");
1451+
/// assert_eq!(Path::new("/feel/the.dark.side"), p.as_path());
1452+
///
1453+
/// p.set_extension("cookie");
1454+
/// assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path());
1455+
///
1456+
/// p.set_extension("");
1457+
/// assert_eq!(Path::new("/feel/the.dark"), p.as_path());
1458+
///
1459+
/// p.set_extension("");
1460+
/// assert_eq!(Path::new("/feel/the"), p.as_path());
1461+
///
1462+
/// p.set_extension("");
1463+
/// assert_eq!(Path::new("/feel/the"), p.as_path());
14371464
/// ```
14381465
#[stable(feature = "rust1", since = "1.0.0")]
14391466
pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {

0 commit comments

Comments
 (0)