Skip to content

Commit 1df54e4

Browse files
committed
Add Path::has_trailing_sep and related methods
1 parent 9822e3d commit 1df54e4

File tree

1 file changed

+159
-0
lines changed

1 file changed

+159
-0
lines changed

library/std/src/path.rs

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,6 +1403,83 @@ impl PathBuf {
14031403
}
14041404
}
14051405

1406+
/// Sets whether the path has a trailing [separator](MAIN_SEPARATOR).
1407+
///
1408+
/// The value returned by [`has_trailing_sep`](Self::has_trailing_sep) will be equivalent to
1409+
/// the provided value.
1410+
///
1411+
/// # Examples
1412+
///
1413+
/// ```
1414+
/// #![feature(path_trailing_sep)]
1415+
/// let mut p = PathBuf::from("dir");
1416+
///
1417+
/// assert!(!p.has_trailing_sep());
1418+
/// p.set_trailing_sep(false);
1419+
/// assert!(!p.has_trailing_sep());
1420+
/// p.set_trailing_sep(true);
1421+
/// assert!(p.has_trailing_sep());
1422+
/// assert_eq!(p.file_name(), None);
1423+
/// p.set_trailing_sep(false);
1424+
/// assert!(!p.has_trailing_sep());
1425+
/// assert_eq!(p.file_name(), Some("dir"));
1426+
/// assert_eq!(p, Path::new("dir"));
1427+
/// ```
1428+
#[unstable(feature = "path_trailing_sep", issue = "142503")]
1429+
pub fn set_trailing_sep(&mut self, trailing_sep: bool) {
1430+
if trailing_sep { self.push_trailing_sep() } else { self.pop_trailing_sep() }
1431+
}
1432+
1433+
/// Adds a trailing [separator](MAIN_SEPARATOR) to the path.
1434+
///
1435+
/// This acts similarly to [`Path::with_trailing_sep`], but mutates the underlying `PathBuf`.
1436+
///
1437+
/// # Examples
1438+
///
1439+
/// ```
1440+
/// #![feature(path_trailing_sep)]
1441+
/// use std::path::{Path, PathBuf};
1442+
///
1443+
/// let mut p = PathBuf::from("dir");
1444+
///
1445+
/// assert_eq!(p.file_name(), Some(Path::new("dir")));
1446+
/// p.push_trailing_sep();
1447+
/// assert_eq!(p.file_name(), None);
1448+
/// p.push_trailing_sep();
1449+
/// assert_eq!(p.file_name(), None);
1450+
/// assert_eq!(p, Path::new("dir/"));
1451+
/// ```
1452+
#[unstable(feature = "path_trailing_sep", issue = "142503")]
1453+
pub fn push_trailing_sep(&mut self) {
1454+
if !self.has_trailing_sep() {
1455+
self.push("");
1456+
}
1457+
}
1458+
1459+
/// Removes a trailing [separator](MAIN_SEPARATOR) from the path, if possible.
1460+
///
1461+
/// This acts similarly to [`Path::trim_trailing_sep`], but mutates the underlying `PathBuf`.
1462+
///
1463+
/// # Examples
1464+
///
1465+
/// ```
1466+
/// #![feature(path_trailing_sep)]
1467+
/// use std::path::{Path, PathBuf};
1468+
///
1469+
/// let mut p = PathBuf::from("dir/");
1470+
///
1471+
/// assert_eq!(p.file_name(), None);
1472+
/// p.pop_trailing_sep();
1473+
/// assert_eq!(p.file_name(), Some("dir"));
1474+
/// p.pop_trailing_sep();
1475+
/// assert_eq!(p.file_name(), Some("dir"));
1476+
/// assert_eq!(p, Path::new("/dir"));
1477+
/// ```
1478+
#[unstable(feature = "path_trailing_sep", issue = "142503")]
1479+
pub fn pop_trailing_sep(&mut self) {
1480+
self.inner.truncate(self.trim_trailing_sep().as_os_str().len());
1481+
}
1482+
14061483
/// Updates [`self.file_name`] to `file_name`.
14071484
///
14081485
/// If [`self.file_name`] was [`None`], this is equivalent to pushing
@@ -2686,6 +2763,88 @@ impl Path {
26862763
self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
26872764
}
26882765

2766+
/// Checks whether the path ends in a trailing [separator](MAIN_SEPARATOR).
2767+
///
2768+
/// This is generally done to ensure that a path is treated as a directory, not a file,
2769+
/// although it does not actually guarantee that such a path is a directory on the underlying
2770+
/// file system.
2771+
///
2772+
/// Despite this behavior, two paths are still considered the same in Rust whether they have a
2773+
/// trailing separator or not.
2774+
///
2775+
/// # Examples
2776+
///
2777+
/// ```
2778+
/// #![feature(path_trailing_sep)]
2779+
/// use std::path::Path;
2780+
///
2781+
/// assert!(Path::new("dir/").has_trailing_sep());
2782+
/// assert!(!Path::new("file.rs").has_trailing_sep());
2783+
/// ```
2784+
#[unstable(feature = "path_trailing_sep", issue = "142503")]
2785+
#[must_use]
2786+
#[inline]
2787+
pub fn has_trailing_sep(&self) -> bool {
2788+
self.as_os_str().as_encoded_bytes().last().copied().is_some_and(is_sep_byte)
2789+
}
2790+
2791+
/// Ensures that a path has a trailing [separator](MAIN_SEPARATOR),
2792+
/// allocating a [`PathBuf`] if necessary.
2793+
///
2794+
/// The resulting path will return true for [`has_trailing_sep`](Self::has_trailing_sep) and
2795+
/// `None` for [`file_name`](Self::file_name).
2796+
///
2797+
/// # Examples
2798+
///
2799+
/// ```
2800+
/// #![feature(path_trailing_sep)]
2801+
/// use std::path::Path;
2802+
///
2803+
/// assert_eq!(Path::new("dir//").with_trailing_sep().file_name(), None);
2804+
/// assert_eq!(Path::new("dir/").with_trailing_sep().file_name(), None);
2805+
/// assert_eq!(Path::new("dir").with_trailing_sep().file_name(), None);
2806+
/// assert_eq!(Path::new("dir").file_name(), Some("dir"));
2807+
/// ```
2808+
#[unstable(feature = "path_trailing_sep", issue = "142503")]
2809+
#[must_use]
2810+
#[inline]
2811+
pub fn with_trailing_sep(&self) -> Cow<'_, Path> {
2812+
if self.has_trailing_sep() { Cow::Borrowed(self) } else { Cow::Owned(self.join("")) }
2813+
}
2814+
2815+
/// Trims a trailing [separator](MAIN_SEPARATOR) from a path, if possible.
2816+
///
2817+
/// The resulting path will return false for [`has_trailing_sep`](Self::has_trailing_sep).
2818+
///
2819+
/// # Examples
2820+
///
2821+
/// ```
2822+
/// #![feature(path_trailing_sep)]
2823+
/// use std::path::Path;
2824+
///
2825+
/// assert_eq!(Path::new("dir//").trim_trailing_sep().file_name(), Some("dir"));
2826+
/// assert_eq!(Path::new("dir/").trim_trailing_sep().file_name(), Some("dir"));
2827+
/// assert_eq!(Path::new("dir").trim_trailing_sep().file_name(), Some("dir"));
2828+
/// ```
2829+
#[unstable(feature = "path_trailing_sep", issue = "142503")]
2830+
#[must_use]
2831+
#[inline]
2832+
pub fn trim_trailing_sep(&self) -> &Path {
2833+
if self.has_trailing_sep() && (!self.has_root() || self.parent().is_some()) {
2834+
let mut bytes = self.inner.as_encoded_bytes();
2835+
while let Some((last, init)) = bytes.split_last()
2836+
&& is_sep_byte(*last)
2837+
{
2838+
bytes = init;
2839+
}
2840+
2841+
// SAFETY: Trimming trailing ASCII bytes will retain the validity of the string.
2842+
Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) })
2843+
} else {
2844+
self
2845+
}
2846+
}
2847+
26892848
/// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
26902849
///
26912850
/// If `path` is absolute, it replaces the current path.

0 commit comments

Comments
 (0)