Skip to content

Commit a3ac0c4

Browse files
authored
Rollup merge of rust-lang#41376 - mbrubeck:docs, r=frewsxcv
Expanded docs and examples for PathBuf::file_name and friends This addresses some common surprises when `PathBuf::set_file_name` is called on the path of a directory rather than a file. r? @steveklabnik
2 parents 38a8aa1 + 3b4d34d commit a3ac0c4

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/libstd/path.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -1189,8 +1189,13 @@ impl PathBuf {
11891189
/// If [`self.file_name`] was [`None`], this is equivalent to pushing
11901190
/// `file_name`.
11911191
///
1192+
/// Otherwise it is equivalent to calling [`pop`] and then pushing
1193+
/// `file_name`. The new path will be a sibling of the original path.
1194+
/// (That is, it will have the same parent.)
1195+
///
11921196
/// [`self.file_name`]: struct.PathBuf.html#method.file_name
11931197
/// [`None`]: ../../std/option/enum.Option.html#variant.None
1198+
/// [`pop`]: struct.PathBuf.html#method.pop
11941199
///
11951200
/// # Examples
11961201
///
@@ -1725,7 +1730,10 @@ impl Path {
17251730
})
17261731
}
17271732

1728-
/// Returns the final component of the `Path`, if it is a normal file.
1733+
/// Returns the final component of the `Path`, if there is one.
1734+
///
1735+
/// If the path is a normal file, this is the file name. If it's the path of a directory, this
1736+
/// is the directory name.
17291737
///
17301738
/// Returns [`None`] If the path terminates in `..`.
17311739
///
@@ -1737,10 +1745,12 @@ impl Path {
17371745
/// use std::path::Path;
17381746
/// use std::ffi::OsStr;
17391747
///
1740-
/// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt").file_name());
1748+
/// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1749+
/// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
17411750
/// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
17421751
/// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
17431752
/// assert_eq!(None, Path::new("foo.txt/..").file_name());
1753+
/// assert_eq!(None, Path::new("/").file_name());
17441754
/// ```
17451755
#[stable(feature = "rust1", since = "1.0.0")]
17461756
pub fn file_name(&self) -> Option<&OsStr> {
@@ -1926,6 +1936,9 @@ impl Path {
19261936
///
19271937
/// let path = Path::new("/tmp/foo.txt");
19281938
/// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1939+
///
1940+
/// let path = Path::new("/tmp");
1941+
/// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
19291942
/// ```
19301943
#[stable(feature = "rust1", since = "1.0.0")]
19311944
pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {

0 commit comments

Comments
 (0)