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