std/path.rs
1//! Cross-platform path manipulation.
2//!
3//! This module provides two types, [`PathBuf`] and [`Path`] (akin to [`String`]
4//! and [`str`]), for working with paths abstractly. These types are thin wrappers
5//! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
6//! on strings according to the local platform's path syntax.
7//!
8//! Paths can be parsed into [`Component`]s by iterating over the structure
9//! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
10//! correspond to the substrings between path separators (`/` or `\`). You can
11//! reconstruct an equivalent path from components with the [`push`] method on
12//! [`PathBuf`]; note that the paths may differ syntactically by the
13//! normalization described in the documentation for the [`components`] method.
14//!
15//! ## Case sensitivity
16//!
17//! Unless otherwise indicated path methods that do not access the filesystem,
18//! such as [`Path::starts_with`] and [`Path::ends_with`], are case sensitive no
19//! matter the platform or filesystem. An exception to this is made for Windows
20//! drive letters.
21//!
22//! ## Path normalization
23//!
24//! Several methods in this module perform basic path normalization by disregarding
25//! repeated separators, non-leading `.` components, and trailing separators. These include:
26//! - Methods for iteration, such as [`Path::components`] and [`Path::iter`]
27//! - Methods for inspection, such as [`Path::has_root`]
28//! - Comparisons using [`PartialEq`], [`PartialOrd`], and [`Ord`]
29//!
30//! [`Path::join`] and [`PathBuf::push`] also disregard trailing slashes.
31//!
32// FIXME(normalize_lexically): mention normalize_lexically once stable
33//! These methods **do not** resolve `..` components or symlinks. For full normalization
34//! including `..` resolution, use [`Path::canonicalize`] (which does access the filesystem).
35//!
36//! ## Simple usage
37//!
38//! Path manipulation includes both parsing components from slices and building
39//! new owned paths.
40//!
41//! To parse a path, you can create a [`Path`] slice from a [`str`]
42//! slice and start asking questions:
43//!
44//! ```
45//! use std::path::Path;
46//! use std::ffi::OsStr;
47//!
48//! let path = Path::new("/tmp/foo/bar.txt");
49//!
50//! let parent = path.parent();
51//! assert_eq!(parent, Some(Path::new("/tmp/foo")));
52//!
53//! let file_stem = path.file_stem();
54//! assert_eq!(file_stem, Some(OsStr::new("bar")));
55//!
56//! let extension = path.extension();
57//! assert_eq!(extension, Some(OsStr::new("txt")));
58//! ```
59//!
60//! To build or modify paths, use [`PathBuf`]:
61//!
62//! ```
63//! use std::path::PathBuf;
64//!
65//! // This way works...
66//! let mut path = PathBuf::from("c:\\");
67//!
68//! path.push("windows");
69//! path.push("system32");
70//!
71//! path.set_extension("dll");
72//!
73//! // ... but push is best used if you don't know everything up
74//! // front. If you do, this way is better:
75//! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
76//! ```
77//!
78//! [`components`]: Path::components
79//! [`push`]: PathBuf::push
80
81#![stable(feature = "rust1", since = "1.0.0")]
82#![deny(unsafe_op_in_unsafe_fn)]
83
84use core::clone::CloneToUninit;
85
86use crate::alloc::Allocator;
87use crate::borrow::{Borrow, Cow};
88use crate::collections::TryReserveError;
89use crate::error::Error;
90use crate::ffi::{OsStr, OsString, os_str};
91use crate::hash::{Hash, Hasher};
92use crate::iter::FusedIterator;
93use crate::ops::{self, Deref};
94use crate::rc::Rc;
95use crate::str::FromStr;
96use crate::sync::Arc;
97use crate::sys::path::{HAS_PREFIXES, is_sep_byte, is_verbatim_sep, parse_prefix};
98use crate::{cmp, fmt, fs, io, sys};
99
100////////////////////////////////////////////////////////////////////////////////
101// GENERAL NOTES
102////////////////////////////////////////////////////////////////////////////////
103//
104// Parsing in this module is done by directly transmuting OsStr to [u8] slices,
105// taking advantage of the fact that OsStr always encodes ASCII characters
106// as-is. Eventually, this transmutation should be replaced by direct uses of
107// OsStr APIs for parsing, but it will take a while for those to become
108// available.
109
110////////////////////////////////////////////////////////////////////////////////
111// Windows Prefixes
112////////////////////////////////////////////////////////////////////////////////
113
114/// Windows path prefixes, e.g., `C:` or `\\server\share`.
115///
116/// Windows uses a variety of path prefix styles, including references to drive
117/// volumes (like `C:`), network shared folders (like `\\server\share`), and
118/// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
119/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
120/// no normalization is performed.
121///
122/// # Examples
123///
124/// ```
125/// use std::path::{Component, Path, Prefix};
126/// use std::path::Prefix::*;
127/// use std::ffi::OsStr;
128///
129/// fn get_path_prefix(s: &str) -> Prefix<'_> {
130/// let path = Path::new(s);
131/// match path.components().next().unwrap() {
132/// Component::Prefix(prefix_component) => prefix_component.kind(),
133/// _ => panic!(),
134/// }
135/// }
136///
137/// # if cfg!(windows) {
138/// assert_eq!(Verbatim(OsStr::new("pictures")),
139/// get_path_prefix(r"\\?\pictures\kittens"));
140/// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
141/// get_path_prefix(r"\\?\UNC\server\share"));
142/// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
143/// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
144/// get_path_prefix(r"\\.\BrainInterface"));
145/// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
146/// get_path_prefix(r"\\server\share"));
147/// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
148/// # }
149/// ```
150#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
151#[stable(feature = "rust1", since = "1.0.0")]
152pub enum Prefix<'a> {
153 /// Verbatim prefix, e.g., `\\?\cat_pics`.
154 ///
155 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
156 /// component.
157 #[stable(feature = "rust1", since = "1.0.0")]
158 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
159
160 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
161 /// e.g., `\\?\UNC\server\share`.
162 ///
163 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
164 /// server's hostname and a share name.
165 #[stable(feature = "rust1", since = "1.0.0")]
166 VerbatimUNC(
167 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
168 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
169 ),
170
171 /// Verbatim disk prefix, e.g., `\\?\C:`.
172 ///
173 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
174 /// drive letter and `:`.
175 #[stable(feature = "rust1", since = "1.0.0")]
176 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
177
178 /// Device namespace prefix, e.g., `\\.\COM42`.
179 ///
180 /// Device namespace prefixes consist of `\\.\` (possibly using `/`
181 /// instead of `\`), immediately followed by the device name.
182 #[stable(feature = "rust1", since = "1.0.0")]
183 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
184
185 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
186 /// `\\server\share`.
187 ///
188 /// UNC prefixes consist of the server's hostname and a share name.
189 #[stable(feature = "rust1", since = "1.0.0")]
190 UNC(
191 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
192 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
193 ),
194
195 /// Prefix `C:` for the given disk drive.
196 #[stable(feature = "rust1", since = "1.0.0")]
197 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
198}
199
200impl<'a> Prefix<'a> {
201 #[inline]
202 fn len(&self) -> usize {
203 use self::Prefix::*;
204 fn os_str_len(s: &OsStr) -> usize {
205 s.as_encoded_bytes().len()
206 }
207 match *self {
208 Verbatim(x) => 4 + os_str_len(x),
209 VerbatimUNC(x, y) => {
210 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
211 }
212 VerbatimDisk(_) => 6,
213 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
214 DeviceNS(x) => 4 + os_str_len(x),
215 Disk(_) => 2,
216 }
217 }
218
219 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
220 ///
221 /// # Examples
222 ///
223 /// ```
224 /// use std::path::Prefix::*;
225 /// use std::ffi::OsStr;
226 ///
227 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
228 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
229 /// assert!(VerbatimDisk(b'C').is_verbatim());
230 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
231 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
232 /// assert!(!Disk(b'C').is_verbatim());
233 /// ```
234 #[inline]
235 #[must_use]
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn is_verbatim(&self) -> bool {
238 use self::Prefix::*;
239 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
240 }
241
242 #[inline]
243 fn is_drive(&self) -> bool {
244 matches!(*self, Prefix::Disk(_))
245 }
246
247 #[inline]
248 fn has_implicit_root(&self) -> bool {
249 !self.is_drive()
250 }
251}
252
253////////////////////////////////////////////////////////////////////////////////
254// Exposed parsing helpers
255////////////////////////////////////////////////////////////////////////////////
256
257/// Determines whether the character is one of the permitted path
258/// separators for the current platform.
259///
260/// # Examples
261///
262/// ```
263/// use std::path;
264///
265/// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
266/// assert!(!path::is_separator('❤'));
267/// ```
268#[must_use]
269#[stable(feature = "rust1", since = "1.0.0")]
270#[rustc_const_unstable(feature = "const_path_separators", issue = "153106")]
271pub const fn is_separator(c: char) -> bool {
272 c.is_ascii() && is_sep_byte(c as u8)
273}
274
275/// All path separators recognized on the current platform, represented as [`char`]s; for example,
276/// this is `&['/'][..]` on Unix and `&['\\', '/'][..]` on Windows. The [primary
277/// separator](MAIN_SEPARATOR) is always element 0 of the slice.
278#[unstable(feature = "const_path_separators", issue = "153106")]
279pub const SEPARATORS: &[char] = crate::sys::path::SEPARATORS;
280
281/// All path separators recognized on the current platform, represented as [`&str`]s; for example,
282/// this is `&["/"][..]` on Unix and `&["\\", "/"][..]` on Windows. The [primary
283/// separator](MAIN_SEPARATOR_STR) is always element 0 of the slice.
284#[unstable(feature = "const_path_separators", issue = "153106")]
285pub const SEPARATORS_STR: &[&str] = crate::sys::path::SEPARATORS_STR;
286
287/// The primary separator of path components for the current platform, represented as a [`char`];
288/// for example, this is `'/'` on Unix and `'\\'` on Windows.
289#[stable(feature = "rust1", since = "1.0.0")]
290#[cfg_attr(not(test), rustc_diagnostic_item = "path_main_separator")]
291pub const MAIN_SEPARATOR: char = SEPARATORS[0];
292
293/// The primary separator of path components for the current platform, represented as a [`&str`];
294/// for example, this is `"/"` on Unix and `"\\"` on Windows.
295#[stable(feature = "main_separator_str", since = "1.68.0")]
296pub const MAIN_SEPARATOR_STR: &str = SEPARATORS_STR[0];
297
298////////////////////////////////////////////////////////////////////////////////
299// Misc helpers
300////////////////////////////////////////////////////////////////////////////////
301
302// Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
303// is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
304// `iter` after having exhausted `prefix`.
305fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
306where
307 I: Iterator<Item = Component<'a>> + Clone,
308 J: Iterator<Item = Component<'b>>,
309{
310 loop {
311 let mut iter_next = iter.clone();
312 match (iter_next.next(), prefix.next()) {
313 (Some(ref x), Some(ref y)) if x == y => (),
314 (Some(_), Some(_)) => return None,
315 (Some(_), None) => return Some(iter),
316 (None, None) => return Some(iter),
317 (None, Some(_)) => return None,
318 }
319 iter = iter_next;
320 }
321}
322
323////////////////////////////////////////////////////////////////////////////////
324// Cross-platform, iterator-independent parsing
325////////////////////////////////////////////////////////////////////////////////
326
327/// Says whether the first byte after the prefix is a separator.
328fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
329 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
330 !path.is_empty() && is_sep_byte(path[0])
331}
332
333// basic workhorse for splitting stem and extension
334fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
335 if file.as_encoded_bytes() == b".." {
336 return (Some(file), None);
337 }
338
339 // The unsafety here stems from converting between &OsStr and &[u8]
340 // and back. This is safe to do because (1) we only look at ASCII
341 // contents of the encoding and (2) new &OsStr values are produced
342 // only from ASCII-bounded slices of existing &OsStr values.
343 let mut iter = file.as_encoded_bytes().rsplitn(2, |b| *b == b'.');
344 let after = iter.next();
345 let before = iter.next();
346 if before == Some(b"") {
347 (Some(file), None)
348 } else {
349 unsafe {
350 (
351 before.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
352 after.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
353 )
354 }
355 }
356}
357
358fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
359 let slice = file.as_encoded_bytes();
360 if slice == b".." {
361 return (file, None);
362 }
363
364 // The unsafety here stems from converting between &OsStr and &[u8]
365 // and back. This is safe to do because (1) we only look at ASCII
366 // contents of the encoding and (2) new &OsStr values are produced
367 // only from ASCII-bounded slices of existing &OsStr values.
368 let i = match slice[1..].iter().position(|b| *b == b'.') {
369 Some(i) => i + 1,
370 None => return (file, None),
371 };
372 let before = &slice[..i];
373 let after = &slice[i + 1..];
374 unsafe {
375 (
376 OsStr::from_encoded_bytes_unchecked(before),
377 Some(OsStr::from_encoded_bytes_unchecked(after)),
378 )
379 }
380}
381
382/// Checks whether the string is valid as a file extension, or panics otherwise.
383fn validate_extension(extension: &OsStr) {
384 for &b in extension.as_encoded_bytes() {
385 if is_sep_byte(b) {
386 panic!("extension cannot contain path separators: {extension:?}");
387 }
388 }
389}
390
391////////////////////////////////////////////////////////////////////////////////
392// The core iterators
393////////////////////////////////////////////////////////////////////////////////
394
395/// Component parsing works by a double-ended state machine; the cursors at the
396/// front and back of the path each keep track of what parts of the path have
397/// been consumed so far.
398///
399/// Going front to back, a path is made up of a prefix, a starting
400/// directory component, and a body (of normal components)
401#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
402enum State {
403 Prefix = 0, // c:
404 StartDir = 1, // / or . or nothing
405 Body = 2, // foo/bar/baz
406 Done = 3,
407}
408
409/// A structure wrapping a Windows path prefix as well as its unparsed string
410/// representation.
411///
412/// In addition to the parsed [`Prefix`] information returned by [`kind`],
413/// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
414/// returned by [`as_os_str`].
415///
416/// Instances of this `struct` can be obtained by matching against the
417/// [`Prefix` variant] on [`Component`].
418///
419/// Does not occur on Unix.
420///
421/// # Examples
422///
423/// ```
424/// # if cfg!(windows) {
425/// use std::path::{Component, Path, Prefix};
426/// use std::ffi::OsStr;
427///
428/// let path = Path::new(r"c:\you\later\");
429/// match path.components().next().unwrap() {
430/// Component::Prefix(prefix_component) => {
431/// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
432/// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
433/// }
434/// _ => unreachable!(),
435/// }
436/// # }
437/// ```
438///
439/// [`as_os_str`]: PrefixComponent::as_os_str
440/// [`kind`]: PrefixComponent::kind
441/// [`Prefix` variant]: Component::Prefix
442#[stable(feature = "rust1", since = "1.0.0")]
443#[derive(Copy, Clone, Eq, Debug)]
444pub struct PrefixComponent<'a> {
445 /// The prefix as an unparsed `OsStr` slice.
446 raw: &'a OsStr,
447
448 /// The parsed prefix data.
449 parsed: Prefix<'a>,
450}
451
452impl<'a> PrefixComponent<'a> {
453 /// Returns the parsed prefix data.
454 ///
455 /// See [`Prefix`]'s documentation for more information on the different
456 /// kinds of prefixes.
457 #[stable(feature = "rust1", since = "1.0.0")]
458 #[must_use]
459 #[inline]
460 pub fn kind(&self) -> Prefix<'a> {
461 self.parsed
462 }
463
464 /// Returns the raw [`OsStr`] slice for this prefix.
465 #[stable(feature = "rust1", since = "1.0.0")]
466 #[must_use]
467 #[inline]
468 pub fn as_os_str(&self) -> &'a OsStr {
469 self.raw
470 }
471}
472
473#[stable(feature = "rust1", since = "1.0.0")]
474impl<'a> PartialEq for PrefixComponent<'a> {
475 #[inline]
476 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
477 self.parsed == other.parsed
478 }
479}
480
481#[stable(feature = "rust1", since = "1.0.0")]
482impl<'a> PartialOrd for PrefixComponent<'a> {
483 #[inline]
484 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
485 PartialOrd::partial_cmp(&self.parsed, &other.parsed)
486 }
487}
488
489#[stable(feature = "rust1", since = "1.0.0")]
490impl Ord for PrefixComponent<'_> {
491 #[inline]
492 fn cmp(&self, other: &Self) -> cmp::Ordering {
493 Ord::cmp(&self.parsed, &other.parsed)
494 }
495}
496
497#[stable(feature = "rust1", since = "1.0.0")]
498impl Hash for PrefixComponent<'_> {
499 fn hash<H: Hasher>(&self, h: &mut H) {
500 self.parsed.hash(h);
501 }
502}
503
504/// A single component of a path.
505///
506/// A `Component` roughly corresponds to a substring between path separators
507/// (`/` or `\`).
508///
509/// This `enum` is created by iterating over [`Components`], which in turn is
510/// created by the [`components`](Path::components) method on [`Path`].
511///
512/// # Examples
513///
514/// ```rust
515/// use std::path::{Component, Path};
516///
517/// let path = Path::new("/tmp/foo/bar.txt");
518/// let components = path.components().collect::<Vec<_>>();
519/// assert_eq!(&components, &[
520/// Component::RootDir,
521/// Component::Normal("tmp".as_ref()),
522/// Component::Normal("foo".as_ref()),
523/// Component::Normal("bar.txt".as_ref()),
524/// ]);
525/// ```
526#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
527#[stable(feature = "rust1", since = "1.0.0")]
528pub enum Component<'a> {
529 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
530 ///
531 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
532 /// for more.
533 ///
534 /// Does not occur on Unix.
535 #[stable(feature = "rust1", since = "1.0.0")]
536 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
537
538 /// The root directory component, appears after any prefix and before anything else.
539 ///
540 /// It represents a separator that designates that a path starts from root.
541 #[stable(feature = "rust1", since = "1.0.0")]
542 RootDir,
543
544 /// A reference to the current directory, i.e., `.`.
545 #[stable(feature = "rust1", since = "1.0.0")]
546 CurDir,
547
548 /// A reference to the parent directory, i.e., `..`.
549 #[stable(feature = "rust1", since = "1.0.0")]
550 ParentDir,
551
552 /// A normal component, e.g., `a` and `b` in `a/b`.
553 ///
554 /// This variant is the most common one, it represents references to files
555 /// or directories.
556 #[stable(feature = "rust1", since = "1.0.0")]
557 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
558}
559
560impl<'a> Component<'a> {
561 /// Extracts the underlying [`OsStr`] slice.
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// use std::path::Path;
567 ///
568 /// let path = Path::new("./tmp/foo/bar.txt");
569 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
570 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
571 /// ```
572 #[must_use = "`self` will be dropped if the result is not used"]
573 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn as_os_str(self) -> &'a OsStr {
575 match self {
576 Component::Prefix(p) => p.as_os_str(),
577 Component::RootDir => OsStr::new(MAIN_SEPARATOR_STR),
578 Component::CurDir => OsStr::new("."),
579 Component::ParentDir => OsStr::new(".."),
580 Component::Normal(path) => path,
581 }
582 }
583}
584
585#[stable(feature = "rust1", since = "1.0.0")]
586impl AsRef<OsStr> for Component<'_> {
587 #[inline]
588 fn as_ref(&self) -> &OsStr {
589 self.as_os_str()
590 }
591}
592
593#[stable(feature = "path_component_asref", since = "1.25.0")]
594impl AsRef<Path> for Component<'_> {
595 #[inline]
596 fn as_ref(&self) -> &Path {
597 self.as_os_str().as_ref()
598 }
599}
600
601/// An iterator over the [`Component`]s of a [`Path`].
602///
603/// This `struct` is created by the [`components`] method on [`Path`].
604/// See its documentation for more.
605///
606/// # Examples
607///
608/// ```
609/// use std::path::Path;
610///
611/// let path = Path::new("/tmp/foo/bar.txt");
612///
613/// for component in path.components() {
614/// println!("{component:?}");
615/// }
616/// ```
617///
618/// [`components`]: Path::components
619#[derive(Clone)]
620#[must_use = "iterators are lazy and do nothing unless consumed"]
621#[stable(feature = "rust1", since = "1.0.0")]
622pub struct Components<'a> {
623 // The path left to parse components from
624 path: &'a [u8],
625
626 // The prefix as it was originally parsed, if any
627 prefix: Option<Prefix<'a>>,
628
629 // true if path *physically* has a root separator; for most Windows
630 // prefixes, it may have a "logical" root separator for the purposes of
631 // normalization, e.g., \\server\share == \\server\share\.
632 has_physical_root: bool,
633
634 // The iterator is double-ended, and these two states keep track of what has
635 // been produced from either end
636 front: State,
637 back: State,
638}
639
640/// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
641///
642/// This `struct` is created by the [`iter`] method on [`Path`].
643/// See its documentation for more.
644///
645/// [`iter`]: Path::iter
646#[derive(Clone)]
647#[must_use = "iterators are lazy and do nothing unless consumed"]
648#[stable(feature = "rust1", since = "1.0.0")]
649pub struct Iter<'a> {
650 inner: Components<'a>,
651}
652
653#[stable(feature = "path_components_debug", since = "1.13.0")]
654impl fmt::Debug for Components<'_> {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 struct DebugHelper<'a>(&'a Path);
657
658 impl fmt::Debug for DebugHelper<'_> {
659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660 f.debug_list().entries(self.0.components()).finish()
661 }
662 }
663
664 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
665 }
666}
667
668impl<'a> Components<'a> {
669 // how long is the prefix, if any?
670 #[inline]
671 fn prefix_len(&self) -> usize {
672 if !HAS_PREFIXES {
673 return 0;
674 }
675 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
676 }
677
678 #[inline]
679 fn prefix_verbatim(&self) -> bool {
680 if !HAS_PREFIXES {
681 return false;
682 }
683 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
684 }
685
686 /// how much of the prefix is left from the point of view of iteration?
687 #[inline]
688 fn prefix_remaining(&self) -> usize {
689 if !HAS_PREFIXES {
690 return 0;
691 }
692 if self.front == State::Prefix { self.prefix_len() } else { 0 }
693 }
694
695 // Given the iteration so far, how much of the pre-State::Body path is left?
696 #[inline]
697 fn len_before_body(&self) -> usize {
698 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
699 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
700 self.prefix_remaining() + root + cur_dir
701 }
702
703 // is the iteration complete?
704 #[inline]
705 fn finished(&self) -> bool {
706 self.front == State::Done || self.back == State::Done || self.front > self.back
707 }
708
709 #[inline]
710 fn is_sep_byte(&self, b: u8) -> bool {
711 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
712 }
713
714 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
715 ///
716 /// # Examples
717 ///
718 /// ```
719 /// use std::path::Path;
720 ///
721 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
722 /// components.next();
723 /// components.next();
724 ///
725 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
726 /// ```
727 #[must_use]
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn as_path(&self) -> &'a Path {
730 let mut comps = self.clone();
731 if comps.front == State::Body {
732 comps.trim_left();
733 }
734 if comps.back == State::Body {
735 comps.trim_right();
736 }
737 unsafe { Path::from_u8_slice(comps.path) }
738 }
739
740 /// Is the *original* path rooted?
741 fn has_root(&self) -> bool {
742 if self.has_physical_root {
743 return true;
744 }
745 if HAS_PREFIXES && let Some(p) = self.prefix {
746 if p.has_implicit_root() {
747 return true;
748 }
749 }
750 false
751 }
752
753 /// Should the normalized path include a leading . ?
754 fn include_cur_dir(&self) -> bool {
755 if self.has_root() {
756 return false;
757 }
758 let slice = &self.path[self.prefix_remaining()..];
759 match slice {
760 [b'.'] => true,
761 [b'.', b, ..] => self.is_sep_byte(*b),
762 _ => false,
763 }
764 }
765
766 // parse a given byte sequence following the OsStr encoding into the
767 // corresponding path component
768 unsafe fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
769 match comp {
770 b"." if HAS_PREFIXES && self.prefix_verbatim() => Some(Component::CurDir),
771 b"." => None, // . components are normalized away, except at
772 // the beginning of a path, which is treated
773 // separately via `include_cur_dir`
774 b".." => Some(Component::ParentDir),
775 b"" => None,
776 _ => Some(Component::Normal(unsafe { OsStr::from_encoded_bytes_unchecked(comp) })),
777 }
778 }
779
780 // parse a component from the left, saying how many bytes to consume to
781 // remove the component
782 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
783 debug_assert!(self.front == State::Body);
784 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
785 None => (0, self.path),
786 Some(i) => (1, &self.path[..i]),
787 };
788 // SAFETY: `comp` is a valid substring, since it is split on a separator.
789 (comp.len() + extra, unsafe { self.parse_single_component(comp) })
790 }
791
792 // parse a component from the right, saying how many bytes to consume to
793 // remove the component
794 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
795 debug_assert!(self.back == State::Body);
796 let start = self.len_before_body();
797 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
798 None => (0, &self.path[start..]),
799 Some(i) => (1, &self.path[start + i + 1..]),
800 };
801 // SAFETY: `comp` is a valid substring, since it is split on a separator.
802 (comp.len() + extra, unsafe { self.parse_single_component(comp) })
803 }
804
805 // trim away repeated separators (i.e., empty components) on the left
806 fn trim_left(&mut self) {
807 while !self.path.is_empty() {
808 let (size, comp) = self.parse_next_component();
809 if comp.is_some() {
810 return;
811 } else {
812 self.path = &self.path[size..];
813 }
814 }
815 }
816
817 // trim away repeated separators (i.e., empty components) on the right
818 fn trim_right(&mut self) {
819 while self.path.len() > self.len_before_body() {
820 let (size, comp) = self.parse_next_component_back();
821 if comp.is_some() {
822 return;
823 } else {
824 self.path = &self.path[..self.path.len() - size];
825 }
826 }
827 }
828}
829
830#[stable(feature = "rust1", since = "1.0.0")]
831impl AsRef<Path> for Components<'_> {
832 #[inline]
833 fn as_ref(&self) -> &Path {
834 self.as_path()
835 }
836}
837
838#[stable(feature = "rust1", since = "1.0.0")]
839impl AsRef<OsStr> for Components<'_> {
840 #[inline]
841 fn as_ref(&self) -> &OsStr {
842 self.as_path().as_os_str()
843 }
844}
845
846#[stable(feature = "path_iter_debug", since = "1.13.0")]
847impl fmt::Debug for Iter<'_> {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 struct DebugHelper<'a>(&'a Path);
850
851 impl fmt::Debug for DebugHelper<'_> {
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 f.debug_list().entries(self.0.iter()).finish()
854 }
855 }
856
857 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
858 }
859}
860
861impl<'a> Iter<'a> {
862 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
863 ///
864 /// # Examples
865 ///
866 /// ```
867 /// use std::path::Path;
868 ///
869 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
870 /// iter.next();
871 /// iter.next();
872 ///
873 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
874 /// ```
875 #[stable(feature = "rust1", since = "1.0.0")]
876 #[must_use]
877 #[inline]
878 pub fn as_path(&self) -> &'a Path {
879 self.inner.as_path()
880 }
881}
882
883#[stable(feature = "rust1", since = "1.0.0")]
884impl AsRef<Path> for Iter<'_> {
885 #[inline]
886 fn as_ref(&self) -> &Path {
887 self.as_path()
888 }
889}
890
891#[stable(feature = "rust1", since = "1.0.0")]
892impl AsRef<OsStr> for Iter<'_> {
893 #[inline]
894 fn as_ref(&self) -> &OsStr {
895 self.as_path().as_os_str()
896 }
897}
898
899#[stable(feature = "rust1", since = "1.0.0")]
900impl<'a> Iterator for Iter<'a> {
901 type Item = &'a OsStr;
902
903 #[inline]
904 fn next(&mut self) -> Option<&'a OsStr> {
905 self.inner.next().map(Component::as_os_str)
906 }
907}
908
909#[stable(feature = "rust1", since = "1.0.0")]
910impl<'a> DoubleEndedIterator for Iter<'a> {
911 #[inline]
912 fn next_back(&mut self) -> Option<&'a OsStr> {
913 self.inner.next_back().map(Component::as_os_str)
914 }
915}
916
917#[stable(feature = "fused", since = "1.26.0")]
918impl FusedIterator for Iter<'_> {}
919
920#[stable(feature = "rust1", since = "1.0.0")]
921impl<'a> Iterator for Components<'a> {
922 type Item = Component<'a>;
923
924 fn next(&mut self) -> Option<Component<'a>> {
925 while !self.finished() {
926 match self.front {
927 // most likely case first
928 State::Body if !self.path.is_empty() => {
929 let (size, comp) = self.parse_next_component();
930 self.path = &self.path[size..];
931 if comp.is_some() {
932 return comp;
933 }
934 }
935 State::Body => {
936 self.front = State::Done;
937 }
938 State::StartDir => {
939 self.front = State::Body;
940 if self.has_physical_root {
941 debug_assert!(!self.path.is_empty());
942 self.path = &self.path[1..];
943 return Some(Component::RootDir);
944 } else if HAS_PREFIXES && let Some(p) = self.prefix {
945 if p.has_implicit_root() && !p.is_verbatim() {
946 return Some(Component::RootDir);
947 }
948 } else if self.include_cur_dir() {
949 debug_assert!(!self.path.is_empty());
950 self.path = &self.path[1..];
951 return Some(Component::CurDir);
952 }
953 }
954 _ if const { !HAS_PREFIXES } => unreachable!(),
955 State::Prefix if self.prefix_len() == 0 => {
956 self.front = State::StartDir;
957 }
958 State::Prefix => {
959 self.front = State::StartDir;
960 debug_assert!(self.prefix_len() <= self.path.len());
961 let raw = &self.path[..self.prefix_len()];
962 self.path = &self.path[self.prefix_len()..];
963 return Some(Component::Prefix(PrefixComponent {
964 raw: unsafe { OsStr::from_encoded_bytes_unchecked(raw) },
965 parsed: self.prefix.unwrap(),
966 }));
967 }
968 State::Done => unreachable!(),
969 }
970 }
971 None
972 }
973}
974
975#[stable(feature = "rust1", since = "1.0.0")]
976impl<'a> DoubleEndedIterator for Components<'a> {
977 fn next_back(&mut self) -> Option<Component<'a>> {
978 while !self.finished() {
979 match self.back {
980 State::Body if self.path.len() > self.len_before_body() => {
981 let (size, comp) = self.parse_next_component_back();
982 self.path = &self.path[..self.path.len() - size];
983 if comp.is_some() {
984 return comp;
985 }
986 }
987 State::Body => {
988 self.back = State::StartDir;
989 }
990 State::StartDir => {
991 self.back = if HAS_PREFIXES { State::Prefix } else { State::Done };
992 if self.has_physical_root {
993 self.path = &self.path[..self.path.len() - 1];
994 return Some(Component::RootDir);
995 } else if HAS_PREFIXES && let Some(p) = self.prefix {
996 if p.has_implicit_root() && !p.is_verbatim() {
997 return Some(Component::RootDir);
998 }
999 } else if self.include_cur_dir() {
1000 self.path = &self.path[..self.path.len() - 1];
1001 return Some(Component::CurDir);
1002 }
1003 }
1004 _ if !HAS_PREFIXES => unreachable!(),
1005 State::Prefix if self.prefix_len() > 0 => {
1006 self.back = State::Done;
1007 return Some(Component::Prefix(PrefixComponent {
1008 raw: unsafe { OsStr::from_encoded_bytes_unchecked(self.path) },
1009 parsed: self.prefix.unwrap(),
1010 }));
1011 }
1012 State::Prefix => {
1013 self.back = State::Done;
1014 return None;
1015 }
1016 State::Done => unreachable!(),
1017 }
1018 }
1019 None
1020 }
1021}
1022
1023#[stable(feature = "fused", since = "1.26.0")]
1024impl FusedIterator for Components<'_> {}
1025
1026#[stable(feature = "rust1", since = "1.0.0")]
1027impl<'a> PartialEq for Components<'a> {
1028 #[inline]
1029 fn eq(&self, other: &Components<'a>) -> bool {
1030 let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ } = self;
1031
1032 // Fast path for exact matches, e.g. for hashmap lookups.
1033 // Don't explicitly compare the prefix or has_physical_root fields since they'll
1034 // either be covered by the `path` buffer or are only relevant for `prefix_verbatim()`.
1035 if self.path.len() == other.path.len()
1036 && self.front == other.front
1037 && self.back == State::Body
1038 && other.back == State::Body
1039 && self.prefix_verbatim() == other.prefix_verbatim()
1040 {
1041 // possible future improvement: this could bail out earlier if there were a
1042 // reverse memcmp/bcmp comparing back to front
1043 if self.path == other.path {
1044 return true;
1045 }
1046 }
1047
1048 // compare back to front since absolute paths often share long prefixes
1049 Iterator::eq(self.clone().rev(), other.clone().rev())
1050 }
1051}
1052
1053#[stable(feature = "rust1", since = "1.0.0")]
1054impl Eq for Components<'_> {}
1055
1056#[stable(feature = "rust1", since = "1.0.0")]
1057impl<'a> PartialOrd for Components<'a> {
1058 #[inline]
1059 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1060 Some(compare_components(self.clone(), other.clone()))
1061 }
1062}
1063
1064#[stable(feature = "rust1", since = "1.0.0")]
1065impl Ord for Components<'_> {
1066 #[inline]
1067 fn cmp(&self, other: &Self) -> cmp::Ordering {
1068 compare_components(self.clone(), other.clone())
1069 }
1070}
1071
1072fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
1073 // Fast path for long shared prefixes
1074 //
1075 // - compare raw bytes to find first mismatch
1076 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1077 // - if found update state to only do a component-wise comparison on the remainder,
1078 // otherwise do it on the full path
1079 //
1080 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1081 // the middle of one
1082 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1083 // possible future improvement: a [u8]::first_mismatch simd implementation
1084 let first_difference = match left.path.iter().zip(right.path).position(|(&a, &b)| a != b) {
1085 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1086 None => left.path.len().min(right.path.len()),
1087 Some(diff) => diff,
1088 };
1089
1090 if let Some(previous_sep) =
1091 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1092 {
1093 let mismatched_component_start = previous_sep + 1;
1094 left.path = &left.path[mismatched_component_start..];
1095 left.front = State::Body;
1096 right.path = &right.path[mismatched_component_start..];
1097 right.front = State::Body;
1098 }
1099 }
1100
1101 Iterator::cmp(left, right)
1102}
1103
1104/// An iterator over [`Path`] and its ancestors.
1105///
1106/// This `struct` is created by the [`ancestors`] method on [`Path`].
1107/// See its documentation for more.
1108///
1109/// # Examples
1110///
1111/// ```
1112/// use std::path::Path;
1113///
1114/// let path = Path::new("/foo/bar");
1115///
1116/// for ancestor in path.ancestors() {
1117/// println!("{}", ancestor.display());
1118/// }
1119/// ```
1120///
1121/// [`ancestors`]: Path::ancestors
1122#[derive(Copy, Clone, Debug)]
1123#[must_use = "iterators are lazy and do nothing unless consumed"]
1124#[stable(feature = "path_ancestors", since = "1.28.0")]
1125pub struct Ancestors<'a> {
1126 next: Option<&'a Path>,
1127}
1128
1129#[stable(feature = "path_ancestors", since = "1.28.0")]
1130impl<'a> Iterator for Ancestors<'a> {
1131 type Item = &'a Path;
1132
1133 #[inline]
1134 fn next(&mut self) -> Option<Self::Item> {
1135 let next = self.next;
1136 self.next = next.and_then(Path::parent);
1137 next
1138 }
1139}
1140
1141#[stable(feature = "path_ancestors", since = "1.28.0")]
1142impl FusedIterator for Ancestors<'_> {}
1143
1144////////////////////////////////////////////////////////////////////////////////
1145// Basic types and traits
1146////////////////////////////////////////////////////////////////////////////////
1147
1148/// An owned, mutable path (akin to [`String`]).
1149///
1150/// This type provides methods like [`push`] and [`set_extension`] that mutate
1151/// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1152/// all methods on [`Path`] slices are available on `PathBuf` values as well.
1153///
1154/// [`push`]: PathBuf::push
1155/// [`set_extension`]: PathBuf::set_extension
1156///
1157/// More details about the overall approach can be found in
1158/// the [module documentation](self).
1159///
1160/// # Examples
1161///
1162/// You can use [`push`] to build up a `PathBuf` from
1163/// components:
1164///
1165/// ```
1166/// use std::path::PathBuf;
1167///
1168/// let mut path = PathBuf::new();
1169///
1170/// path.push(r"C:\");
1171/// path.push("windows");
1172/// path.push("system32");
1173///
1174/// path.set_extension("dll");
1175/// ```
1176///
1177/// However, [`push`] is best used for dynamic situations. This is a better way
1178/// to do this when you know all of the components ahead of time:
1179///
1180/// ```
1181/// use std::path::PathBuf;
1182///
1183/// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1184/// ```
1185///
1186/// We can still do better than this! Since these are all strings, we can use
1187/// `From::from`:
1188///
1189/// ```
1190/// use std::path::PathBuf;
1191///
1192/// let path = PathBuf::from(r"C:\windows\system32.dll");
1193/// ```
1194///
1195/// Which method works best depends on what kind of situation you're in.
1196///
1197/// Note that `PathBuf` does not always sanitize arguments, for example
1198/// [`push`] allows paths built from strings which include separators:
1199///
1200/// ```
1201/// use std::path::PathBuf;
1202///
1203/// let mut path = PathBuf::new();
1204///
1205/// path.push(r"C:\");
1206/// path.push("windows");
1207/// path.push(r"..\otherdir");
1208/// path.push("system32");
1209/// ```
1210///
1211/// The behavior of `PathBuf` may be changed to a panic on such inputs
1212/// in the future. [`Extend::extend`] should be used to add multi-part paths.
1213#[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1214#[stable(feature = "rust1", since = "1.0.0")]
1215pub struct PathBuf {
1216 inner: OsString,
1217}
1218
1219impl PathBuf {
1220 /// Allocates an empty `PathBuf`.
1221 ///
1222 /// # Examples
1223 ///
1224 /// ```
1225 /// use std::path::PathBuf;
1226 ///
1227 /// let path = PathBuf::new();
1228 /// ```
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 #[must_use]
1231 #[inline]
1232 #[rustc_const_stable(feature = "const_pathbuf_osstring_new", since = "1.91.0")]
1233 pub const fn new() -> PathBuf {
1234 PathBuf { inner: OsString::new() }
1235 }
1236
1237 /// Creates a new `PathBuf` with a given capacity used to create the
1238 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1239 ///
1240 /// # Examples
1241 ///
1242 /// ```
1243 /// use std::path::PathBuf;
1244 ///
1245 /// let mut path = PathBuf::with_capacity(10);
1246 /// let capacity = path.capacity();
1247 ///
1248 /// // This push is done without reallocating
1249 /// path.push(r"C:\");
1250 ///
1251 /// assert_eq!(capacity, path.capacity());
1252 /// ```
1253 ///
1254 /// [`with_capacity`]: OsString::with_capacity
1255 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1256 #[must_use]
1257 #[inline]
1258 pub fn with_capacity(capacity: usize) -> PathBuf {
1259 PathBuf { inner: OsString::with_capacity(capacity) }
1260 }
1261
1262 /// Coerces to a [`Path`] slice.
1263 ///
1264 /// # Examples
1265 ///
1266 /// ```
1267 /// use std::path::{Path, PathBuf};
1268 ///
1269 /// let p = PathBuf::from("/test");
1270 /// assert_eq!(Path::new("/test"), p.as_path());
1271 /// ```
1272 #[cfg_attr(not(test), rustc_diagnostic_item = "pathbuf_as_path")]
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 #[must_use]
1275 #[inline]
1276 pub fn as_path(&self) -> &Path {
1277 self
1278 }
1279
1280 /// Consumes and leaks the `PathBuf`, returning a mutable reference to the contents,
1281 /// `&'a mut Path`.
1282 ///
1283 /// The caller has free choice over the returned lifetime, including 'static.
1284 /// Indeed, this function is ideally used for data that lives for the remainder of
1285 /// the program's life, as dropping the returned reference will cause a memory leak.
1286 ///
1287 /// It does not reallocate or shrink the `PathBuf`, so the leaked allocation may include
1288 /// unused capacity that is not part of the returned slice. If you want to discard excess
1289 /// capacity, call [`into_boxed_path`], and then [`Box::leak`] instead.
1290 /// However, keep in mind that trimming the capacity may result in a reallocation and copy.
1291 ///
1292 /// [`into_boxed_path`]: Self::into_boxed_path
1293 #[stable(feature = "os_string_pathbuf_leak", since = "1.89.0")]
1294 #[inline]
1295 pub fn leak<'a>(self) -> &'a mut Path {
1296 Path::from_inner_mut(self.inner.leak())
1297 }
1298
1299 /// Extends `self` with `path`.
1300 ///
1301 /// If `path` is absolute, it replaces the current path.
1302 ///
1303 /// On Windows:
1304 ///
1305 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1306 /// replaces everything except for the prefix (if any) of `self`.
1307 /// * if `path` has a prefix but no root, it replaces `self`.
1308 /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
1309 /// and `path` is not empty, the new path is normalized: all references
1310 /// to `.` and `..` are removed.
1311 ///
1312 /// Consider using [`Path::join`] if you need a new `PathBuf` instead of
1313 /// using this function on a cloned `PathBuf`.
1314 ///
1315 /// # Examples
1316 ///
1317 /// Pushing a relative path extends the existing path:
1318 ///
1319 /// ```
1320 /// use std::path::PathBuf;
1321 ///
1322 /// let mut path = PathBuf::from("/tmp");
1323 /// path.push("file.bk");
1324 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1325 /// ```
1326 ///
1327 /// Pushing an absolute path replaces the existing path:
1328 ///
1329 /// ```
1330 /// use std::path::PathBuf;
1331 ///
1332 /// let mut path = PathBuf::from("/tmp");
1333 /// path.push("/etc");
1334 /// assert_eq!(path, PathBuf::from("/etc"));
1335 /// ```
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 #[rustc_confusables("append", "put")]
1338 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1339 self._push(path.as_ref())
1340 }
1341
1342 fn _push(&mut self, path: &Path) {
1343 // in general, a separator is needed if the rightmost byte is not a separator
1344 let buf = self.inner.as_encoded_bytes();
1345 let mut need_sep = buf.last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1346
1347 let self_comps = self.components();
1348 let self_prefix_len = self_comps.prefix_len();
1349
1350 // in the special case of `C:` on Windows, do *not* add a separator
1351 if self_prefix_len > 0
1352 && self_prefix_len == self_comps.path.len()
1353 && self_comps.prefix.unwrap().is_drive()
1354 {
1355 need_sep = false
1356 }
1357
1358 let path_comps = path.components();
1359
1360 let need_clear = if cfg!(any(target_os = "windows", target_os = "cygwin")) {
1361 // Windows/Cygwin: If path is absolute and its prefix is none, it is like `\foo`
1362 // (Windows) or `/foo` (Cygwin), and will be handled below.
1363 path_comps.prefix.is_some()
1364 } else {
1365 // On Unix: prefix is always None.
1366 path.is_absolute() || path_comps.prefix.is_some()
1367 };
1368
1369 // absolute `path` replaces `self`
1370 if need_clear {
1371 self.inner.clear();
1372
1373 // verbatim paths need . and .. removed
1374 } else if self_comps.prefix_verbatim() && !path.inner.is_empty() {
1375 let mut buf: Vec<_> = self_comps.collect();
1376 for c in path_comps {
1377 match c {
1378 Component::RootDir => {
1379 buf.truncate(1);
1380 buf.push(c);
1381 }
1382 Component::CurDir => (),
1383 Component::ParentDir => {
1384 if let Some(Component::Normal(_)) = buf.last() {
1385 buf.pop();
1386 }
1387 }
1388 _ => buf.push(c),
1389 }
1390 }
1391
1392 let mut res = OsString::new();
1393 let mut need_sep = false;
1394
1395 for c in buf {
1396 if need_sep && c != Component::RootDir {
1397 res.push(MAIN_SEPARATOR_STR);
1398 }
1399 res.push(c.as_os_str());
1400 need_sep = c != Component::RootDir;
1401 }
1402
1403 self.inner = res;
1404 return;
1405
1406 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1407 } else if path_comps.has_root() {
1408 self.inner.truncate(self_prefix_len);
1409
1410 // `path` is a pure relative path
1411 } else if need_sep {
1412 self.inner.push(MAIN_SEPARATOR_STR);
1413 }
1414
1415 self.inner.push(path);
1416 }
1417
1418 /// Truncates `self` to [`self.parent`].
1419 ///
1420 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1421 /// Otherwise, returns `true`.
1422 ///
1423 /// [`self.parent`]: Path::parent
1424 ///
1425 /// # Examples
1426 ///
1427 /// ```
1428 /// use std::path::{Path, PathBuf};
1429 ///
1430 /// let mut p = PathBuf::from("/spirited/away.rs");
1431 ///
1432 /// p.pop();
1433 /// assert_eq!(Path::new("/spirited"), p);
1434 /// p.pop();
1435 /// assert_eq!(Path::new("/"), p);
1436 /// ```
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 pub fn pop(&mut self) -> bool {
1439 match self.parent().map(|p| p.as_u8_slice().len()) {
1440 Some(len) => {
1441 self.inner.truncate(len);
1442 true
1443 }
1444 None => false,
1445 }
1446 }
1447
1448 /// Sets whether the path has a trailing [separator](MAIN_SEPARATOR).
1449 ///
1450 /// The value returned by [`has_trailing_sep`](Path::has_trailing_sep) will be equivalent to
1451 /// the provided value if possible.
1452 ///
1453 /// # Examples
1454 ///
1455 /// ```
1456 /// #![feature(path_trailing_sep)]
1457 /// use std::path::PathBuf;
1458 ///
1459 /// let mut p = PathBuf::from("dir");
1460 ///
1461 /// assert!(!p.has_trailing_sep());
1462 /// p.set_trailing_sep(false);
1463 /// assert!(!p.has_trailing_sep());
1464 /// p.set_trailing_sep(true);
1465 /// assert!(p.has_trailing_sep());
1466 /// p.set_trailing_sep(false);
1467 /// assert!(!p.has_trailing_sep());
1468 ///
1469 /// p = PathBuf::from("/");
1470 /// assert!(p.has_trailing_sep());
1471 /// p.set_trailing_sep(false);
1472 /// assert!(p.has_trailing_sep());
1473 /// ```
1474 #[unstable(feature = "path_trailing_sep", issue = "142503")]
1475 pub fn set_trailing_sep(&mut self, trailing_sep: bool) {
1476 if trailing_sep { self.push_trailing_sep() } else { self.pop_trailing_sep() }
1477 }
1478
1479 /// Adds a trailing [separator](MAIN_SEPARATOR) to the path.
1480 ///
1481 /// This acts similarly to [`Path::with_trailing_sep`], but mutates the underlying `PathBuf`.
1482 ///
1483 /// # Examples
1484 ///
1485 /// ```
1486 /// #![feature(path_trailing_sep)]
1487 /// use std::ffi::OsStr;
1488 /// use std::path::PathBuf;
1489 ///
1490 /// let mut p = PathBuf::from("dir");
1491 ///
1492 /// assert!(!p.has_trailing_sep());
1493 /// p.push_trailing_sep();
1494 /// assert!(p.has_trailing_sep());
1495 /// p.push_trailing_sep();
1496 /// assert!(p.has_trailing_sep());
1497 ///
1498 /// p = PathBuf::from("dir/");
1499 /// p.push_trailing_sep();
1500 /// assert_eq!(p.as_os_str(), OsStr::new("dir/"));
1501 /// ```
1502 #[unstable(feature = "path_trailing_sep", issue = "142503")]
1503 pub fn push_trailing_sep(&mut self) {
1504 if !self.has_trailing_sep() {
1505 self.push("");
1506 }
1507 }
1508
1509 /// Removes a trailing [separator](MAIN_SEPARATOR) from the path, if possible.
1510 ///
1511 /// This acts similarly to [`Path::trim_trailing_sep`], but mutates the underlying `PathBuf`.
1512 ///
1513 /// # Examples
1514 ///
1515 /// ```
1516 /// #![feature(path_trailing_sep)]
1517 /// use std::ffi::OsStr;
1518 /// use std::path::PathBuf;
1519 ///
1520 /// let mut p = PathBuf::from("dir//");
1521 ///
1522 /// assert!(p.has_trailing_sep());
1523 /// assert_eq!(p.as_os_str(), OsStr::new("dir//"));
1524 /// p.pop_trailing_sep();
1525 /// assert!(!p.has_trailing_sep());
1526 /// assert_eq!(p.as_os_str(), OsStr::new("dir"));
1527 /// p.pop_trailing_sep();
1528 /// assert!(!p.has_trailing_sep());
1529 /// assert_eq!(p.as_os_str(), OsStr::new("dir"));
1530 ///
1531 /// p = PathBuf::from("/");
1532 /// assert!(p.has_trailing_sep());
1533 /// p.pop_trailing_sep();
1534 /// assert!(p.has_trailing_sep());
1535 /// ```
1536 #[unstable(feature = "path_trailing_sep", issue = "142503")]
1537 pub fn pop_trailing_sep(&mut self) {
1538 self.inner.truncate(self.trim_trailing_sep().as_os_str().len());
1539 }
1540
1541 /// Updates [`self.file_name`] to `file_name`.
1542 ///
1543 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1544 /// `file_name`.
1545 ///
1546 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1547 /// `file_name`. The new path will be a sibling of the original path.
1548 /// (That is, it will have the same parent.)
1549 ///
1550 /// The argument is not sanitized, so can include separators. This
1551 /// behavior may be changed to a panic in the future.
1552 ///
1553 /// [`self.file_name`]: Path::file_name
1554 /// [`pop`]: PathBuf::pop
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```
1559 /// use std::path::PathBuf;
1560 ///
1561 /// let mut buf = PathBuf::from("/");
1562 /// assert!(buf.file_name() == None);
1563 ///
1564 /// buf.set_file_name("foo.txt");
1565 /// assert!(buf == PathBuf::from("/foo.txt"));
1566 /// assert!(buf.file_name().is_some());
1567 ///
1568 /// buf.set_file_name("bar.txt");
1569 /// assert!(buf == PathBuf::from("/bar.txt"));
1570 ///
1571 /// buf.set_file_name("baz");
1572 /// assert!(buf == PathBuf::from("/baz"));
1573 ///
1574 /// buf.set_file_name("../b/c.txt");
1575 /// assert!(buf == PathBuf::from("/../b/c.txt"));
1576 ///
1577 /// buf.set_file_name("baz");
1578 /// assert!(buf == PathBuf::from("/../b/baz"));
1579 /// ```
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1582 self._set_file_name(file_name.as_ref())
1583 }
1584
1585 fn _set_file_name(&mut self, file_name: &OsStr) {
1586 if self.file_name().is_some() {
1587 let popped = self.pop();
1588 debug_assert!(popped);
1589 }
1590 self.push(file_name);
1591 }
1592
1593 /// Updates [`self.extension`] to `Some(extension)` or to `None` if
1594 /// `extension` is empty.
1595 ///
1596 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1597 /// returns `true` and updates the extension otherwise.
1598 ///
1599 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1600 /// it is replaced.
1601 ///
1602 /// If `extension` is the empty string, [`self.extension`] will be [`None`]
1603 /// afterwards, not `Some("")`.
1604 ///
1605 /// # Panics
1606 ///
1607 /// Panics if the passed extension contains a path separator (see
1608 /// [`is_separator`]).
1609 ///
1610 /// # Caveats
1611 ///
1612 /// The new `extension` may contain dots and will be used in its entirety,
1613 /// but only the part after the final dot will be reflected in
1614 /// [`self.extension`].
1615 ///
1616 /// If the file stem contains internal dots and `extension` is empty, part
1617 /// of the old file stem will be considered the new [`self.extension`].
1618 ///
1619 /// See the examples below.
1620 ///
1621 /// [`self.file_name`]: Path::file_name
1622 /// [`self.extension`]: Path::extension
1623 ///
1624 /// # Examples
1625 ///
1626 /// ```
1627 /// use std::path::{Path, PathBuf};
1628 ///
1629 /// let mut p = PathBuf::from("/feel/the");
1630 ///
1631 /// p.set_extension("force");
1632 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1633 ///
1634 /// p.set_extension("dark.side");
1635 /// assert_eq!(Path::new("/feel/the.dark.side"), p.as_path());
1636 ///
1637 /// p.set_extension("cookie");
1638 /// assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path());
1639 ///
1640 /// p.set_extension("");
1641 /// assert_eq!(Path::new("/feel/the.dark"), p.as_path());
1642 ///
1643 /// p.set_extension("");
1644 /// assert_eq!(Path::new("/feel/the"), p.as_path());
1645 ///
1646 /// p.set_extension("");
1647 /// assert_eq!(Path::new("/feel/the"), p.as_path());
1648 /// ```
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1651 self._set_extension(extension.as_ref())
1652 }
1653
1654 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1655 validate_extension(extension);
1656
1657 let file_stem = match self.file_stem() {
1658 None => return false,
1659 Some(f) => f.as_encoded_bytes(),
1660 };
1661
1662 // truncate until right after the file stem
1663 let end_file_stem = file_stem[file_stem.len()..].as_ptr().addr();
1664 let start = self.inner.as_encoded_bytes().as_ptr().addr();
1665 self.inner.truncate(end_file_stem.wrapping_sub(start));
1666
1667 // add the new extension, if any
1668 let new = extension.as_encoded_bytes();
1669 if !new.is_empty() {
1670 self.inner.reserve_exact(new.len() + 1);
1671 self.inner.push(".");
1672 // SAFETY: Since a UTF-8 string was just pushed, it is not possible
1673 // for the buffer to end with a surrogate half.
1674 unsafe { self.inner.extend_from_slice_unchecked(new) };
1675 }
1676
1677 true
1678 }
1679
1680 /// Append [`self.extension`] with `extension`.
1681 ///
1682 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1683 /// returns `true` and updates the extension otherwise.
1684 ///
1685 /// # Panics
1686 ///
1687 /// Panics if the passed extension contains a path separator (see
1688 /// [`is_separator`]).
1689 ///
1690 /// # Caveats
1691 ///
1692 /// The appended `extension` may contain dots and will be used in its entirety,
1693 /// but only the part after the final dot will be reflected in
1694 /// [`self.extension`].
1695 ///
1696 /// See the examples below.
1697 ///
1698 /// [`self.file_name`]: Path::file_name
1699 /// [`self.extension`]: Path::extension
1700 ///
1701 /// # Examples
1702 ///
1703 /// ```
1704 /// use std::path::{Path, PathBuf};
1705 ///
1706 /// let mut p = PathBuf::from("/feel/the");
1707 ///
1708 /// p.add_extension("formatted");
1709 /// assert_eq!(Path::new("/feel/the.formatted"), p.as_path());
1710 ///
1711 /// p.add_extension("dark.side");
1712 /// assert_eq!(Path::new("/feel/the.formatted.dark.side"), p.as_path());
1713 ///
1714 /// p.set_extension("cookie");
1715 /// assert_eq!(Path::new("/feel/the.formatted.dark.cookie"), p.as_path());
1716 ///
1717 /// p.set_extension("");
1718 /// assert_eq!(Path::new("/feel/the.formatted.dark"), p.as_path());
1719 ///
1720 /// p.add_extension("");
1721 /// assert_eq!(Path::new("/feel/the.formatted.dark"), p.as_path());
1722 /// ```
1723 #[stable(feature = "path_add_extension", since = "1.91.0")]
1724 pub fn add_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1725 self._add_extension(extension.as_ref())
1726 }
1727
1728 fn _add_extension(&mut self, extension: &OsStr) -> bool {
1729 validate_extension(extension);
1730
1731 let file_name = match self.file_name() {
1732 None => return false,
1733 Some(f) => f.as_encoded_bytes(),
1734 };
1735
1736 let new = extension.as_encoded_bytes();
1737 if !new.is_empty() {
1738 // truncate until right after the file name
1739 // this is necessary for trimming the trailing separator
1740 let end_file_name = file_name[file_name.len()..].as_ptr().addr();
1741 let start = self.inner.as_encoded_bytes().as_ptr().addr();
1742 self.inner.truncate(end_file_name.wrapping_sub(start));
1743
1744 // append the new extension
1745 self.inner.reserve_exact(new.len() + 1);
1746 self.inner.push(".");
1747 // SAFETY: Since a UTF-8 string was just pushed, it is not possible
1748 // for the buffer to end with a surrogate half.
1749 unsafe { self.inner.extend_from_slice_unchecked(new) };
1750 }
1751
1752 true
1753 }
1754
1755 /// Yields a mutable reference to the underlying [`OsString`] instance.
1756 ///
1757 /// # Examples
1758 ///
1759 /// ```
1760 /// use std::path::{Path, PathBuf};
1761 ///
1762 /// let mut path = PathBuf::from("/foo");
1763 ///
1764 /// path.push("bar");
1765 /// assert_eq!(path, Path::new("/foo/bar"));
1766 ///
1767 /// // OsString's `push` does not add a separator.
1768 /// path.as_mut_os_string().push("baz");
1769 /// assert_eq!(path, Path::new("/foo/barbaz"));
1770 /// ```
1771 #[stable(feature = "path_as_mut_os_str", since = "1.70.0")]
1772 #[must_use]
1773 #[inline]
1774 pub fn as_mut_os_string(&mut self) -> &mut OsString {
1775 &mut self.inner
1776 }
1777
1778 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1779 ///
1780 /// # Examples
1781 ///
1782 /// ```
1783 /// use std::path::PathBuf;
1784 ///
1785 /// let p = PathBuf::from("/the/head");
1786 /// let os_str = p.into_os_string();
1787 /// ```
1788 #[stable(feature = "rust1", since = "1.0.0")]
1789 #[must_use = "`self` will be dropped if the result is not used"]
1790 #[inline]
1791 pub fn into_os_string(self) -> OsString {
1792 self.inner
1793 }
1794
1795 /// Converts the `PathBuf` into a `String` if it contains valid Unicode data.
1796 ///
1797 /// On failure, ownership of the original `PathBuf` is returned.
1798 ///
1799 /// # Examples
1800 ///
1801 /// ```
1802 /// use std::path::PathBuf;
1803 ///
1804 /// let path_buf = PathBuf::from("foo");
1805 /// let string = path_buf.into_string();
1806 /// assert_eq!(string, Ok(String::from("foo")));
1807 /// ```
1808 #[stable(feature = "pathbuf_into_string", since = "1.98.0")]
1809 pub fn into_string(self) -> Result<String, PathBuf> {
1810 self.into_os_string().into_string().map_err(PathBuf::from)
1811 }
1812
1813 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1814 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1815 #[must_use = "`self` will be dropped if the result is not used"]
1816 #[inline]
1817 pub fn into_boxed_path(self) -> Box<Path> {
1818 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1819 unsafe { Box::from_raw(rw) }
1820 }
1821
1822 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1823 ///
1824 /// [`capacity`]: OsString::capacity
1825 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1826 #[must_use]
1827 #[inline]
1828 pub fn capacity(&self) -> usize {
1829 self.inner.capacity()
1830 }
1831
1832 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1833 ///
1834 /// [`clear`]: OsString::clear
1835 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1836 #[inline]
1837 pub fn clear(&mut self) {
1838 self.inner.clear()
1839 }
1840
1841 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1842 ///
1843 /// [`reserve`]: OsString::reserve
1844 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1845 #[inline]
1846 pub fn reserve(&mut self, additional: usize) {
1847 self.inner.reserve(additional)
1848 }
1849
1850 /// Invokes [`try_reserve`] on the underlying instance of [`OsString`].
1851 ///
1852 /// [`try_reserve`]: OsString::try_reserve
1853 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1854 #[inline]
1855 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1856 self.inner.try_reserve(additional)
1857 }
1858
1859 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1860 ///
1861 /// [`reserve_exact`]: OsString::reserve_exact
1862 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1863 #[inline]
1864 pub fn reserve_exact(&mut self, additional: usize) {
1865 self.inner.reserve_exact(additional)
1866 }
1867
1868 /// Invokes [`try_reserve_exact`] on the underlying instance of [`OsString`].
1869 ///
1870 /// [`try_reserve_exact`]: OsString::try_reserve_exact
1871 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1872 #[inline]
1873 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1874 self.inner.try_reserve_exact(additional)
1875 }
1876
1877 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1878 ///
1879 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1880 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1881 #[inline]
1882 pub fn shrink_to_fit(&mut self) {
1883 self.inner.shrink_to_fit()
1884 }
1885
1886 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1887 ///
1888 /// [`shrink_to`]: OsString::shrink_to
1889 #[stable(feature = "shrink_to", since = "1.56.0")]
1890 #[inline]
1891 pub fn shrink_to(&mut self, min_capacity: usize) {
1892 self.inner.shrink_to(min_capacity)
1893 }
1894}
1895
1896#[stable(feature = "rust1", since = "1.0.0")]
1897impl Clone for PathBuf {
1898 #[inline]
1899 fn clone(&self) -> Self {
1900 PathBuf { inner: self.inner.clone() }
1901 }
1902
1903 /// Clones the contents of `source` into `self`.
1904 ///
1905 /// This method is preferred over simply assigning `source.clone()` to `self`,
1906 /// as it avoids reallocation if possible.
1907 #[inline]
1908 fn clone_from(&mut self, source: &Self) {
1909 self.inner.clone_from(&source.inner)
1910 }
1911}
1912
1913#[stable(feature = "box_from_path", since = "1.17.0")]
1914impl From<&Path> for Box<Path> {
1915 /// Creates a boxed [`Path`] from a reference.
1916 ///
1917 /// This will allocate and clone `path` to it.
1918 fn from(path: &Path) -> Box<Path> {
1919 Box::clone_from_ref(path)
1920 }
1921}
1922
1923#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
1924impl From<&mut Path> for Box<Path> {
1925 /// Creates a boxed [`Path`] from a reference.
1926 ///
1927 /// This will allocate and clone `path` to it.
1928 fn from(path: &mut Path) -> Box<Path> {
1929 Self::from(&*path)
1930 }
1931}
1932
1933#[stable(feature = "box_from_cow", since = "1.45.0")]
1934impl From<Cow<'_, Path>> for Box<Path> {
1935 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1936 ///
1937 /// Converting from a `Cow::Owned` does not clone or allocate.
1938 #[inline]
1939 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1940 match cow {
1941 Cow::Borrowed(path) => Box::from(path),
1942 Cow::Owned(path) => Box::from(path),
1943 }
1944 }
1945}
1946
1947#[stable(feature = "path_buf_from_box", since = "1.18.0")]
1948impl From<Box<Path>> for PathBuf {
1949 /// Converts a <code>[Box]<[Path]></code> into a [`PathBuf`].
1950 ///
1951 /// This conversion does not allocate or copy memory.
1952 #[inline]
1953 fn from(boxed: Box<Path>) -> PathBuf {
1954 boxed.into_path_buf()
1955 }
1956}
1957
1958#[stable(feature = "box_from_path_buf", since = "1.20.0")]
1959impl From<PathBuf> for Box<Path> {
1960 /// Converts a [`PathBuf`] into a <code>[Box]<[Path]></code>.
1961 ///
1962 /// This conversion currently should not allocate memory,
1963 /// but this behavior is not guaranteed on all platforms or in all future versions.
1964 #[inline]
1965 fn from(p: PathBuf) -> Box<Path> {
1966 p.into_boxed_path()
1967 }
1968}
1969
1970#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1971impl<A: Allocator + Clone> Clone for Box<Path, A> {
1972 #[inline]
1973 fn clone(&self) -> Self {
1974 Box::clone_from_ref_in(&**self, Self::allocator(self).clone())
1975 }
1976}
1977
1978#[stable(feature = "rust1", since = "1.0.0")]
1979impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1980 /// Converts a borrowed [`OsStr`] to a [`PathBuf`].
1981 ///
1982 /// Allocates a [`PathBuf`] and copies the data into it.
1983 #[inline]
1984 fn from(s: &T) -> PathBuf {
1985 PathBuf::from(s.as_ref().to_os_string())
1986 }
1987}
1988
1989#[stable(feature = "rust1", since = "1.0.0")]
1990impl From<OsString> for PathBuf {
1991 /// Converts an [`OsString`] into a [`PathBuf`].
1992 ///
1993 /// This conversion does not allocate or copy memory.
1994 #[inline]
1995 fn from(s: OsString) -> PathBuf {
1996 PathBuf { inner: s }
1997 }
1998}
1999
2000#[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
2001impl From<PathBuf> for OsString {
2002 /// Converts a [`PathBuf`] into an [`OsString`]
2003 ///
2004 /// This conversion does not allocate or copy memory.
2005 #[inline]
2006 fn from(path_buf: PathBuf) -> OsString {
2007 path_buf.inner
2008 }
2009}
2010
2011#[stable(feature = "rust1", since = "1.0.0")]
2012impl From<String> for PathBuf {
2013 /// Converts a [`String`] into a [`PathBuf`]
2014 ///
2015 /// This conversion does not allocate or copy memory.
2016 #[inline]
2017 fn from(s: String) -> PathBuf {
2018 PathBuf::from(OsString::from(s))
2019 }
2020}
2021
2022#[stable(feature = "path_from_str", since = "1.32.0")]
2023impl FromStr for PathBuf {
2024 type Err = !;
2025
2026 #[inline]
2027 fn from_str(s: &str) -> Result<Self, !> {
2028 Ok(PathBuf::from(s))
2029 }
2030}
2031
2032#[stable(feature = "rust1", since = "1.0.0")]
2033impl<P: AsRef<Path>> FromIterator<P> for PathBuf {
2034 /// Creates a new `PathBuf` from the [`Path`] elements of an iterator.
2035 ///
2036 /// This uses [`push`](Self::push) to add each element, so can be used to adjoin multiple path
2037 /// [components](Components).
2038 ///
2039 /// # Examples
2040 /// ```
2041 /// # use std::path::PathBuf;
2042 /// let path = PathBuf::from_iter(["/tmp", "foo", "bar"]);
2043 /// assert_eq!(path, PathBuf::from("/tmp/foo/bar"));
2044 /// ```
2045 ///
2046 /// See documentation for [`push`](Self::push) for more details on how the path is constructed.
2047 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
2048 let mut buf = PathBuf::new();
2049 buf.extend(iter);
2050 buf
2051 }
2052}
2053
2054#[stable(feature = "rust1", since = "1.0.0")]
2055impl<P: AsRef<Path>> Extend<P> for PathBuf {
2056 /// Extends `self` with [`Path`] elements from `iter`.
2057 ///
2058 /// This uses [`push`](Self::push) to add each element, so can be used to adjoin multiple path
2059 /// [components](Components).
2060 ///
2061 /// # Examples
2062 /// ```
2063 /// # use std::path::PathBuf;
2064 /// let mut path = PathBuf::from("/tmp");
2065 /// path.extend(["foo", "bar", "file.txt"]);
2066 /// assert_eq!(path, PathBuf::from("/tmp/foo/bar/file.txt"));
2067 /// ```
2068 ///
2069 /// See documentation for [`push`](Self::push) for more details on how the path is constructed.
2070 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
2071 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
2072 }
2073
2074 #[inline]
2075 fn extend_one(&mut self, p: P) {
2076 self.push(p.as_ref());
2077 }
2078}
2079
2080#[stable(feature = "rust1", since = "1.0.0")]
2081impl fmt::Debug for PathBuf {
2082 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2083 fmt::Debug::fmt(&**self, formatter)
2084 }
2085}
2086
2087#[stable(feature = "rust1", since = "1.0.0")]
2088impl ops::Deref for PathBuf {
2089 type Target = Path;
2090 #[inline]
2091 fn deref(&self) -> &Path {
2092 Path::new(&self.inner)
2093 }
2094}
2095
2096#[stable(feature = "path_buf_deref_mut", since = "1.68.0")]
2097impl ops::DerefMut for PathBuf {
2098 #[inline]
2099 fn deref_mut(&mut self) -> &mut Path {
2100 Path::from_inner_mut(&mut self.inner)
2101 }
2102}
2103
2104#[stable(feature = "rust1", since = "1.0.0")]
2105impl Borrow<Path> for PathBuf {
2106 #[inline]
2107 fn borrow(&self) -> &Path {
2108 self.deref()
2109 }
2110}
2111
2112#[stable(feature = "default_for_pathbuf", since = "1.17.0")]
2113impl Default for PathBuf {
2114 #[inline]
2115 fn default() -> Self {
2116 PathBuf::new()
2117 }
2118}
2119
2120#[stable(feature = "cow_from_path", since = "1.6.0")]
2121impl<'a> From<&'a Path> for Cow<'a, Path> {
2122 /// Creates a clone-on-write pointer from a reference to
2123 /// [`Path`].
2124 ///
2125 /// This conversion does not clone or allocate.
2126 #[inline]
2127 fn from(s: &'a Path) -> Cow<'a, Path> {
2128 Cow::Borrowed(s)
2129 }
2130}
2131
2132#[stable(feature = "cow_from_path", since = "1.6.0")]
2133impl<'a> From<PathBuf> for Cow<'a, Path> {
2134 /// Creates a clone-on-write pointer from an owned
2135 /// instance of [`PathBuf`].
2136 ///
2137 /// This conversion does not clone or allocate.
2138 #[inline]
2139 fn from(s: PathBuf) -> Cow<'a, Path> {
2140 Cow::Owned(s)
2141 }
2142}
2143
2144#[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
2145impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
2146 /// Creates a clone-on-write pointer from a reference to
2147 /// [`PathBuf`].
2148 ///
2149 /// This conversion does not clone or allocate.
2150 #[inline]
2151 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
2152 Cow::Borrowed(p.as_path())
2153 }
2154}
2155
2156#[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
2157impl<'a> From<Cow<'a, Path>> for PathBuf {
2158 /// Converts a clone-on-write pointer to an owned path.
2159 ///
2160 /// Converting from a `Cow::Owned` does not clone or allocate.
2161 #[inline]
2162 fn from(p: Cow<'a, Path>) -> Self {
2163 p.into_owned()
2164 }
2165}
2166
2167#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2168impl From<PathBuf> for Arc<Path> {
2169 /// Converts a [`PathBuf`] into an <code>[Arc]<[Path]></code> by moving the [`PathBuf`] data
2170 /// into a new [`Arc`] buffer.
2171 #[inline]
2172 fn from(s: PathBuf) -> Arc<Path> {
2173 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
2174 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
2175 }
2176}
2177
2178#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2179impl From<&Path> for Arc<Path> {
2180 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
2181 #[inline]
2182 fn from(s: &Path) -> Arc<Path> {
2183 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
2184 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
2185 }
2186}
2187
2188#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2189impl From<&mut Path> for Arc<Path> {
2190 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
2191 #[inline]
2192 fn from(s: &mut Path) -> Arc<Path> {
2193 Arc::from(&*s)
2194 }
2195}
2196
2197#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2198impl From<PathBuf> for Rc<Path> {
2199 /// Converts a [`PathBuf`] into an <code>[Rc]<[Path]></code> by moving the [`PathBuf`] data into
2200 /// a new [`Rc`] buffer.
2201 #[inline]
2202 fn from(s: PathBuf) -> Rc<Path> {
2203 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
2204 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
2205 }
2206}
2207
2208#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2209impl From<&Path> for Rc<Path> {
2210 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new [`Rc`] buffer.
2211 #[inline]
2212 fn from(s: &Path) -> Rc<Path> {
2213 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
2214 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
2215 }
2216}
2217
2218#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2219impl From<&mut Path> for Rc<Path> {
2220 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new [`Rc`] buffer.
2221 #[inline]
2222 fn from(s: &mut Path) -> Rc<Path> {
2223 Rc::from(&*s)
2224 }
2225}
2226
2227#[stable(feature = "rust1", since = "1.0.0")]
2228impl ToOwned for Path {
2229 type Owned = PathBuf;
2230 #[inline]
2231 fn to_owned(&self) -> PathBuf {
2232 self.to_path_buf()
2233 }
2234 #[inline]
2235 fn clone_into(&self, target: &mut PathBuf) {
2236 self.inner.clone_into(&mut target.inner);
2237 }
2238}
2239
2240#[stable(feature = "rust1", since = "1.0.0")]
2241impl PartialEq for PathBuf {
2242 #[inline]
2243 fn eq(&self, other: &PathBuf) -> bool {
2244 self.components() == other.components()
2245 }
2246}
2247
2248#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2249impl cmp::PartialEq<str> for PathBuf {
2250 #[inline]
2251 fn eq(&self, other: &str) -> bool {
2252 self.as_path() == other
2253 }
2254}
2255
2256#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2257impl cmp::PartialEq<PathBuf> for str {
2258 #[inline]
2259 fn eq(&self, other: &PathBuf) -> bool {
2260 self == other.as_path()
2261 }
2262}
2263
2264#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2265impl cmp::PartialEq<String> for PathBuf {
2266 #[inline]
2267 fn eq(&self, other: &String) -> bool {
2268 self.as_path() == other.as_str()
2269 }
2270}
2271
2272#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2273impl cmp::PartialEq<PathBuf> for String {
2274 #[inline]
2275 fn eq(&self, other: &PathBuf) -> bool {
2276 self.as_str() == other.as_path()
2277 }
2278}
2279
2280#[stable(feature = "rust1", since = "1.0.0")]
2281impl Hash for PathBuf {
2282 fn hash<H: Hasher>(&self, h: &mut H) {
2283 self.as_path().hash(h)
2284 }
2285}
2286
2287#[stable(feature = "rust1", since = "1.0.0")]
2288impl Eq for PathBuf {}
2289
2290#[stable(feature = "rust1", since = "1.0.0")]
2291impl PartialOrd for PathBuf {
2292 #[inline]
2293 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
2294 Some(compare_components(self.components(), other.components()))
2295 }
2296}
2297
2298#[stable(feature = "rust1", since = "1.0.0")]
2299impl Ord for PathBuf {
2300 #[inline]
2301 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
2302 compare_components(self.components(), other.components())
2303 }
2304}
2305
2306#[stable(feature = "rust1", since = "1.0.0")]
2307impl AsRef<OsStr> for PathBuf {
2308 #[inline]
2309 fn as_ref(&self) -> &OsStr {
2310 &self.inner[..]
2311 }
2312}
2313
2314/// A slice of a path (akin to [`str`]).
2315///
2316/// This type supports a number of operations for inspecting a path, including
2317/// breaking the path into its components (separated by `/` on Unix and by either
2318/// `/` or `\` on Windows), extracting the file name, determining whether the path
2319/// is absolute, and so on.
2320///
2321/// This is an *unsized* type, meaning that it must always be used behind a
2322/// pointer like `&` or [`Box`]. For an owned version of this type,
2323/// see [`PathBuf`].
2324///
2325/// More details about the overall approach can be found in
2326/// the [module documentation](self).
2327///
2328/// # Examples
2329///
2330/// ```
2331/// use std::path::Path;
2332/// use std::ffi::OsStr;
2333///
2334/// // Note: this example does work on Windows
2335/// let path = Path::new("./foo/bar.txt");
2336///
2337/// let parent = path.parent();
2338/// assert_eq!(parent, Some(Path::new("./foo")));
2339///
2340/// let file_stem = path.file_stem();
2341/// assert_eq!(file_stem, Some(OsStr::new("bar")));
2342///
2343/// let extension = path.extension();
2344/// assert_eq!(extension, Some(OsStr::new("txt")));
2345/// ```
2346#[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
2347#[stable(feature = "rust1", since = "1.0.0")]
2348// `Path::new` and `impl CloneToUninit for Path` current implementation relies
2349// on `Path` being layout-compatible with `OsStr`.
2350// However, `Path` layout is considered an implementation detail and must not be relied upon.
2351#[repr(transparent)]
2352pub struct Path {
2353 inner: OsStr,
2354}
2355
2356/// An error returned from [`Path::strip_prefix`] if the prefix was not found.
2357///
2358/// This `struct` is created by the [`strip_prefix`] method on [`Path`].
2359/// See its documentation for more.
2360///
2361/// [`strip_prefix`]: Path::strip_prefix
2362#[derive(Debug, Clone, PartialEq, Eq)]
2363#[stable(since = "1.7.0", feature = "strip_prefix")]
2364pub struct StripPrefixError(());
2365
2366/// An error returned from [`Path::normalize_lexically`] if a `..` parent reference
2367/// would escape the path.
2368#[unstable(feature = "normalize_lexically", issue = "134694")]
2369#[derive(Debug, PartialEq)]
2370#[non_exhaustive]
2371pub struct NormalizeError;
2372
2373impl Path {
2374 // The following (private!) function allows construction of a path from a u8
2375 // slice, which is only safe when it is known to follow the OsStr encoding.
2376 pub(crate) unsafe fn from_u8_slice(s: &[u8]) -> &Path {
2377 unsafe { Path::new(OsStr::from_encoded_bytes_unchecked(s)) }
2378 }
2379 // The following (private!) function reveals the byte encoding used for OsStr.
2380 pub(crate) fn as_u8_slice(&self) -> &[u8] {
2381 self.inner.as_encoded_bytes()
2382 }
2383
2384 /// Directly wraps a string slice as a `Path` slice.
2385 ///
2386 /// This is a cost-free conversion.
2387 ///
2388 /// # Examples
2389 ///
2390 /// ```
2391 /// use std::path::Path;
2392 ///
2393 /// Path::new("foo.txt");
2394 /// ```
2395 ///
2396 /// You can create `Path`s from `String`s, or even other `Path`s:
2397 ///
2398 /// ```
2399 /// use std::path::Path;
2400 ///
2401 /// let string = String::from("foo.txt");
2402 /// let from_string = Path::new(&string);
2403 /// let from_path = Path::new(&from_string);
2404 /// assert_eq!(from_string, from_path);
2405 /// ```
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2408 pub const fn new<S: [const] AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
2409 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
2410 }
2411
2412 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2413 const fn from_inner_mut(inner: &mut OsStr) -> &mut Path {
2414 // SAFETY: Path is just a wrapper around OsStr,
2415 // therefore converting &mut OsStr to &mut Path is safe.
2416 unsafe { &mut *(inner as *mut OsStr as *mut Path) }
2417 }
2418
2419 /// Yields the underlying [`OsStr`] slice.
2420 ///
2421 /// # Examples
2422 ///
2423 /// ```
2424 /// use std::path::Path;
2425 ///
2426 /// let os_str = Path::new("foo.txt").as_os_str();
2427 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
2428 /// ```
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 #[must_use]
2431 #[inline]
2432 pub fn as_os_str(&self) -> &OsStr {
2433 &self.inner
2434 }
2435
2436 /// Yields a mutable reference to the underlying [`OsStr`] slice.
2437 ///
2438 /// # Examples
2439 ///
2440 /// ```
2441 /// use std::path::{Path, PathBuf};
2442 ///
2443 /// let mut path = PathBuf::from("Foo.TXT");
2444 ///
2445 /// assert_ne!(path, Path::new("foo.txt"));
2446 ///
2447 /// path.as_mut_os_str().make_ascii_lowercase();
2448 /// assert_eq!(path, Path::new("foo.txt"));
2449 /// ```
2450 #[stable(feature = "path_as_mut_os_str", since = "1.70.0")]
2451 #[must_use]
2452 #[inline]
2453 pub fn as_mut_os_str(&mut self) -> &mut OsStr {
2454 &mut self.inner
2455 }
2456
2457 /// Yields a [`&str`] slice if the `Path` is valid unicode.
2458 ///
2459 /// This conversion may entail doing a check for UTF-8 validity.
2460 /// Note that validation is performed because non-UTF-8 strings are
2461 /// perfectly valid for some OS.
2462 ///
2463 /// [`&str`]: str
2464 ///
2465 /// # Examples
2466 ///
2467 /// ```
2468 /// use std::path::Path;
2469 ///
2470 /// let path = Path::new("foo.txt");
2471 /// assert_eq!(path.to_str(), Some("foo.txt"));
2472 /// ```
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 #[must_use = "this returns the result of the operation, \
2475 without modifying the original"]
2476 #[inline]
2477 pub fn to_str(&self) -> Option<&str> {
2478 self.inner.to_str()
2479 }
2480
2481 /// Converts a `Path` to a [`Cow<str>`].
2482 ///
2483 /// Any non-UTF-8 sequences are replaced with
2484 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
2485 ///
2486 /// [U+FFFD]: char::REPLACEMENT_CHARACTER
2487 ///
2488 /// # Examples
2489 ///
2490 /// Calling `to_string_lossy` on a `Path` with valid unicode:
2491 ///
2492 /// ```
2493 /// use std::path::Path;
2494 ///
2495 /// let path = Path::new("foo.txt");
2496 /// assert_eq!(path.to_string_lossy(), "foo.txt");
2497 /// ```
2498 ///
2499 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
2500 /// have returned `"fo�.txt"`.
2501 #[stable(feature = "rust1", since = "1.0.0")]
2502 #[must_use = "this returns the result of the operation, \
2503 without modifying the original"]
2504 #[inline]
2505 pub fn to_string_lossy(&self) -> Cow<'_, str> {
2506 self.inner.to_string_lossy()
2507 }
2508
2509 /// Converts a `Path` to an owned [`PathBuf`].
2510 ///
2511 /// # Examples
2512 ///
2513 /// ```
2514 /// use std::path::{Path, PathBuf};
2515 ///
2516 /// let path_buf = Path::new("foo.txt").to_path_buf();
2517 /// assert_eq!(path_buf, PathBuf::from("foo.txt"));
2518 /// ```
2519 #[rustc_conversion_suggestion]
2520 #[must_use = "this returns the result of the operation, \
2521 without modifying the original"]
2522 #[stable(feature = "rust1", since = "1.0.0")]
2523 #[cfg_attr(not(test), rustc_diagnostic_item = "path_to_pathbuf")]
2524 pub fn to_path_buf(&self) -> PathBuf {
2525 PathBuf::from(self.inner.to_os_string())
2526 }
2527
2528 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
2529 /// the current directory.
2530 ///
2531 /// * On Unix, a path is absolute if it starts with the root, so
2532 /// `is_absolute` and [`has_root`] are equivalent.
2533 ///
2534 /// * On Windows, a path is absolute if it has a prefix and starts with the
2535 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2536 ///
2537 /// # Examples
2538 ///
2539 /// ```
2540 /// use std::path::Path;
2541 ///
2542 /// assert!(!Path::new("foo.txt").is_absolute());
2543 /// ```
2544 ///
2545 /// [`has_root`]: Path::has_root
2546 #[stable(feature = "rust1", since = "1.0.0")]
2547 #[must_use]
2548 #[allow(deprecated)]
2549 pub fn is_absolute(&self) -> bool {
2550 sys::path::is_absolute(self)
2551 }
2552
2553 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2554 ///
2555 /// See [`is_absolute`]'s documentation for more details.
2556 ///
2557 /// # Examples
2558 ///
2559 /// ```
2560 /// use std::path::Path;
2561 ///
2562 /// assert!(Path::new("foo.txt").is_relative());
2563 /// ```
2564 ///
2565 /// [`is_absolute`]: Path::is_absolute
2566 #[stable(feature = "rust1", since = "1.0.0")]
2567 #[must_use]
2568 #[inline]
2569 pub fn is_relative(&self) -> bool {
2570 !self.is_absolute()
2571 }
2572
2573 #[cfg(not(target_os = "uefi"))]
2574 pub(crate) fn prefix(&self) -> Option<Prefix<'_>> {
2575 self.components().prefix
2576 }
2577
2578 /// Returns `true` if the `Path` has a root.
2579 ///
2580 /// * On Unix, a path has a root if it begins with `/`.
2581 ///
2582 /// * On Windows, a path has a root if it:
2583 /// * has no prefix and begins with a separator, e.g., `\windows`
2584 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2585 /// * has any non-disk prefix, e.g., `\\server\share`
2586 ///
2587 /// # Examples
2588 ///
2589 /// ```
2590 /// use std::path::Path;
2591 ///
2592 /// assert!(Path::new("/etc/passwd").has_root());
2593 /// ```
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 #[must_use]
2596 #[inline]
2597 pub fn has_root(&self) -> bool {
2598 self.components().has_root()
2599 }
2600
2601 /// Returns the `Path` without its final component, if there is one.
2602 ///
2603 /// This means it returns `Some("")` for relative paths with one component.
2604 ///
2605 /// Returns [`None`] if the path terminates in a root or prefix, or if it's
2606 /// the empty string.
2607 ///
2608 /// # Examples
2609 ///
2610 /// ```
2611 /// use std::path::Path;
2612 ///
2613 /// let path = Path::new("/foo/bar");
2614 /// let parent = path.parent().unwrap();
2615 /// assert_eq!(parent, Path::new("/foo"));
2616 ///
2617 /// let grand_parent = parent.parent().unwrap();
2618 /// assert_eq!(grand_parent, Path::new("/"));
2619 /// assert_eq!(grand_parent.parent(), None);
2620 ///
2621 /// let relative_path = Path::new("foo/bar");
2622 /// let parent = relative_path.parent();
2623 /// assert_eq!(parent, Some(Path::new("foo")));
2624 /// let grand_parent = parent.and_then(Path::parent);
2625 /// assert_eq!(grand_parent, Some(Path::new("")));
2626 /// let great_grand_parent = grand_parent.and_then(Path::parent);
2627 /// assert_eq!(great_grand_parent, None);
2628 /// ```
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 #[doc(alias = "dirname")]
2631 #[must_use]
2632 pub fn parent(&self) -> Option<&Path> {
2633 let mut comps = self.components();
2634 let comp = comps.next_back();
2635 comp.and_then(|p| match p {
2636 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2637 Some(comps.as_path())
2638 }
2639 _ => None,
2640 })
2641 }
2642
2643 /// Produces an iterator over `Path` and its ancestors.
2644 ///
2645 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2646 /// or more times. If the [`parent`] method returns [`None`], the iterator will do likewise.
2647 /// The iterator will always yield at least one value, namely `Some(&self)`. Next it will yield
2648 /// `&self.parent()`, `&self.parent().and_then(Path::parent)` and so on.
2649 ///
2650 /// # Examples
2651 ///
2652 /// ```
2653 /// use std::path::Path;
2654 ///
2655 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2656 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2657 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2658 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2659 /// assert_eq!(ancestors.next(), None);
2660 ///
2661 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2662 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2663 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2664 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2665 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2666 /// assert_eq!(ancestors.next(), None);
2667 /// ```
2668 ///
2669 /// [`parent`]: Path::parent
2670 #[stable(feature = "path_ancestors", since = "1.28.0")]
2671 #[inline]
2672 pub fn ancestors(&self) -> Ancestors<'_> {
2673 Ancestors { next: Some(self) }
2674 }
2675
2676 /// Returns the final component of the `Path`, if there is one.
2677 ///
2678 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2679 /// is the directory name.
2680 ///
2681 /// Returns [`None`] if the path terminates in `..`.
2682 ///
2683 /// # Examples
2684 ///
2685 /// ```
2686 /// use std::path::Path;
2687 /// use std::ffi::OsStr;
2688 ///
2689 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2690 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2691 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2692 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2693 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2694 /// assert_eq!(None, Path::new("/").file_name());
2695 /// ```
2696 #[stable(feature = "rust1", since = "1.0.0")]
2697 #[doc(alias = "basename")]
2698 #[must_use]
2699 pub fn file_name(&self) -> Option<&OsStr> {
2700 self.components().next_back().and_then(|p| match p {
2701 Component::Normal(p) => Some(p),
2702 _ => None,
2703 })
2704 }
2705
2706 /// Returns a path that, when joined onto `base`, yields `self`.
2707 ///
2708 /// # Errors
2709 ///
2710 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2711 /// returns `false`), returns [`Err`].
2712 ///
2713 /// [`starts_with`]: Path::starts_with
2714 ///
2715 /// # Examples
2716 ///
2717 /// ```
2718 /// use std::path::{Path, PathBuf};
2719 ///
2720 /// let path = Path::new("/test/haha/foo.txt");
2721 ///
2722 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2723 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2724 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2725 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2726 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2727 ///
2728 /// assert!(path.strip_prefix("test").is_err());
2729 /// assert!(path.strip_prefix("/te").is_err());
2730 /// assert!(path.strip_prefix("/haha").is_err());
2731 ///
2732 /// let prefix = PathBuf::from("/test/");
2733 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2734 /// ```
2735 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2736 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2737 where
2738 P: AsRef<Path>,
2739 {
2740 self._strip_prefix(base.as_ref())
2741 }
2742
2743 /// Returns a path with the optional prefix removed.
2744 ///
2745 /// If `base` is not a prefix of `self` (i.e., [`starts_with`] returns `false`), returns the original path (`self`)
2746 ///
2747 /// [`starts_with`]: Path::starts_with
2748 ///
2749 /// # Examples
2750 ///
2751 /// ```
2752 /// use std::path::Path;
2753 ///
2754 /// let path = Path::new("/test/haha/foo.txt");
2755 ///
2756 /// // Prefix present - remove it
2757 /// assert_eq!(path.trim_prefix("/"), Path::new("test/haha/foo.txt"));
2758 /// assert_eq!(path.trim_prefix("/test"), Path::new("haha/foo.txt"));
2759 /// assert_eq!(path.trim_prefix("/test/"), Path::new("haha/foo.txt"));
2760 /// assert_eq!(path.trim_prefix("/test/haha/foo.txt"), Path::new(""));
2761 /// assert_eq!(path.trim_prefix("/test/haha/foo.txt/"), Path::new(""));
2762 ///
2763 /// // Prefix absent - return original
2764 /// assert_eq!(path.trim_prefix("test"), path);
2765 /// assert_eq!(path.trim_prefix("/te"), path);
2766 /// assert_eq!(path.trim_prefix("/haha"), path);
2767 /// ```
2768 #[must_use = "this returns the remaining path as a new path, without modifying the original"]
2769 #[stable(feature = "trim_prefix_suffix", since = "1.100.0")]
2770 pub fn trim_prefix<P>(&self, base: P) -> &Path
2771 where
2772 P: AsRef<Path>,
2773 {
2774 self._strip_prefix(base.as_ref()).unwrap_or(self)
2775 }
2776
2777 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2778 iter_after(self.components(), base.components())
2779 .map(|c| c.as_path())
2780 .ok_or(StripPrefixError(()))
2781 }
2782
2783 /// Determines whether `base` is a prefix of `self`.
2784 ///
2785 /// Only considers whole path components to match.
2786 ///
2787 /// # Examples
2788 ///
2789 /// ```
2790 /// use std::path::Path;
2791 ///
2792 /// let path = Path::new("/etc/passwd");
2793 ///
2794 /// assert!(path.starts_with("/etc"));
2795 /// assert!(path.starts_with("/etc/"));
2796 /// assert!(path.starts_with("/etc/passwd"));
2797 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2798 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2799 ///
2800 /// assert!(!path.starts_with("/e"));
2801 /// assert!(!path.starts_with("/etc/passwd.txt"));
2802 ///
2803 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2804 /// ```
2805 #[stable(feature = "rust1", since = "1.0.0")]
2806 #[must_use]
2807 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2808 self._starts_with(base.as_ref())
2809 }
2810
2811 fn _starts_with(&self, base: &Path) -> bool {
2812 iter_after(self.components(), base.components()).is_some()
2813 }
2814
2815 /// Determines whether `child` is a suffix of `self`.
2816 ///
2817 /// Only considers whole path components to match.
2818 ///
2819 /// # Examples
2820 ///
2821 /// ```
2822 /// use std::path::Path;
2823 ///
2824 /// let path = Path::new("/etc/resolv.conf");
2825 ///
2826 /// assert!(path.ends_with("resolv.conf"));
2827 /// assert!(path.ends_with("etc/resolv.conf"));
2828 /// assert!(path.ends_with("/etc/resolv.conf"));
2829 ///
2830 /// assert!(!path.ends_with("/resolv.conf"));
2831 /// assert!(!path.ends_with("conf")); // use .extension() instead
2832 /// ```
2833 #[stable(feature = "rust1", since = "1.0.0")]
2834 #[must_use]
2835 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2836 self._ends_with(child.as_ref())
2837 }
2838
2839 fn _ends_with(&self, child: &Path) -> bool {
2840 iter_after(self.components().rev(), child.components().rev()).is_some()
2841 }
2842
2843 /// Checks whether the `Path` is empty.
2844 ///
2845 /// Passing an empty path to most OS filesystem APIs will always result in an error.
2846 ///
2847 /// [Pushing][PathBuf::push] an empty path to an existing path will append a directory separator unless it already ends with a separator or the existing path is itself empty.
2848 ///
2849 /// # Examples
2850 ///
2851 /// ```
2852 /// use std::path::Path;
2853 ///
2854 /// let path = Path::new("");
2855 /// assert!(path.is_empty());
2856 ///
2857 /// let path = Path::new("foo");
2858 /// assert!(!path.is_empty());
2859 ///
2860 /// let path = Path::new(".");
2861 /// assert!(!path.is_empty());
2862 /// ```
2863 #[stable(feature = "path_is_empty", since = "1.98.0")]
2864 pub fn is_empty(&self) -> bool {
2865 self.as_os_str().is_empty()
2866 }
2867
2868 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2869 ///
2870 /// [`self.file_name`]: Path::file_name
2871 ///
2872 /// The stem is:
2873 ///
2874 /// * [`None`], if there is no file name;
2875 /// * The entire file name if there is no embedded `.`;
2876 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2877 /// * Otherwise, the portion of the file name before the final `.`
2878 ///
2879 /// # Examples
2880 ///
2881 /// ```
2882 /// use std::path::Path;
2883 ///
2884 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2885 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2886 /// ```
2887 ///
2888 /// # See Also
2889 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2890 /// before the *first* `.`
2891 ///
2892 /// [`Path::file_prefix`]: Path::file_prefix
2893 ///
2894 #[stable(feature = "rust1", since = "1.0.0")]
2895 #[must_use]
2896 pub fn file_stem(&self) -> Option<&OsStr> {
2897 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2898 }
2899
2900 /// Extracts the prefix of [`self.file_name`].
2901 ///
2902 /// The prefix is:
2903 ///
2904 /// * [`None`], if there is no file name;
2905 /// * The entire file name if there is no embedded `.`;
2906 /// * The portion of the file name before the first non-beginning `.`;
2907 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2908 /// * The portion of the file name before the second `.` if the file name begins with `.`
2909 ///
2910 /// [`self.file_name`]: Path::file_name
2911 ///
2912 /// # Examples
2913 ///
2914 /// ```
2915 /// use std::path::Path;
2916 ///
2917 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2918 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2919 /// assert_eq!(".config", Path::new(".config").file_prefix().unwrap());
2920 /// assert_eq!(".config", Path::new(".config.toml").file_prefix().unwrap());
2921 /// ```
2922 ///
2923 /// # See Also
2924 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2925 /// before the *last* `.`
2926 ///
2927 /// [`Path::file_stem`]: Path::file_stem
2928 ///
2929 #[stable(feature = "path_file_prefix", since = "1.91.0")]
2930 #[must_use]
2931 pub fn file_prefix(&self) -> Option<&OsStr> {
2932 self.file_name().map(split_file_at_dot).map(|(before, _after)| before)
2933 }
2934
2935 /// Extracts the extension (without the leading dot) of [`self.file_name`], if possible.
2936 ///
2937 /// The extension is:
2938 ///
2939 /// * [`None`], if there is no file name;
2940 /// * [`None`], if there is no embedded `.`;
2941 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2942 /// * Otherwise, the portion of the file name after the final `.`
2943 ///
2944 /// [`self.file_name`]: Path::file_name
2945 ///
2946 /// # Examples
2947 ///
2948 /// ```
2949 /// use std::path::Path;
2950 ///
2951 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2952 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2953 /// ```
2954 #[stable(feature = "rust1", since = "1.0.0")]
2955 #[must_use]
2956 pub fn extension(&self) -> Option<&OsStr> {
2957 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2958 }
2959
2960 /// Checks whether the path ends in a trailing [separator](MAIN_SEPARATOR).
2961 ///
2962 /// This is generally done to ensure that a path is treated as a directory, not a file,
2963 /// although it does not actually guarantee that such a path is a directory on the underlying
2964 /// file system.
2965 ///
2966 /// Despite this behavior, two paths are still considered the same in Rust whether they have a
2967 /// trailing separator or not.
2968 ///
2969 /// # Examples
2970 ///
2971 /// ```
2972 /// #![feature(path_trailing_sep)]
2973 /// use std::path::Path;
2974 ///
2975 /// assert!(Path::new("dir/").has_trailing_sep());
2976 /// assert!(!Path::new("file.rs").has_trailing_sep());
2977 /// ```
2978 #[unstable(feature = "path_trailing_sep", issue = "142503")]
2979 #[must_use]
2980 #[inline]
2981 pub fn has_trailing_sep(&self) -> bool {
2982 let comps = self.components();
2983 self.as_os_str().as_encoded_bytes().last().copied().is_some_and(|b| comps.is_sep_byte(b))
2984 }
2985
2986 /// Ensures that a path has a trailing [separator](MAIN_SEPARATOR),
2987 /// allocating a [`PathBuf`] if necessary.
2988 ///
2989 /// The resulting path will return true for [`has_trailing_sep`](Self::has_trailing_sep).
2990 ///
2991 /// # Examples
2992 ///
2993 /// ```
2994 /// #![feature(path_trailing_sep)]
2995 /// use std::ffi::OsStr;
2996 /// use std::path::Path;
2997 ///
2998 /// assert_eq!(Path::new("dir//").with_trailing_sep().as_os_str(), OsStr::new("dir//"));
2999 /// assert_eq!(Path::new("dir/").with_trailing_sep().as_os_str(), OsStr::new("dir/"));
3000 /// assert!(!Path::new("dir").has_trailing_sep());
3001 /// assert!(Path::new("dir").with_trailing_sep().has_trailing_sep());
3002 /// ```
3003 #[unstable(feature = "path_trailing_sep", issue = "142503")]
3004 #[must_use]
3005 #[inline]
3006 pub fn with_trailing_sep(&self) -> Cow<'_, Path> {
3007 if self.has_trailing_sep() { Cow::Borrowed(self) } else { Cow::Owned(self.join("")) }
3008 }
3009
3010 /// Trims a trailing [separator](MAIN_SEPARATOR) from a path, if possible.
3011 ///
3012 /// The resulting path will return false for [`has_trailing_sep`](Self::has_trailing_sep) for
3013 /// most paths.
3014 ///
3015 /// Some paths, like `/`, cannot be trimmed in this way.
3016 ///
3017 /// # Examples
3018 ///
3019 /// ```
3020 /// #![feature(path_trailing_sep)]
3021 /// use std::ffi::OsStr;
3022 /// use std::path::Path;
3023 ///
3024 /// assert_eq!(Path::new("dir//").trim_trailing_sep().as_os_str(), OsStr::new("dir"));
3025 /// assert_eq!(Path::new("dir/").trim_trailing_sep().as_os_str(), OsStr::new("dir"));
3026 /// assert_eq!(Path::new("dir").trim_trailing_sep().as_os_str(), OsStr::new("dir"));
3027 /// assert_eq!(Path::new("/").trim_trailing_sep().as_os_str(), OsStr::new("/"));
3028 /// assert_eq!(Path::new("//").trim_trailing_sep().as_os_str(), OsStr::new("//"));
3029 /// ```
3030 #[unstable(feature = "path_trailing_sep", issue = "142503")]
3031 #[must_use]
3032 #[inline]
3033 pub fn trim_trailing_sep(&self) -> &Path {
3034 let comps = self.components();
3035 if self.has_trailing_sep() && (!self.has_root() || self.parent().is_some()) {
3036 let mut bytes = self.inner.as_encoded_bytes();
3037 while let Some((last, init)) = bytes.split_last()
3038 && comps.is_sep_byte(*last)
3039 {
3040 bytes = init;
3041 }
3042
3043 // SAFETY: Trimming trailing ASCII bytes will retain the validity of the string.
3044 Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) })
3045 } else {
3046 self
3047 }
3048 }
3049
3050 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
3051 ///
3052 /// If `path` is absolute, it replaces the current path.
3053 ///
3054 /// On Windows:
3055 ///
3056 /// * if `path` has a root but no prefix (e.g., `\windows`), it
3057 /// replaces and returns everything except for the prefix (if any) of `self`.
3058 /// * if `path` has a prefix but no root, `self` is ignored and `path` is returned.
3059 /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
3060 /// and `path` is not empty, the new path is normalized: all references
3061 /// to `.` and `..` are removed.
3062 ///
3063 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
3064 ///
3065 /// # Examples
3066 ///
3067 /// ```
3068 /// use std::path::{Path, PathBuf};
3069 ///
3070 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
3071 /// assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh"));
3072 /// ```
3073 #[stable(feature = "rust1", since = "1.0.0")]
3074 #[must_use]
3075 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
3076 self._join(path.as_ref())
3077 }
3078
3079 fn _join(&self, path: &Path) -> PathBuf {
3080 let mut buf = self.to_path_buf();
3081 buf.push(path);
3082 buf
3083 }
3084
3085 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
3086 ///
3087 /// See [`PathBuf::set_file_name`] for more details.
3088 ///
3089 /// # Examples
3090 ///
3091 /// ```
3092 /// use std::path::{Path, PathBuf};
3093 ///
3094 /// let path = Path::new("/tmp/foo.png");
3095 /// assert_eq!(path.with_file_name("bar"), PathBuf::from("/tmp/bar"));
3096 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
3097 ///
3098 /// let path = Path::new("/tmp");
3099 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
3100 /// ```
3101 #[stable(feature = "rust1", since = "1.0.0")]
3102 #[must_use]
3103 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
3104 self._with_file_name(file_name.as_ref())
3105 }
3106
3107 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
3108 let mut buf = self.to_path_buf();
3109 buf.set_file_name(file_name);
3110 buf
3111 }
3112
3113 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
3114 ///
3115 /// See [`PathBuf::set_extension`] for more details.
3116 ///
3117 /// # Examples
3118 ///
3119 /// ```
3120 /// use std::path::Path;
3121 ///
3122 /// let path = Path::new("foo.rs");
3123 /// assert_eq!(path.with_extension("txt"), Path::new("foo.txt"));
3124 /// assert_eq!(path.with_extension(""), Path::new("foo"));
3125 /// ```
3126 ///
3127 /// Handling multiple extensions:
3128 ///
3129 /// ```
3130 /// use std::path::Path;
3131 ///
3132 /// let path = Path::new("foo.tar.gz");
3133 /// assert_eq!(path.with_extension("xz"), Path::new("foo.tar.xz"));
3134 /// assert_eq!(path.with_extension("").with_extension("txt"), Path::new("foo.txt"));
3135 /// ```
3136 ///
3137 /// Adding an extension where one did not exist:
3138 ///
3139 /// ```
3140 /// use std::path::Path;
3141 ///
3142 /// let path = Path::new("foo");
3143 /// assert_eq!(path.with_extension("rs"), Path::new("foo.rs"));
3144 /// ```
3145 #[stable(feature = "rust1", since = "1.0.0")]
3146 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
3147 self._with_extension(extension.as_ref())
3148 }
3149
3150 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
3151 let self_len = self.as_os_str().len();
3152 let self_bytes = self.as_os_str().as_encoded_bytes();
3153
3154 let (new_capacity, slice_to_copy) = match self.extension() {
3155 None => {
3156 // Enough capacity for the extension and the dot
3157 let capacity = self_len + extension.len() + 1;
3158 let whole_path = self_bytes;
3159 (capacity, whole_path)
3160 }
3161 Some(previous_extension) => {
3162 let capacity = self_len + extension.len() - previous_extension.len();
3163 let path_till_dot = &self_bytes[..self_len - previous_extension.len()];
3164 (capacity, path_till_dot)
3165 }
3166 };
3167
3168 let mut new_path = PathBuf::with_capacity(new_capacity);
3169 // SAFETY: The path is empty, so cannot have surrogate halves.
3170 unsafe { new_path.inner.extend_from_slice_unchecked(slice_to_copy) };
3171 new_path.set_extension(extension);
3172 new_path
3173 }
3174
3175 /// Creates an owned [`PathBuf`] like `self` but with the extension added.
3176 ///
3177 /// See [`PathBuf::add_extension`] for more details. The return value of
3178 /// [`PathBuf::add_extension`] is ignored, which means no extension
3179 /// will be added to paths with no [`Path::file_name`].
3180 ///
3181 /// # Examples
3182 ///
3183 /// ```
3184 /// use std::path::{Path, PathBuf};
3185 ///
3186 /// let path = Path::new("foo.rs");
3187 /// assert_eq!(path.with_added_extension("txt"), PathBuf::from("foo.rs.txt"));
3188 ///
3189 /// let path = Path::new("foo.tar.gz");
3190 /// assert_eq!(path.with_added_extension(""), PathBuf::from("foo.tar.gz"));
3191 /// assert_eq!(path.with_added_extension("xz"), PathBuf::from("foo.tar.gz.xz"));
3192 /// assert_eq!(path.with_added_extension("").with_added_extension("txt"), PathBuf::from("foo.tar.gz.txt"));
3193 ///
3194 /// let path = Path::new("/");
3195 /// assert_eq!(path.with_added_extension("gz"), PathBuf::from("/"));
3196 /// let path = Path::new("/dir/");
3197 /// assert_eq!(path.with_added_extension("gz"), PathBuf::from("/dir.gz"));
3198 /// let path = Path::new("/dir/..");
3199 /// assert_eq!(path.with_added_extension("gz"), PathBuf::from("/dir/.."));
3200 /// ```
3201 #[stable(feature = "path_add_extension", since = "1.91.0")]
3202 pub fn with_added_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
3203 let mut new_path = self.to_path_buf();
3204 new_path.add_extension(extension);
3205 new_path
3206 }
3207
3208 /// Produces an iterator over the [`Component`]s of the path.
3209 ///
3210 /// When parsing the path, there is a small amount of normalization:
3211 ///
3212 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
3213 /// `a` and `b` as components.
3214 ///
3215 /// * Occurrences of `.` are normalized away, except if they are at the
3216 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
3217 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
3218 /// an additional [`CurDir`] component.
3219 ///
3220 /// * Trailing separators are normalized away, so `/a/b` and `/a/b/` are equivalent.
3221 ///
3222 /// Note that no other normalization takes place; in particular, `a/c`
3223 /// and `a/b/../c` are distinct, to account for the possibility that `b`
3224 /// is a symbolic link (so its parent isn't `a`).
3225 ///
3226 /// # Examples
3227 ///
3228 /// ```
3229 /// use std::path::{Path, Component};
3230 /// use std::ffi::OsStr;
3231 ///
3232 /// let mut components = Path::new("/tmp/foo.txt").components();
3233 ///
3234 /// assert_eq!(components.next(), Some(Component::RootDir));
3235 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
3236 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
3237 /// assert_eq!(components.next(), None)
3238 /// ```
3239 ///
3240 /// [`CurDir`]: Component::CurDir
3241 #[stable(feature = "rust1", since = "1.0.0")]
3242 pub fn components(&self) -> Components<'_> {
3243 let prefix = parse_prefix(self.as_os_str());
3244 Components {
3245 path: self.as_u8_slice(),
3246 prefix,
3247 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
3248 // use a platform-specific initial state to avoid one turn of
3249 // the state-machine when the platform doesn't have a Prefix.
3250 front: const { if HAS_PREFIXES { State::Prefix } else { State::StartDir } },
3251 back: State::Body,
3252 }
3253 }
3254
3255 /// Produces an iterator over the path's components viewed as [`OsStr`]
3256 /// slices.
3257 ///
3258 /// For more information about the particulars of how the path is separated
3259 /// into components, see [`components`].
3260 ///
3261 /// [`components`]: Path::components
3262 ///
3263 /// # Examples
3264 ///
3265 /// ```
3266 /// use std::path::{self, Path};
3267 /// use std::ffi::OsStr;
3268 ///
3269 /// let mut it = Path::new("/tmp/foo.txt").iter();
3270 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
3271 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
3272 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
3273 /// assert_eq!(it.next(), None)
3274 /// ```
3275 #[stable(feature = "rust1", since = "1.0.0")]
3276 #[inline]
3277 pub fn iter(&self) -> Iter<'_> {
3278 Iter { inner: self.components() }
3279 }
3280
3281 /// Returns an object that implements [`Display`] for safely printing paths
3282 /// that may contain non-Unicode data. This may perform lossy conversion,
3283 /// depending on the platform. If you would like an implementation which
3284 /// escapes the path please use [`Debug`] instead.
3285 ///
3286 /// [`Display`]: fmt::Display
3287 /// [`Debug`]: fmt::Debug
3288 ///
3289 /// # Examples
3290 ///
3291 /// ```
3292 /// use std::path::Path;
3293 ///
3294 /// let path = Path::new("/tmp/foo.rs");
3295 ///
3296 /// println!("{}", path.display());
3297 /// ```
3298 #[stable(feature = "rust1", since = "1.0.0")]
3299 #[must_use = "this does not display the path, \
3300 it returns an object that can be displayed"]
3301 #[inline]
3302 pub fn display(&self) -> Display<'_> {
3303 Display { inner: self.inner.display() }
3304 }
3305
3306 /// Returns the same path as `&Path`.
3307 ///
3308 /// This method is redundant when used directly on `&Path`, but
3309 /// it helps dereferencing other `PathBuf`-like types to `Path`s,
3310 /// for example references to `Box<Path>` or `Arc<Path>`.
3311 #[inline]
3312 #[unstable(feature = "str_as_str", issue = "130366")]
3313 pub const fn as_path(&self) -> &Path {
3314 self
3315 }
3316
3317 /// Queries the file system to get information about a file, directory, etc.
3318 ///
3319 /// This function will traverse symbolic links to query information about the
3320 /// destination file.
3321 ///
3322 /// This is an alias to [`fs::metadata`].
3323 ///
3324 /// # Examples
3325 ///
3326 /// ```no_run
3327 /// use std::path::Path;
3328 ///
3329 /// let path = Path::new("/Minas/tirith");
3330 /// let metadata = path.metadata().expect("the path should point to an existing file or directory");
3331 /// println!("{:?}", metadata.file_type());
3332 /// ```
3333 #[stable(feature = "path_ext", since = "1.5.0")]
3334 #[inline]
3335 pub fn metadata(&self) -> io::Result<fs::Metadata> {
3336 fs::metadata(self)
3337 }
3338
3339 /// Queries the metadata about a file without following symlinks.
3340 ///
3341 /// This is an alias to [`fs::symlink_metadata`].
3342 ///
3343 /// # Examples
3344 ///
3345 /// ```no_run
3346 /// use std::path::Path;
3347 ///
3348 /// let path = Path::new("/Minas/tirith");
3349 /// let metadata = path.symlink_metadata().expect("the path should exist");
3350 /// println!("{:?}", metadata.file_type());
3351 /// ```
3352 #[stable(feature = "path_ext", since = "1.5.0")]
3353 #[inline]
3354 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
3355 fs::symlink_metadata(self)
3356 }
3357
3358 /// Returns the canonical, absolute form of the path with all intermediate
3359 /// components normalized and symbolic links resolved.
3360 ///
3361 /// This is an alias to [`fs::canonicalize`].
3362 ///
3363 /// # Errors
3364 ///
3365 /// This method will return an error in the following situations, but is not
3366 /// limited to just these cases:
3367 ///
3368 /// * `path` does not exist.
3369 /// * A non-final component in path is not a directory.
3370 ///
3371 /// # Examples
3372 ///
3373 /// ```no_run
3374 /// use std::path::{Path, PathBuf};
3375 ///
3376 /// let path = Path::new("/foo/test/../test/bar.rs");
3377 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
3378 /// ```
3379 #[stable(feature = "path_ext", since = "1.5.0")]
3380 #[inline]
3381 pub fn canonicalize(&self) -> io::Result<PathBuf> {
3382 fs::canonicalize(self)
3383 }
3384
3385 /// Makes the path absolute without accessing the filesystem.
3386 ///
3387 /// This is an alias to [`path::absolute`](absolute).
3388 ///
3389 /// # Errors
3390 ///
3391 /// This function may return an error in the following situations:
3392 ///
3393 /// * If the path is syntactically invalid; in particular, if it is empty.
3394 /// * If getting the [current directory][crate::env::current_dir] fails.
3395 ///
3396 /// # Examples
3397 ///
3398 /// ```no_run
3399 /// #![feature(path_absolute_method)]
3400 /// use std::path::Path;
3401 ///
3402 /// let path = Path::new("foo/./bar");
3403 /// let absolute = path.absolute()?;
3404 /// assert!(absolute.is_absolute());
3405 /// # Ok::<(), std::io::Error>(())
3406 /// ```
3407 #[unstable(feature = "path_absolute_method", issue = "153328")]
3408 #[inline]
3409 pub fn absolute(&self) -> io::Result<PathBuf> {
3410 absolute(self)
3411 }
3412
3413 /// Normalize a path, including `..` without traversing the filesystem.
3414 ///
3415 /// Returns an error if normalization would leave leading `..` components.
3416 ///
3417 /// <div class="warning">
3418 ///
3419 /// This function always resolves `..` to the "lexical" parent.
3420 /// That is "a/b/../c" will always resolve to `a/c` which can change the meaning of the path.
3421 /// In particular, `a/c` and `a/b/../c` are distinct on many systems because `b` may be a symbolic link, so its parent isn't `a`.
3422 ///
3423 /// </div>
3424 ///
3425 /// On Windows this will convert all `/` to `\` unless a [verbatim](Prefix::is_verbatim()) path is given.
3426 ///
3427 /// [`path::absolute`](absolute) is an alternative that preserves `..`.
3428 /// Or [`Path::canonicalize`] can be used to resolve any `..` by querying the filesystem.
3429 #[unstable(feature = "normalize_lexically", issue = "134694")]
3430 pub fn normalize_lexically(&self) -> Result<PathBuf, NormalizeError> {
3431 let mut lexical = PathBuf::new();
3432 let mut iter = self.components().peekable();
3433
3434 // Find the root, if any, and add it to the lexical path.
3435 // Here we treat the Windows path "C:\" as a single "root" even though
3436 // `components` splits it into two: (Prefix, RootDir).
3437 let root = match iter.peek() {
3438 Some(Component::ParentDir) => return Err(NormalizeError),
3439 Some(p @ Component::RootDir) | Some(p @ Component::CurDir) => {
3440 lexical.push(p);
3441 iter.next();
3442 lexical.as_os_str().len()
3443 }
3444 Some(Component::Prefix(prefix)) => {
3445 lexical.push(prefix.as_os_str());
3446 iter.next();
3447 if let Some(p @ Component::RootDir) = iter.peek() {
3448 lexical.push(p);
3449 iter.next();
3450 }
3451 lexical.as_os_str().len()
3452 }
3453 None => return Ok(PathBuf::new()),
3454 Some(Component::Normal(_)) => 0,
3455 };
3456
3457 for component in iter {
3458 match component {
3459 Component::RootDir => unreachable!(),
3460 Component::Prefix(_) => return Err(NormalizeError),
3461 Component::CurDir => continue,
3462 Component::ParentDir => {
3463 // It's an error if ParentDir causes us to go above the "root".
3464 if lexical.as_os_str().len() == root {
3465 return Err(NormalizeError);
3466 } else {
3467 lexical.pop();
3468 }
3469 }
3470 Component::Normal(path) => lexical.push(path),
3471 }
3472 }
3473 Ok(lexical)
3474 }
3475
3476 /// Reads a symbolic link, returning the file that the link points to.
3477 ///
3478 /// This is an alias to [`fs::read_link`].
3479 ///
3480 /// # Examples
3481 ///
3482 /// ```no_run
3483 /// use std::path::Path;
3484 ///
3485 /// let path = Path::new("/laputa/sky_castle.rs");
3486 /// let path_link = path.read_link().expect("the path should be an existing symbolic link");
3487 /// ```
3488 #[stable(feature = "path_ext", since = "1.5.0")]
3489 #[inline]
3490 pub fn read_link(&self) -> io::Result<PathBuf> {
3491 fs::read_link(self)
3492 }
3493
3494 /// Returns an iterator over the entries within a directory.
3495 ///
3496 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
3497 /// errors may be encountered after an iterator is initially constructed.
3498 ///
3499 /// This is an alias to [`fs::read_dir`].
3500 ///
3501 /// # Examples
3502 ///
3503 /// ```no_run
3504 /// use std::path::Path;
3505 ///
3506 /// let path = Path::new("/laputa");
3507 /// for entry in path.read_dir().expect("the path should point to an existing directory") {
3508 /// if let Ok(entry) = entry {
3509 /// println!("{:?}", entry.path());
3510 /// }
3511 /// }
3512 /// ```
3513 #[stable(feature = "path_ext", since = "1.5.0")]
3514 #[inline]
3515 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
3516 fs::read_dir(self)
3517 }
3518
3519 /// Returns `true` if the path points at an existing entity.
3520 ///
3521 /// Warning: this method may be error-prone, consider using [`try_exists()`] instead!
3522 /// It also has a risk of introducing time-of-check to time-of-use ([TOCTOU]) bugs.
3523 ///
3524 /// This function will traverse symbolic links to query information about the
3525 /// destination file.
3526 ///
3527 /// If you cannot access the metadata of the file, e.g. because of a
3528 /// permission error or broken symbolic links, this will return `false`.
3529 ///
3530 /// # Examples
3531 ///
3532 /// ```no_run
3533 /// use std::path::Path;
3534 /// assert!(!Path::new("does_not_exist.txt").exists());
3535 /// ```
3536 ///
3537 /// # See Also
3538 ///
3539 /// This is a convenience function that coerces errors to false. If you want to
3540 /// check errors, call [`Path::try_exists`].
3541 ///
3542 /// [`try_exists()`]: Self::try_exists
3543 /// [TOCTOU]: fs#time-of-check-to-time-of-use-toctou
3544 #[stable(feature = "path_ext", since = "1.5.0")]
3545 #[must_use]
3546 #[inline]
3547 pub fn exists(&self) -> bool {
3548 fs::metadata(self).is_ok()
3549 }
3550
3551 /// Returns `Ok(true)` if the path points at an existing entity.
3552 ///
3553 /// This function will traverse symbolic links to query information about the
3554 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
3555 ///
3556 /// [`Path::exists()`] only checks whether or not a path was both found and readable. By
3557 /// contrast, `try_exists` will return `Ok(true)` or `Ok(false)`, respectively, if the path
3558 /// was _verified_ to exist or not exist. If its existence can neither be confirmed nor
3559 /// denied, it will propagate an `Err(_)` instead. This can be the case if e.g. listing
3560 /// permission is denied on one of the parent directories.
3561 ///
3562 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3563 /// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3564 /// where those bugs are not an issue.
3565 ///
3566 /// This is an alias for [`std::fs::exists`](crate::fs::exists).
3567 ///
3568 /// # Examples
3569 ///
3570 /// ```no_run
3571 /// use std::path::Path;
3572 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("the path's existence should be verifiable"));
3573 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
3574 /// ```
3575 ///
3576 /// [TOCTOU]: fs#time-of-check-to-time-of-use-toctou
3577 /// [`exists()`]: Self::exists
3578 #[stable(feature = "path_try_exists", since = "1.63.0")]
3579 #[inline]
3580 pub fn try_exists(&self) -> io::Result<bool> {
3581 fs::exists(self)
3582 }
3583
3584 /// Returns `true` if the path exists on disk and is pointing at a regular file.
3585 ///
3586 /// This function will traverse symbolic links to query information about the
3587 /// destination file.
3588 ///
3589 /// If you cannot access the metadata of the file, e.g. because of a
3590 /// permission error or broken symbolic links, this will return `false`.
3591 ///
3592 /// # Examples
3593 ///
3594 /// ```no_run
3595 /// use std::path::Path;
3596 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
3597 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
3598 /// ```
3599 ///
3600 /// # See Also
3601 ///
3602 /// This is a convenience function that coerces errors to false. If you want to
3603 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
3604 /// [`fs::Metadata::is_file`] if it was [`Ok`].
3605 ///
3606 /// When the goal is simply to read from (or write to) the source, the most
3607 /// reliable way to test the source can be read (or written to) is to open
3608 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
3609 /// a Unix-like system for example. See [`fs::File::open`] or
3610 /// [`fs::OpenOptions::open`] for more information.
3611 #[stable(feature = "path_ext", since = "1.5.0")]
3612 #[must_use]
3613 pub fn is_file(&self) -> bool {
3614 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
3615 }
3616
3617 /// Returns `true` if the path exists on disk and is pointing at a directory.
3618 ///
3619 /// This function will traverse symbolic links to query information about the
3620 /// destination file.
3621 ///
3622 /// If you cannot access the metadata of the file, e.g. because of a
3623 /// permission error or broken symbolic links, this will return `false`.
3624 ///
3625 /// # Examples
3626 ///
3627 /// ```no_run
3628 /// use std::path::Path;
3629 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
3630 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
3631 /// ```
3632 ///
3633 /// # See Also
3634 ///
3635 /// This is a convenience function that coerces errors to false. If you want to
3636 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
3637 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
3638 #[stable(feature = "path_ext", since = "1.5.0")]
3639 #[must_use]
3640 pub fn is_dir(&self) -> bool {
3641 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
3642 }
3643
3644 /// Returns `true` if the path exists on disk and is pointing at a symbolic link.
3645 ///
3646 /// This function will not traverse symbolic links.
3647 /// In case of a broken symbolic link this will also return true.
3648 ///
3649 /// If you cannot access the directory containing the file, e.g., because of a
3650 /// permission error, this will return false.
3651 ///
3652 /// # Examples
3653 ///
3654 /// ```rust,no_run
3655 /// # #[cfg(unix)] {
3656 /// use std::path::Path;
3657 /// use std::os::unix::fs::symlink;
3658 ///
3659 /// let link_path = Path::new("link");
3660 /// symlink("/origin_does_not_exist/", link_path).unwrap();
3661 /// assert_eq!(link_path.is_symlink(), true);
3662 /// assert_eq!(link_path.exists(), false);
3663 /// # }
3664 /// ```
3665 ///
3666 /// # See Also
3667 ///
3668 /// This is a convenience function that coerces errors to false. If you want to
3669 /// check errors, call [`fs::symlink_metadata`] and handle its [`Result`]. Then call
3670 /// [`fs::Metadata::is_symlink`] if it was [`Ok`].
3671 #[must_use]
3672 #[stable(feature = "is_symlink", since = "1.58.0")]
3673 pub fn is_symlink(&self) -> bool {
3674 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
3675 }
3676
3677 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
3678 /// allocating.
3679 #[stable(feature = "into_boxed_path", since = "1.20.0")]
3680 #[must_use = "`self` will be dropped if the result is not used"]
3681 pub fn into_path_buf(self: Box<Self>) -> PathBuf {
3682 let rw = Box::into_raw(self) as *mut OsStr;
3683 let inner = unsafe { Box::from_raw(rw) };
3684 PathBuf { inner: OsString::from(inner) }
3685 }
3686}
3687
3688#[unstable(feature = "clone_to_uninit", issue = "126799")]
3689unsafe impl CloneToUninit for Path {
3690 #[inline]
3691 #[cfg_attr(debug_assertions, track_caller)]
3692 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
3693 // SAFETY: Path is just a transparent wrapper around OsStr
3694 unsafe { self.inner.clone_to_uninit(dst) }
3695 }
3696}
3697
3698#[stable(feature = "rust1", since = "1.0.0")]
3699#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3700const impl AsRef<OsStr> for Path {
3701 #[inline]
3702 fn as_ref(&self) -> &OsStr {
3703 &self.inner
3704 }
3705}
3706
3707#[stable(feature = "rust1", since = "1.0.0")]
3708impl fmt::Debug for Path {
3709 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3710 fmt::Debug::fmt(&self.inner, formatter)
3711 }
3712}
3713
3714/// Helper struct for safely printing paths with [`format!`] and `{}`.
3715///
3716/// A [`Path`] might contain non-Unicode data. This `struct` implements the
3717/// [`Display`] trait in a way that mitigates that. It is created by the
3718/// [`display`](Path::display) method on [`Path`]. This may perform lossy
3719/// conversion, depending on the platform. If you would like an implementation
3720/// which escapes the path please use [`Debug`] instead.
3721///
3722/// # Examples
3723///
3724/// ```
3725/// use std::path::Path;
3726///
3727/// let path = Path::new("/tmp/foo.rs");
3728///
3729/// println!("{}", path.display());
3730/// ```
3731///
3732/// [`Display`]: fmt::Display
3733/// [`format!`]: crate::format
3734#[stable(feature = "rust1", since = "1.0.0")]
3735pub struct Display<'a> {
3736 inner: os_str::Display<'a>,
3737}
3738
3739#[stable(feature = "rust1", since = "1.0.0")]
3740impl fmt::Debug for Display<'_> {
3741 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3742 fmt::Debug::fmt(&self.inner, f)
3743 }
3744}
3745
3746#[stable(feature = "rust1", since = "1.0.0")]
3747impl fmt::Display for Display<'_> {
3748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3749 fmt::Display::fmt(&self.inner, f)
3750 }
3751}
3752
3753#[stable(feature = "rust1", since = "1.0.0")]
3754impl PartialEq for Path {
3755 #[inline]
3756 fn eq(&self, other: &Path) -> bool {
3757 self.components() == other.components()
3758 }
3759}
3760
3761#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3762impl cmp::PartialEq<str> for Path {
3763 #[inline]
3764 fn eq(&self, other: &str) -> bool {
3765 let other: &OsStr = other.as_ref();
3766 self == other
3767 }
3768}
3769
3770#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3771impl cmp::PartialEq<Path> for str {
3772 #[inline]
3773 fn eq(&self, other: &Path) -> bool {
3774 other == self
3775 }
3776}
3777
3778#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3779impl cmp::PartialEq<String> for Path {
3780 #[inline]
3781 fn eq(&self, other: &String) -> bool {
3782 self == other.as_str()
3783 }
3784}
3785
3786#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3787impl cmp::PartialEq<Path> for String {
3788 #[inline]
3789 fn eq(&self, other: &Path) -> bool {
3790 self.as_str() == other
3791 }
3792}
3793
3794#[stable(feature = "rust1", since = "1.0.0")]
3795impl Hash for Path {
3796 fn hash<H: Hasher>(&self, h: &mut H) {
3797 let bytes = self.as_u8_slice();
3798 let (prefix_len, verbatim) = match parse_prefix(&self.inner) {
3799 Some(prefix) => {
3800 prefix.hash(h);
3801 (prefix.len(), prefix.is_verbatim())
3802 }
3803 None => (0, false),
3804 };
3805 let bytes = &bytes[prefix_len..];
3806
3807 let mut component_start = 0;
3808 // track some extra state to avoid prefix collisions.
3809 // ["foo", "bar"] and ["foobar"], will have the same payload bytes
3810 // but result in different chunk_bits
3811 let mut chunk_bits: usize = 0;
3812
3813 for i in 0..bytes.len() {
3814 let is_sep = if verbatim { is_verbatim_sep(bytes[i]) } else { is_sep_byte(bytes[i]) };
3815 if is_sep {
3816 if i > component_start {
3817 let to_hash = &bytes[component_start..i];
3818 chunk_bits = chunk_bits.wrapping_add(to_hash.len());
3819 chunk_bits = chunk_bits.rotate_right(2);
3820 h.write(to_hash);
3821 }
3822
3823 // skip over separator and optionally a following CurDir item
3824 // since components() would normalize these away.
3825 component_start = i + 1;
3826
3827 let tail = &bytes[component_start..];
3828
3829 if !verbatim {
3830 component_start += match tail {
3831 [b'.'] => 1,
3832 [b'.', sep, ..] if is_sep_byte(*sep) => 1,
3833 _ => 0,
3834 };
3835 }
3836 }
3837 }
3838
3839 if component_start < bytes.len() {
3840 let to_hash = &bytes[component_start..];
3841 chunk_bits = chunk_bits.wrapping_add(to_hash.len());
3842 chunk_bits = chunk_bits.rotate_right(2);
3843 h.write(to_hash);
3844 }
3845
3846 h.write_usize(chunk_bits);
3847 }
3848}
3849
3850#[stable(feature = "rust1", since = "1.0.0")]
3851impl Eq for Path {}
3852
3853#[stable(feature = "rust1", since = "1.0.0")]
3854impl PartialOrd for Path {
3855 #[inline]
3856 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
3857 Some(compare_components(self.components(), other.components()))
3858 }
3859}
3860
3861#[stable(feature = "rust1", since = "1.0.0")]
3862impl Ord for Path {
3863 #[inline]
3864 fn cmp(&self, other: &Path) -> cmp::Ordering {
3865 compare_components(self.components(), other.components())
3866 }
3867}
3868
3869#[stable(feature = "rust1", since = "1.0.0")]
3870#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3871const impl AsRef<Path> for Path {
3872 #[inline]
3873 fn as_ref(&self) -> &Path {
3874 self
3875 }
3876}
3877
3878#[stable(feature = "rust1", since = "1.0.0")]
3879#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3880const impl AsRef<Path> for OsStr {
3881 #[inline]
3882 fn as_ref(&self) -> &Path {
3883 Path::new(self)
3884 }
3885}
3886
3887#[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
3888impl AsRef<Path> for Cow<'_, OsStr> {
3889 #[inline]
3890 fn as_ref(&self) -> &Path {
3891 Path::new(self)
3892 }
3893}
3894
3895#[stable(feature = "rust1", since = "1.0.0")]
3896impl AsRef<Path> for OsString {
3897 #[inline]
3898 fn as_ref(&self) -> &Path {
3899 Path::new(self)
3900 }
3901}
3902
3903#[stable(feature = "rust1", since = "1.0.0")]
3904impl AsRef<Path> for str {
3905 #[inline]
3906 fn as_ref(&self) -> &Path {
3907 Path::new(self)
3908 }
3909}
3910
3911#[stable(feature = "rust1", since = "1.0.0")]
3912impl AsRef<Path> for String {
3913 #[inline]
3914 fn as_ref(&self) -> &Path {
3915 Path::new(self)
3916 }
3917}
3918
3919#[stable(feature = "rust1", since = "1.0.0")]
3920impl AsRef<Path> for PathBuf {
3921 #[inline]
3922 fn as_ref(&self) -> &Path {
3923 self
3924 }
3925}
3926
3927#[stable(feature = "path_into_iter", since = "1.6.0")]
3928impl<'a> IntoIterator for &'a PathBuf {
3929 type Item = &'a OsStr;
3930 type IntoIter = Iter<'a>;
3931 #[inline]
3932 fn into_iter(self) -> Iter<'a> {
3933 self.iter()
3934 }
3935}
3936
3937#[stable(feature = "path_into_iter", since = "1.6.0")]
3938impl<'a> IntoIterator for &'a Path {
3939 type Item = &'a OsStr;
3940 type IntoIter = Iter<'a>;
3941 #[inline]
3942 fn into_iter(self) -> Iter<'a> {
3943 self.iter()
3944 }
3945}
3946
3947macro_rules! impl_cmp {
3948 ($lhs:ty, $rhs: ty) => {
3949 #[stable(feature = "partialeq_path", since = "1.6.0")]
3950 impl PartialEq<$rhs> for $lhs {
3951 #[inline]
3952 fn eq(&self, other: &$rhs) -> bool {
3953 <Path as PartialEq>::eq(self, other)
3954 }
3955 }
3956
3957 #[stable(feature = "partialeq_path", since = "1.6.0")]
3958 impl PartialEq<$lhs> for $rhs {
3959 #[inline]
3960 fn eq(&self, other: &$lhs) -> bool {
3961 <Path as PartialEq>::eq(self, other)
3962 }
3963 }
3964
3965 #[stable(feature = "cmp_path", since = "1.8.0")]
3966 impl PartialOrd<$rhs> for $lhs {
3967 #[inline]
3968 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3969 <Path as PartialOrd>::partial_cmp(self, other)
3970 }
3971 }
3972
3973 #[stable(feature = "cmp_path", since = "1.8.0")]
3974 impl PartialOrd<$lhs> for $rhs {
3975 #[inline]
3976 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3977 <Path as PartialOrd>::partial_cmp(self, other)
3978 }
3979 }
3980 };
3981}
3982
3983impl_cmp!(PathBuf, Path);
3984impl_cmp!(PathBuf, &Path);
3985impl_cmp!(Cow<'_, Path>, Path);
3986impl_cmp!(Cow<'_, Path>, &Path);
3987impl_cmp!(Cow<'_, Path>, PathBuf);
3988
3989macro_rules! impl_cmp_os_str {
3990 ($lhs:ty, $rhs: ty) => {
3991 #[stable(feature = "cmp_path", since = "1.8.0")]
3992 impl PartialEq<$rhs> for $lhs {
3993 #[inline]
3994 fn eq(&self, other: &$rhs) -> bool {
3995 <Path as PartialEq>::eq(self, other.as_ref())
3996 }
3997 }
3998
3999 #[stable(feature = "cmp_path", since = "1.8.0")]
4000 impl PartialEq<$lhs> for $rhs {
4001 #[inline]
4002 fn eq(&self, other: &$lhs) -> bool {
4003 <Path as PartialEq>::eq(self.as_ref(), other)
4004 }
4005 }
4006
4007 #[stable(feature = "cmp_path", since = "1.8.0")]
4008 impl PartialOrd<$rhs> for $lhs {
4009 #[inline]
4010 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
4011 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
4012 }
4013 }
4014
4015 #[stable(feature = "cmp_path", since = "1.8.0")]
4016 impl PartialOrd<$lhs> for $rhs {
4017 #[inline]
4018 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
4019 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
4020 }
4021 }
4022 };
4023}
4024
4025impl_cmp_os_str!(PathBuf, OsStr);
4026impl_cmp_os_str!(PathBuf, &OsStr);
4027impl_cmp_os_str!(PathBuf, Cow<'_, OsStr>);
4028impl_cmp_os_str!(PathBuf, OsString);
4029impl_cmp_os_str!(Path, OsStr);
4030impl_cmp_os_str!(Path, &OsStr);
4031impl_cmp_os_str!(Path, Cow<'_, OsStr>);
4032impl_cmp_os_str!(Path, OsString);
4033impl_cmp_os_str!(&Path, OsStr);
4034impl_cmp_os_str!(&Path, Cow<'_, OsStr>);
4035impl_cmp_os_str!(&Path, OsString);
4036impl_cmp_os_str!(Cow<'_, Path>, OsStr);
4037impl_cmp_os_str!(Cow<'_, Path>, &OsStr);
4038impl_cmp_os_str!(Cow<'_, Path>, OsString);
4039
4040#[stable(since = "1.7.0", feature = "strip_prefix")]
4041impl fmt::Display for StripPrefixError {
4042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4043 "prefix not found".fmt(f)
4044 }
4045}
4046
4047#[stable(since = "1.7.0", feature = "strip_prefix")]
4048impl Error for StripPrefixError {}
4049
4050#[unstable(feature = "normalize_lexically", issue = "134694")]
4051impl fmt::Display for NormalizeError {
4052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4053 f.write_str("parent reference `..` points outside of base directory")
4054 }
4055}
4056#[unstable(feature = "normalize_lexically", issue = "134694")]
4057impl Error for NormalizeError {}
4058
4059/// Makes the path absolute without accessing the filesystem.
4060///
4061/// If the path is relative, the current directory is used as the base directory.
4062/// All intermediate components will be resolved according to platform-specific
4063/// rules, but unlike [`canonicalize`][crate::fs::canonicalize], this does not
4064/// resolve symlinks and may succeed even if the path does not exist.
4065///
4066/// If the `path` is empty or getting the
4067/// [current directory][crate::env::current_dir] fails, then an error will be
4068/// returned.
4069///
4070/// # Platform-specific behavior
4071///
4072/// On POSIX platforms, the path is resolved using [POSIX semantics][posix-semantics],
4073/// except that it stops short of resolving symlinks. This means it will keep `..`
4074/// components and trailing separators.
4075///
4076/// On Windows, for verbatim paths, this will simply return the path as given. For other
4077/// paths, this is currently equivalent to calling
4078/// [`GetFullPathNameW`][windows-path].
4079///
4080/// On Cygwin, this is currently equivalent to calling [`cygwin_conv_path`][cygwin-path]
4081/// with mode `CCP_WIN_A_TO_POSIX`, and then being processed like other POSIX platforms.
4082/// If a Windows path is given, it will be converted to an absolute POSIX path without
4083/// keeping `..`.
4084///
4085/// Note that these [may change in the future][changes].
4086///
4087/// # Errors
4088///
4089/// This function may return an error in the following situations:
4090///
4091/// * If `path` is syntactically invalid; in particular, if it is empty.
4092/// * If getting the [current directory][crate::env::current_dir] fails.
4093///
4094/// # Examples
4095///
4096/// ## POSIX paths
4097///
4098/// ```
4099/// # #[cfg(unix)]
4100/// fn main() -> std::io::Result<()> {
4101/// use std::path::{self, Path};
4102///
4103/// // Relative to absolute
4104/// let absolute = path::absolute("foo/./bar")?;
4105/// assert!(absolute.ends_with("foo/bar"));
4106///
4107/// // Absolute to absolute
4108/// let absolute = path::absolute("/foo//test/.././bar.rs")?;
4109/// assert_eq!(absolute, Path::new("/foo/test/../bar.rs"));
4110/// Ok(())
4111/// }
4112/// # #[cfg(not(unix))]
4113/// # fn main() {}
4114/// ```
4115///
4116/// ## Windows paths
4117///
4118/// ```
4119/// # #[cfg(windows)]
4120/// fn main() -> std::io::Result<()> {
4121/// use std::path::{self, Path};
4122///
4123/// // Relative to absolute
4124/// let absolute = path::absolute("foo/./bar")?;
4125/// assert!(absolute.ends_with(r"foo\bar"));
4126///
4127/// // Absolute to absolute
4128/// let absolute = path::absolute(r"C:\foo//test\..\./bar.rs")?;
4129///
4130/// assert_eq!(absolute, Path::new(r"C:\foo\bar.rs"));
4131/// Ok(())
4132/// }
4133/// # #[cfg(not(windows))]
4134/// # fn main() {}
4135/// ```
4136///
4137/// Note that this [may change in the future][changes].
4138///
4139/// [changes]: io#platform-specific-behavior
4140/// [posix-semantics]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap04.html#tag_04_16
4141/// [windows-path]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
4142/// [cygwin-path]: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html
4143#[stable(feature = "absolute_path", since = "1.79.0")]
4144pub fn absolute<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
4145 let path = path.as_ref();
4146 if path.as_os_str().is_empty() {
4147 Err(io::const_error!(io::ErrorKind::InvalidInput, "cannot make an empty path absolute"))
4148 } else {
4149 sys::path::absolute(path)
4150 }
4151}