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