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