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