1 //! Cross-platform path manipulation.
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.
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.
17 //! Path manipulation includes both parsing components from slices and building
20 //! To parse a path, you can create a [`Path`] slice from a [`str`]
21 //! slice and start asking questions:
24 //! use std::path::Path;
25 //! use std::ffi::OsStr;
27 //! let path = Path::new("/tmp/foo/bar.txt");
29 //! let parent = path.parent();
30 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
32 //! let file_stem = path.file_stem();
33 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
35 //! let extension = path.extension();
36 //! assert_eq!(extension, Some(OsStr::new("txt")));
39 //! To build or modify paths, use [`PathBuf`]:
42 //! use std::path::PathBuf;
44 //! // This way works...
45 //! let mut path = PathBuf::from("c:\\");
47 //! path.push("windows");
48 //! path.push("system32");
50 //! path.set_extension("dll");
52 //! // ... but push is best used if you don't know everything up
53 //! // front. If you do, this way is better:
54 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
57 //! [`components`]: Path::components
58 //! [`push`]: PathBuf::push
60 #![stable(feature = "rust1", since = "1.0.0")]
61 #![deny(unsafe_op_in_unsafe_fn)]
66 use crate::borrow
::{Borrow, Cow}
;
68 use crate::error
::Error
;
71 use crate::hash
::{Hash, Hasher}
;
73 use crate::iter
::{self, FusedIterator}
;
74 use crate::ops
::{self, Deref}
;
76 use crate::str::FromStr
;
79 use crate::ffi
::{OsStr, OsString}
;
81 use crate::sys
::path
::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR}
;
83 ////////////////////////////////////////////////////////////////////////////////
85 ////////////////////////////////////////////////////////////////////////////////
87 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
88 // taking advantage of the fact that OsStr always encodes ASCII characters
89 // as-is. Eventually, this transmutation should be replaced by direct uses of
90 // OsStr APIs for parsing, but it will take a while for those to become
93 ////////////////////////////////////////////////////////////////////////////////
95 ////////////////////////////////////////////////////////////////////////////////
97 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
99 /// Windows uses a variety of path prefix styles, including references to drive
100 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
101 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
102 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
103 /// no normalization is performed.
108 /// use std::path::{Component, Path, Prefix};
109 /// use std::path::Prefix::*;
110 /// use std::ffi::OsStr;
112 /// fn get_path_prefix(s: &str) -> Prefix {
113 /// let path = Path::new(s);
114 /// match path.components().next().unwrap() {
115 /// Component::Prefix(prefix_component) => prefix_component.kind(),
120 /// # if cfg!(windows) {
121 /// assert_eq!(Verbatim(OsStr::new("pictures")),
122 /// get_path_prefix(r"\\?\pictures\kittens"));
123 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
124 /// get_path_prefix(r"\\?\UNC\server\share"));
125 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
126 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
127 /// get_path_prefix(r"\\.\BrainInterface"));
128 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
129 /// get_path_prefix(r"\\server\share"));
130 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
133 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub enum Prefix
<'a
> {
136 /// Verbatim prefix, e.g., `\\?\cat_pics`.
138 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
140 #[stable(feature = "rust1", since = "1.0.0")]
141 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
143 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
144 /// e.g., `\\?\UNC\server\share`.
146 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
147 /// server's hostname and a share name.
148 #[stable(feature = "rust1", since = "1.0.0")]
150 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
151 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
154 /// Verbatim disk prefix, e.g., `\\?\C:`.
156 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
157 /// drive letter and `:`.
158 #[stable(feature = "rust1", since = "1.0.0")]
159 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
161 /// Device namespace prefix, e.g., `\\.\COM42`.
163 /// Device namespace prefixes consist of `\\.\` immediately followed by the
165 #[stable(feature = "rust1", since = "1.0.0")]
166 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
168 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
169 /// `\\server\share`.
171 /// UNC prefixes consist of the server's hostname and a share name.
172 #[stable(feature = "rust1", since = "1.0.0")]
174 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
175 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
178 /// Prefix `C:` for the given disk drive.
179 #[stable(feature = "rust1", since = "1.0.0")]
180 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
183 impl<'a
> Prefix
<'a
> {
185 fn len(&self) -> usize {
187 fn os_str_len(s
: &OsStr
) -> usize {
188 os_str_as_u8_slice(s
).len()
191 Verbatim(x
) => 4 + os_str_len(x
),
192 VerbatimUNC(x
, y
) => {
193 8 + os_str_len(x
) + if os_str_len(y
) > 0 { 1 + os_str_len(y) }
else { 0 }
195 VerbatimDisk(_
) => 6,
196 UNC(x
, y
) => 2 + os_str_len(x
) + if os_str_len(y
) > 0 { 1 + os_str_len(y) }
else { 0 }
,
197 DeviceNS(x
) => 4 + os_str_len(x
),
202 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
207 /// use std::path::Prefix::*;
208 /// use std::ffi::OsStr;
210 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
211 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
212 /// assert!(VerbatimDisk(b'C').is_verbatim());
213 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
214 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
215 /// assert!(!Disk(b'C').is_verbatim());
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn is_verbatim(&self) -> bool
{
221 matches
!(*self, Verbatim(_
) | VerbatimDisk(_
) | VerbatimUNC(..))
225 fn is_drive(&self) -> bool
{
226 matches
!(*self, Prefix
::Disk(_
))
230 fn has_implicit_root(&self) -> bool
{
235 ////////////////////////////////////////////////////////////////////////////////
236 // Exposed parsing helpers
237 ////////////////////////////////////////////////////////////////////////////////
239 /// Determines whether the character is one of the permitted path
240 /// separators for the current platform.
247 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
248 /// assert!(!path::is_separator('❤'));
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn is_separator(c
: char) -> bool
{
252 c
.is_ascii() && is_sep_byte(c
as u8)
255 /// The primary separator of path components for the current platform.
257 /// For example, `/` on Unix and `\` on Windows.
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub const MAIN_SEPARATOR
: char = crate::sys
::path
::MAIN_SEP
;
261 ////////////////////////////////////////////////////////////////////////////////
263 ////////////////////////////////////////////////////////////////////////////////
265 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
266 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
267 // `iter` after having exhausted `prefix`.
268 fn iter_after
<'a
, 'b
, I
, J
>(mut iter
: I
, mut prefix
: J
) -> Option
<I
>
270 I
: Iterator
<Item
= Component
<'a
>> + Clone
,
271 J
: Iterator
<Item
= Component
<'b
>>,
274 let mut iter_next
= iter
.clone();
275 match (iter_next
.next(), prefix
.next()) {
276 (Some(ref x
), Some(ref y
)) if x
== y
=> (),
277 (Some(_
), Some(_
)) => return None
,
278 (Some(_
), None
) => return Some(iter
),
279 (None
, None
) => return Some(iter
),
280 (None
, Some(_
)) => return None
,
286 // See note at the top of this module to understand why these are used:
288 // These casts are safe as OsStr is internally a wrapper around [u8] on all
291 // Note that currently this relies on the special knowledge that libstd has;
292 // these types are single-element structs but are not marked repr(transparent)
293 // or repr(C) which would make these casts allowable outside std.
294 fn os_str_as_u8_slice(s
: &OsStr
) -> &[u8] {
295 unsafe { &*(s as *const OsStr as *const [u8]) }
297 unsafe fn u8_slice_as_os_str(s
: &[u8]) -> &OsStr
{
298 // SAFETY: see the comment of `os_str_as_u8_slice`
299 unsafe { &*(s as *const [u8] as *const OsStr) }
302 // Detect scheme on Redox
303 fn has_redox_scheme(s
: &[u8]) -> bool
{
304 cfg
!(target_os
= "redox") && s
.contains(&b'
:'
)
307 ////////////////////////////////////////////////////////////////////////////////
308 // Cross-platform, iterator-independent parsing
309 ////////////////////////////////////////////////////////////////////////////////
311 /// Says whether the first byte after the prefix is a separator.
312 fn has_physical_root(s
: &[u8], prefix
: Option
<Prefix
<'_
>>) -> bool
{
313 let path
= if let Some(p
) = prefix { &s[p.len()..] }
else { s }
;
314 !path
.is_empty() && is_sep_byte(path
[0])
317 // basic workhorse for splitting stem and extension
318 fn split_file_at_dot(file
: &OsStr
) -> (Option
<&OsStr
>, Option
<&OsStr
>) {
319 if os_str_as_u8_slice(file
) == b
".." {
320 return (Some(file
), None
);
323 // The unsafety here stems from converting between &OsStr and &[u8]
324 // and back. This is safe to do because (1) we only look at ASCII
325 // contents of the encoding and (2) new &OsStr values are produced
326 // only from ASCII-bounded slices of existing &OsStr values.
327 let mut iter
= os_str_as_u8_slice(file
).rsplitn(2, |b
| *b
== b'
.'
);
328 let after
= iter
.next();
329 let before
= iter
.next();
330 if before
== Some(b
"") {
333 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
337 ////////////////////////////////////////////////////////////////////////////////
338 // The core iterators
339 ////////////////////////////////////////////////////////////////////////////////
341 /// Component parsing works by a double-ended state machine; the cursors at the
342 /// front and back of the path each keep track of what parts of the path have
343 /// been consumed so far.
345 /// Going front to back, a path is made up of a prefix, a starting
346 /// directory component, and a body (of normal components)
347 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
350 StartDir
= 1, // / or . or nothing
351 Body
= 2, // foo/bar/baz
355 /// A structure wrapping a Windows path prefix as well as its unparsed string
358 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
359 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
360 /// returned by [`as_os_str`].
362 /// Instances of this `struct` can be obtained by matching against the
363 /// [`Prefix` variant] on [`Component`].
365 /// Does not occur on Unix.
370 /// # if cfg!(windows) {
371 /// use std::path::{Component, Path, Prefix};
372 /// use std::ffi::OsStr;
374 /// let path = Path::new(r"c:\you\later\");
375 /// match path.components().next().unwrap() {
376 /// Component::Prefix(prefix_component) => {
377 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
378 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
380 /// _ => unreachable!(),
385 /// [`as_os_str`]: PrefixComponent::as_os_str
386 /// [`kind`]: PrefixComponent::kind
387 /// [`Prefix` variant]: Component::Prefix
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[derive(Copy, Clone, Eq, Debug)]
390 pub struct PrefixComponent
<'a
> {
391 /// The prefix as an unparsed `OsStr` slice.
394 /// The parsed prefix data.
398 impl<'a
> PrefixComponent
<'a
> {
399 /// Returns the parsed prefix data.
401 /// See [`Prefix`]'s documentation for more information on the different
402 /// kinds of prefixes.
403 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn kind(&self) -> Prefix
<'a
> {
409 /// Returns the raw [`OsStr`] slice for this prefix.
410 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn as_os_str(&self) -> &'a OsStr
{
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<'a
> cmp
::PartialEq
for PrefixComponent
<'a
> {
420 fn eq(&self, other
: &PrefixComponent
<'a
>) -> bool
{
421 cmp
::PartialEq
::eq(&self.parsed
, &other
.parsed
)
425 #[stable(feature = "rust1", since = "1.0.0")]
426 impl<'a
> cmp
::PartialOrd
for PrefixComponent
<'a
> {
428 fn partial_cmp(&self, other
: &PrefixComponent
<'a
>) -> Option
<cmp
::Ordering
> {
429 cmp
::PartialOrd
::partial_cmp(&self.parsed
, &other
.parsed
)
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl cmp
::Ord
for PrefixComponent
<'_
> {
436 fn cmp(&self, other
: &Self) -> cmp
::Ordering
{
437 cmp
::Ord
::cmp(&self.parsed
, &other
.parsed
)
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl Hash
for PrefixComponent
<'_
> {
443 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
448 /// A single component of a path.
450 /// A `Component` roughly corresponds to a substring between path separators
453 /// This `enum` is created by iterating over [`Components`], which in turn is
454 /// created by the [`components`](Path::components) method on [`Path`].
459 /// use std::path::{Component, Path};
461 /// let path = Path::new("/tmp/foo/bar.txt");
462 /// let components = path.components().collect::<Vec<_>>();
463 /// assert_eq!(&components, &[
464 /// Component::RootDir,
465 /// Component::Normal("tmp".as_ref()),
466 /// Component::Normal("foo".as_ref()),
467 /// Component::Normal("bar.txt".as_ref()),
470 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
471 #[stable(feature = "rust1", since = "1.0.0")]
472 pub enum Component
<'a
> {
473 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
475 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
478 /// Does not occur on Unix.
479 #[stable(feature = "rust1", since = "1.0.0")]
480 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
482 /// The root directory component, appears after any prefix and before anything else.
484 /// It represents a separator that designates that a path starts from root.
485 #[stable(feature = "rust1", since = "1.0.0")]
488 /// A reference to the current directory, i.e., `.`.
489 #[stable(feature = "rust1", since = "1.0.0")]
492 /// A reference to the parent directory, i.e., `..`.
493 #[stable(feature = "rust1", since = "1.0.0")]
496 /// A normal component, e.g., `a` and `b` in `a/b`.
498 /// This variant is the most common one, it represents references to files
500 #[stable(feature = "rust1", since = "1.0.0")]
501 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
504 impl<'a
> Component
<'a
> {
505 /// Extracts the underlying [`OsStr`] slice.
510 /// use std::path::Path;
512 /// let path = Path::new("./tmp/foo/bar.txt");
513 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
514 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn as_os_str(self) -> &'a OsStr
{
519 Component
::Prefix(p
) => p
.as_os_str(),
520 Component
::RootDir
=> OsStr
::new(MAIN_SEP_STR
),
521 Component
::CurDir
=> OsStr
::new("."),
522 Component
::ParentDir
=> OsStr
::new(".."),
523 Component
::Normal(path
) => path
,
528 #[stable(feature = "rust1", since = "1.0.0")]
529 impl AsRef
<OsStr
> for Component
<'_
> {
531 fn as_ref(&self) -> &OsStr
{
536 #[stable(feature = "path_component_asref", since = "1.25.0")]
537 impl AsRef
<Path
> for Component
<'_
> {
539 fn as_ref(&self) -> &Path
{
540 self.as_os_str().as_ref()
544 /// An iterator over the [`Component`]s of a [`Path`].
546 /// This `struct` is created by the [`components`] method on [`Path`].
547 /// See its documentation for more.
552 /// use std::path::Path;
554 /// let path = Path::new("/tmp/foo/bar.txt");
556 /// for component in path.components() {
557 /// println!("{:?}", component);
561 /// [`components`]: Path::components
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub struct Components
<'a
> {
565 // The path left to parse components from
568 // The prefix as it was originally parsed, if any
569 prefix
: Option
<Prefix
<'a
>>,
571 // true if path *physically* has a root separator; for most Windows
572 // prefixes, it may have a "logical" root separator for the purposes of
573 // normalization, e.g., \\server\share == \\server\share\.
574 has_physical_root
: bool
,
576 // The iterator is double-ended, and these two states keep track of what has
577 // been produced from either end
582 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
584 /// This `struct` is created by the [`iter`] method on [`Path`].
585 /// See its documentation for more.
587 /// [`iter`]: Path::iter
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub struct Iter
<'a
> {
591 inner
: Components
<'a
>,
594 #[stable(feature = "path_components_debug", since = "1.13.0")]
595 impl fmt
::Debug
for Components
<'_
> {
596 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
597 struct DebugHelper
<'a
>(&'a Path
);
599 impl fmt
::Debug
for DebugHelper
<'_
> {
600 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
601 f
.debug_list().entries(self.0.components()).finish()
605 f
.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
609 impl<'a
> Components
<'a
> {
610 // how long is the prefix, if any?
612 fn prefix_len(&self) -> usize {
613 self.prefix
.as_ref().map(Prefix
::len
).unwrap_or(0)
617 fn prefix_verbatim(&self) -> bool
{
618 self.prefix
.as_ref().map(Prefix
::is_verbatim
).unwrap_or(false)
621 /// how much of the prefix is left from the point of view of iteration?
623 fn prefix_remaining(&self) -> usize {
624 if self.front
== State
::Prefix { self.prefix_len() }
else { 0 }
627 // Given the iteration so far, how much of the pre-State::Body path is left?
629 fn len_before_body(&self) -> usize {
630 let root
= if self.front
<= State
::StartDir
&& self.has_physical_root { 1 }
else { 0 }
;
631 let cur_dir
= if self.front
<= State
::StartDir
&& self.include_cur_dir() { 1 }
else { 0 }
;
632 self.prefix_remaining() + root
+ cur_dir
635 // is the iteration complete?
637 fn finished(&self) -> bool
{
638 self.front
== State
::Done
|| self.back
== State
::Done
|| self.front
> self.back
642 fn is_sep_byte(&self, b
: u8) -> bool
{
643 if self.prefix_verbatim() { is_verbatim_sep(b) }
else { is_sep_byte(b) }
646 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
651 /// use std::path::Path;
653 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
654 /// components.next();
655 /// components.next();
657 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
659 #[stable(feature = "rust1", since = "1.0.0")]
660 pub fn as_path(&self) -> &'a Path
{
661 let mut comps
= self.clone();
662 if comps
.front
== State
::Body
{
665 if comps
.back
== State
::Body
{
668 unsafe { Path::from_u8_slice(comps.path) }
671 /// Is the *original* path rooted?
672 fn has_root(&self) -> bool
{
673 if self.has_physical_root
{
676 if let Some(p
) = self.prefix
{
677 if p
.has_implicit_root() {
684 /// Should the normalized path include a leading . ?
685 fn include_cur_dir(&self) -> bool
{
689 let mut iter
= self.path
[self.prefix_len()..].iter();
690 match (iter
.next(), iter
.next()) {
691 (Some(&b'
.'
), None
) => true,
692 (Some(&b'
.'
), Some(&b
)) => self.is_sep_byte(b
),
697 // parse a given byte sequence into the corresponding path component
698 fn parse_single_component
<'b
>(&self, comp
: &'b
[u8]) -> Option
<Component
<'b
>> {
700 b
"." if self.prefix_verbatim() => Some(Component
::CurDir
),
701 b
"." => None
, // . components are normalized away, except at
702 // the beginning of a path, which is treated
703 // separately via `include_cur_dir`
704 b
".." => Some(Component
::ParentDir
),
706 _
=> Some(Component
::Normal(unsafe { u8_slice_as_os_str(comp) }
)),
710 // parse a component from the left, saying how many bytes to consume to
711 // remove the component
712 fn parse_next_component(&self) -> (usize, Option
<Component
<'a
>>) {
713 debug_assert
!(self.front
== State
::Body
);
714 let (extra
, comp
) = match self.path
.iter().position(|b
| self.is_sep_byte(*b
)) {
715 None
=> (0, self.path
),
716 Some(i
) => (1, &self.path
[..i
]),
718 (comp
.len() + extra
, self.parse_single_component(comp
))
721 // parse a component from the right, saying how many bytes to consume to
722 // remove the component
723 fn parse_next_component_back(&self) -> (usize, Option
<Component
<'a
>>) {
724 debug_assert
!(self.back
== State
::Body
);
725 let start
= self.len_before_body();
726 let (extra
, comp
) = match self.path
[start
..].iter().rposition(|b
| self.is_sep_byte(*b
)) {
727 None
=> (0, &self.path
[start
..]),
728 Some(i
) => (1, &self.path
[start
+ i
+ 1..]),
730 (comp
.len() + extra
, self.parse_single_component(comp
))
733 // trim away repeated separators (i.e., empty components) on the left
734 fn trim_left(&mut self) {
735 while !self.path
.is_empty() {
736 let (size
, comp
) = self.parse_next_component();
740 self.path
= &self.path
[size
..];
745 // trim away repeated separators (i.e., empty components) on the right
746 fn trim_right(&mut self) {
747 while self.path
.len() > self.len_before_body() {
748 let (size
, comp
) = self.parse_next_component_back();
752 self.path
= &self.path
[..self.path
.len() - size
];
758 #[stable(feature = "rust1", since = "1.0.0")]
759 impl AsRef
<Path
> for Components
<'_
> {
761 fn as_ref(&self) -> &Path
{
766 #[stable(feature = "rust1", since = "1.0.0")]
767 impl AsRef
<OsStr
> for Components
<'_
> {
769 fn as_ref(&self) -> &OsStr
{
770 self.as_path().as_os_str()
774 #[stable(feature = "path_iter_debug", since = "1.13.0")]
775 impl fmt
::Debug
for Iter
<'_
> {
776 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
777 struct DebugHelper
<'a
>(&'a Path
);
779 impl fmt
::Debug
for DebugHelper
<'_
> {
780 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
781 f
.debug_list().entries(self.0.iter
()).finish()
785 f
.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
790 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
795 /// use std::path::Path;
797 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
801 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
803 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn as_path(&self) -> &'a Path
{
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl AsRef
<Path
> for Iter
<'_
> {
813 fn as_ref(&self) -> &Path
{
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl AsRef
<OsStr
> for Iter
<'_
> {
821 fn as_ref(&self) -> &OsStr
{
822 self.as_path().as_os_str()
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<'a
> Iterator
for Iter
<'a
> {
828 type Item
= &'a OsStr
;
831 fn next(&mut self) -> Option
<&'a OsStr
> {
832 self.inner
.next().map(Component
::as_os_str
)
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<'a
> DoubleEndedIterator
for Iter
<'a
> {
839 fn next_back(&mut self) -> Option
<&'a OsStr
> {
840 self.inner
.next_back().map(Component
::as_os_str
)
844 #[stable(feature = "fused", since = "1.26.0")]
845 impl FusedIterator
for Iter
<'_
> {}
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<'a
> Iterator
for Components
<'a
> {
849 type Item
= Component
<'a
>;
851 fn next(&mut self) -> Option
<Component
<'a
>> {
852 while !self.finished() {
854 State
::Prefix
if self.prefix_len() > 0 => {
855 self.front
= State
::StartDir
;
856 debug_assert
!(self.prefix_len() <= self.path
.len());
857 let raw
= &self.path
[..self.prefix_len()];
858 self.path
= &self.path
[self.prefix_len()..];
859 return Some(Component
::Prefix(PrefixComponent
{
860 raw
: unsafe { u8_slice_as_os_str(raw) }
,
861 parsed
: self.prefix
.unwrap(),
865 self.front
= State
::StartDir
;
868 self.front
= State
::Body
;
869 if self.has_physical_root
{
870 debug_assert
!(!self.path
.is_empty());
871 self.path
= &self.path
[1..];
872 return Some(Component
::RootDir
);
873 } else if let Some(p
) = self.prefix
{
874 if p
.has_implicit_root() && !p
.is_verbatim() {
875 return Some(Component
::RootDir
);
877 } else if self.include_cur_dir() {
878 debug_assert
!(!self.path
.is_empty());
879 self.path
= &self.path
[1..];
880 return Some(Component
::CurDir
);
883 State
::Body
if !self.path
.is_empty() => {
884 let (size
, comp
) = self.parse_next_component();
885 self.path
= &self.path
[size
..];
891 self.front
= State
::Done
;
893 State
::Done
=> unreachable
!(),
900 #[stable(feature = "rust1", since = "1.0.0")]
901 impl<'a
> DoubleEndedIterator
for Components
<'a
> {
902 fn next_back(&mut self) -> Option
<Component
<'a
>> {
903 while !self.finished() {
905 State
::Body
if self.path
.len() > self.len_before_body() => {
906 let (size
, comp
) = self.parse_next_component_back();
907 self.path
= &self.path
[..self.path
.len() - size
];
913 self.back
= State
::StartDir
;
916 self.back
= State
::Prefix
;
917 if self.has_physical_root
{
918 self.path
= &self.path
[..self.path
.len() - 1];
919 return Some(Component
::RootDir
);
920 } else if let Some(p
) = self.prefix
{
921 if p
.has_implicit_root() && !p
.is_verbatim() {
922 return Some(Component
::RootDir
);
924 } else if self.include_cur_dir() {
925 self.path
= &self.path
[..self.path
.len() - 1];
926 return Some(Component
::CurDir
);
929 State
::Prefix
if self.prefix_len() > 0 => {
930 self.back
= State
::Done
;
931 return Some(Component
::Prefix(PrefixComponent
{
932 raw
: unsafe { u8_slice_as_os_str(self.path) }
,
933 parsed
: self.prefix
.unwrap(),
937 self.back
= State
::Done
;
940 State
::Done
=> unreachable
!(),
947 #[stable(feature = "fused", since = "1.26.0")]
948 impl FusedIterator
for Components
<'_
> {}
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl<'a
> cmp
::PartialEq
for Components
<'a
> {
953 fn eq(&self, other
: &Components
<'a
>) -> bool
{
954 Iterator
::eq(self.clone(), other
.clone())
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl cmp
::Eq
for Components
<'_
> {}
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a
> cmp
::PartialOrd
for Components
<'a
> {
964 fn partial_cmp(&self, other
: &Components
<'a
>) -> Option
<cmp
::Ordering
> {
965 Iterator
::partial_cmp(self.clone(), other
.clone())
969 #[stable(feature = "rust1", since = "1.0.0")]
970 impl cmp
::Ord
for Components
<'_
> {
972 fn cmp(&self, other
: &Self) -> cmp
::Ordering
{
973 Iterator
::cmp(self.clone(), other
.clone())
977 /// An iterator over [`Path`] and its ancestors.
979 /// This `struct` is created by the [`ancestors`] method on [`Path`].
980 /// See its documentation for more.
985 /// use std::path::Path;
987 /// let path = Path::new("/foo/bar");
989 /// for ancestor in path.ancestors() {
990 /// println!("{}", ancestor.display());
994 /// [`ancestors`]: Path::ancestors
995 #[derive(Copy, Clone, Debug)]
996 #[stable(feature = "path_ancestors", since = "1.28.0")]
997 pub struct Ancestors
<'a
> {
998 next
: Option
<&'a Path
>,
1001 #[stable(feature = "path_ancestors", since = "1.28.0")]
1002 impl<'a
> Iterator
for Ancestors
<'a
> {
1003 type Item
= &'a Path
;
1006 fn next(&mut self) -> Option
<Self::Item
> {
1007 let next
= self.next
;
1008 self.next
= next
.and_then(Path
::parent
);
1013 #[stable(feature = "path_ancestors", since = "1.28.0")]
1014 impl FusedIterator
for Ancestors
<'_
> {}
1016 ////////////////////////////////////////////////////////////////////////////////
1017 // Basic types and traits
1018 ////////////////////////////////////////////////////////////////////////////////
1020 /// An owned, mutable path (akin to [`String`]).
1022 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1023 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1024 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1026 /// [`push`]: PathBuf::push
1027 /// [`set_extension`]: PathBuf::set_extension
1029 /// More details about the overall approach can be found in
1030 /// the [module documentation](self).
1034 /// You can use [`push`] to build up a `PathBuf` from
1038 /// use std::path::PathBuf;
1040 /// let mut path = PathBuf::new();
1042 /// path.push(r"C:\");
1043 /// path.push("windows");
1044 /// path.push("system32");
1046 /// path.set_extension("dll");
1049 /// However, [`push`] is best used for dynamic situations. This is a better way
1050 /// to do this when you know all of the components ahead of time:
1053 /// use std::path::PathBuf;
1055 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1058 /// We can still do better than this! Since these are all strings, we can use
1062 /// use std::path::PathBuf;
1064 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1067 /// Which method works best depends on what kind of situation you're in.
1068 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1069 #[stable(feature = "rust1", since = "1.0.0")]
1071 // `PathBuf::as_mut_vec` current implementation relies
1072 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1073 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1074 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1075 // not documented and must not be relied upon.
1076 pub struct PathBuf
{
1082 fn as_mut_vec(&mut self) -> &mut Vec
<u8> {
1083 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1086 /// Allocates an empty `PathBuf`.
1091 /// use std::path::PathBuf;
1093 /// let path = PathBuf::new();
1095 #[stable(feature = "rust1", since = "1.0.0")]
1097 pub fn new() -> PathBuf
{
1098 PathBuf { inner: OsString::new() }
1101 /// Creates a new `PathBuf` with a given capacity used to create the
1102 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1107 /// use std::path::PathBuf;
1109 /// let mut path = PathBuf::with_capacity(10);
1110 /// let capacity = path.capacity();
1112 /// // This push is done without reallocating
1113 /// path.push(r"C:\");
1115 /// assert_eq!(capacity, path.capacity());
1118 /// [`with_capacity`]: OsString::with_capacity
1119 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1121 pub fn with_capacity(capacity
: usize) -> PathBuf
{
1122 PathBuf { inner: OsString::with_capacity(capacity) }
1125 /// Coerces to a [`Path`] slice.
1130 /// use std::path::{Path, PathBuf};
1132 /// let p = PathBuf::from("/test");
1133 /// assert_eq!(Path::new("/test"), p.as_path());
1135 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn as_path(&self) -> &Path
{
1141 /// Extends `self` with `path`.
1143 /// If `path` is absolute, it replaces the current path.
1147 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1148 /// replaces everything except for the prefix (if any) of `self`.
1149 /// * if `path` has a prefix but no root, it replaces `self`.
1153 /// Pushing a relative path extends the existing path:
1156 /// use std::path::PathBuf;
1158 /// let mut path = PathBuf::from("/tmp");
1159 /// path.push("file.bk");
1160 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1163 /// Pushing an absolute path replaces the existing path:
1166 /// use std::path::PathBuf;
1168 /// let mut path = PathBuf::from("/tmp");
1169 /// path.push("/etc");
1170 /// assert_eq!(path, PathBuf::from("/etc"));
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 pub fn push
<P
: AsRef
<Path
>>(&mut self, path
: P
) {
1174 self._push(path
.as_ref())
1177 fn _push(&mut self, path
: &Path
) {
1178 // in general, a separator is needed if the rightmost byte is not a separator
1179 let mut need_sep
= self.as_mut_vec().last().map(|c
| !is_sep_byte(*c
)).unwrap_or(false);
1181 // in the special case of `C:` on Windows, do *not* add a separator
1183 let comps
= self.components();
1184 if comps
.prefix_len() > 0
1185 && comps
.prefix_len() == comps
.path
.len()
1186 && comps
.prefix
.unwrap().is_drive()
1192 // absolute `path` replaces `self`
1193 if path
.is_absolute() || path
.prefix().is_some() {
1194 self.as_mut_vec().truncate(0);
1196 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1197 } else if path
.has_root() {
1198 let prefix_len
= self.components().prefix_remaining();
1199 self.as_mut_vec().truncate(prefix_len
);
1201 // `path` is a pure relative path
1202 } else if need_sep
{
1203 self.inner
.push(MAIN_SEP_STR
);
1206 self.inner
.push(path
);
1209 /// Truncates `self` to [`self.parent`].
1211 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1212 /// Otherwise, returns `true`.
1214 /// [`self.parent`]: Path::parent
1219 /// use std::path::{Path, PathBuf};
1221 /// let mut p = PathBuf::from("/spirited/away.rs");
1224 /// assert_eq!(Path::new("/spirited"), p);
1226 /// assert_eq!(Path::new("/"), p);
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub fn pop(&mut self) -> bool
{
1230 match self.parent().map(|p
| p
.as_u8_slice().len()) {
1232 self.as_mut_vec().truncate(len
);
1239 /// Updates [`self.file_name`] to `file_name`.
1241 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1244 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1245 /// `file_name`. The new path will be a sibling of the original path.
1246 /// (That is, it will have the same parent.)
1248 /// [`self.file_name`]: Path::file_name
1249 /// [`pop`]: PathBuf::pop
1254 /// use std::path::PathBuf;
1256 /// let mut buf = PathBuf::from("/");
1257 /// assert!(buf.file_name() == None);
1258 /// buf.set_file_name("bar");
1259 /// assert!(buf == PathBuf::from("/bar"));
1260 /// assert!(buf.file_name().is_some());
1261 /// buf.set_file_name("baz.txt");
1262 /// assert!(buf == PathBuf::from("/baz.txt"));
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub fn set_file_name
<S
: AsRef
<OsStr
>>(&mut self, file_name
: S
) {
1266 self._set_file_name(file_name
.as_ref())
1269 fn _set_file_name(&mut self, file_name
: &OsStr
) {
1270 if self.file_name().is_some() {
1271 let popped
= self.pop();
1272 debug_assert
!(popped
);
1274 self.push(file_name
);
1277 /// Updates [`self.extension`] to `extension`.
1279 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1280 /// returns `true` and updates the extension otherwise.
1282 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1285 /// [`self.file_name`]: Path::file_name
1286 /// [`self.extension`]: Path::extension
1291 /// use std::path::{Path, PathBuf};
1293 /// let mut p = PathBuf::from("/feel/the");
1295 /// p.set_extension("force");
1296 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1298 /// p.set_extension("dark_side");
1299 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub fn set_extension
<S
: AsRef
<OsStr
>>(&mut self, extension
: S
) -> bool
{
1303 self._set_extension(extension
.as_ref())
1306 fn _set_extension(&mut self, extension
: &OsStr
) -> bool
{
1307 let file_stem
= match self.file_stem() {
1308 None
=> return false,
1309 Some(f
) => os_str_as_u8_slice(f
),
1312 // truncate until right after the file stem
1313 let end_file_stem
= file_stem
[file_stem
.len()..].as_ptr() as usize;
1314 let start
= os_str_as_u8_slice(&self.inner
).as_ptr() as usize;
1315 let v
= self.as_mut_vec();
1316 v
.truncate(end_file_stem
.wrapping_sub(start
));
1318 // add the new extension, if any
1319 let new
= os_str_as_u8_slice(extension
);
1320 if !new
.is_empty() {
1321 v
.reserve_exact(new
.len() + 1);
1323 v
.extend_from_slice(new
);
1329 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1334 /// use std::path::PathBuf;
1336 /// let p = PathBuf::from("/the/head");
1337 /// let os_str = p.into_os_string();
1339 #[stable(feature = "rust1", since = "1.0.0")]
1341 pub fn into_os_string(self) -> OsString
{
1345 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1346 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1348 pub fn into_boxed_path(self) -> Box
<Path
> {
1349 let rw
= Box
::into_raw(self.inner
.into_boxed_os_str()) as *mut Path
;
1350 unsafe { Box::from_raw(rw) }
1353 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1355 /// [`capacity`]: OsString::capacity
1356 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1358 pub fn capacity(&self) -> usize {
1359 self.inner
.capacity()
1362 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1364 /// [`clear`]: OsString::clear
1365 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1367 pub fn clear(&mut self) {
1371 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1373 /// [`reserve`]: OsString::reserve
1374 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1376 pub fn reserve(&mut self, additional
: usize) {
1377 self.inner
.reserve(additional
)
1380 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1382 /// [`reserve_exact`]: OsString::reserve_exact
1383 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1385 pub fn reserve_exact(&mut self, additional
: usize) {
1386 self.inner
.reserve_exact(additional
)
1389 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1391 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1392 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1394 pub fn shrink_to_fit(&mut self) {
1395 self.inner
.shrink_to_fit()
1398 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1400 /// [`shrink_to`]: OsString::shrink_to
1401 #[unstable(feature = "shrink_to", issue = "56431")]
1403 pub fn shrink_to(&mut self, min_capacity
: usize) {
1404 self.inner
.shrink_to(min_capacity
)
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl Clone
for PathBuf
{
1411 fn clone(&self) -> Self {
1412 PathBuf { inner: self.inner.clone() }
1416 fn clone_from(&mut self, source
: &Self) {
1417 self.inner
.clone_from(&source
.inner
)
1421 #[stable(feature = "box_from_path", since = "1.17.0")]
1422 impl From
<&Path
> for Box
<Path
> {
1423 /// Creates a boxed [`Path`] from a reference.
1425 /// This will allocate and clone `path` to it.
1426 fn from(path
: &Path
) -> Box
<Path
> {
1427 let boxed
: Box
<OsStr
> = path
.inner
.into();
1428 let rw
= Box
::into_raw(boxed
) as *mut Path
;
1429 unsafe { Box::from_raw(rw) }
1433 #[stable(feature = "box_from_cow", since = "1.45.0")]
1434 impl From
<Cow
<'_
, Path
>> for Box
<Path
> {
1435 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1437 /// Converting from a `Cow::Owned` does not clone or allocate.
1439 fn from(cow
: Cow
<'_
, Path
>) -> Box
<Path
> {
1441 Cow
::Borrowed(path
) => Box
::from(path
),
1442 Cow
::Owned(path
) => Box
::from(path
),
1447 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1448 impl From
<Box
<Path
>> for PathBuf
{
1449 /// Converts a `Box<Path>` into a `PathBuf`
1451 /// This conversion does not allocate or copy memory.
1453 fn from(boxed
: Box
<Path
>) -> PathBuf
{
1454 boxed
.into_path_buf()
1458 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1459 impl From
<PathBuf
> for Box
<Path
> {
1460 /// Converts a `PathBuf` into a `Box<Path>`
1462 /// This conversion currently should not allocate memory,
1463 /// but this behavior is not guaranteed on all platforms or in all future versions.
1465 fn from(p
: PathBuf
) -> Box
<Path
> {
1470 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1471 impl Clone
for Box
<Path
> {
1473 fn clone(&self) -> Self {
1474 self.to_path_buf().into_boxed_path()
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<T
: ?Sized
+ AsRef
<OsStr
>> From
<&T
> for PathBuf
{
1480 /// Converts a borrowed `OsStr` to a `PathBuf`.
1482 /// Allocates a [`PathBuf`] and copies the data into it.
1484 fn from(s
: &T
) -> PathBuf
{
1485 PathBuf
::from(s
.as_ref().to_os_string())
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl From
<OsString
> for PathBuf
{
1491 /// Converts an [`OsString`] into a [`PathBuf`]
1493 /// This conversion does not allocate or copy memory.
1495 fn from(s
: OsString
) -> PathBuf
{
1496 PathBuf { inner: s }
1500 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1501 impl From
<PathBuf
> for OsString
{
1502 /// Converts a [`PathBuf`] into an [`OsString`]
1504 /// This conversion does not allocate or copy memory.
1506 fn from(path_buf
: PathBuf
) -> OsString
{
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl From
<String
> for PathBuf
{
1513 /// Converts a [`String`] into a [`PathBuf`]
1515 /// This conversion does not allocate or copy memory.
1517 fn from(s
: String
) -> PathBuf
{
1518 PathBuf
::from(OsString
::from(s
))
1522 #[stable(feature = "path_from_str", since = "1.32.0")]
1523 impl FromStr
for PathBuf
{
1524 type Err
= core
::convert
::Infallible
;
1527 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
1528 Ok(PathBuf
::from(s
))
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<P
: AsRef
<Path
>> iter
::FromIterator
<P
> for PathBuf
{
1534 fn from_iter
<I
: IntoIterator
<Item
= P
>>(iter
: I
) -> PathBuf
{
1535 let mut buf
= PathBuf
::new();
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 impl<P
: AsRef
<Path
>> iter
::Extend
<P
> for PathBuf
{
1543 fn extend
<I
: IntoIterator
<Item
= P
>>(&mut self, iter
: I
) {
1544 iter
.into_iter().for_each(move |p
| self.push(p
.as_ref()));
1548 fn extend_one(&mut self, p
: P
) {
1549 self.push(p
.as_ref());
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl fmt
::Debug
for PathBuf
{
1555 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1556 fmt
::Debug
::fmt(&**self, formatter
)
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl ops
::Deref
for PathBuf
{
1564 fn deref(&self) -> &Path
{
1565 Path
::new(&self.inner
)
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl Borrow
<Path
> for PathBuf
{
1572 fn borrow(&self) -> &Path
{
1577 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1578 impl Default
for PathBuf
{
1580 fn default() -> Self {
1585 #[stable(feature = "cow_from_path", since = "1.6.0")]
1586 impl<'a
> From
<&'a Path
> for Cow
<'a
, Path
> {
1587 /// Creates a clone-on-write pointer from a reference to
1590 /// This conversion does not clone or allocate.
1592 fn from(s
: &'a Path
) -> Cow
<'a
, Path
> {
1597 #[stable(feature = "cow_from_path", since = "1.6.0")]
1598 impl<'a
> From
<PathBuf
> for Cow
<'a
, Path
> {
1599 /// Creates a clone-on-write pointer from an owned
1600 /// instance of [`PathBuf`].
1602 /// This conversion does not clone or allocate.
1604 fn from(s
: PathBuf
) -> Cow
<'a
, Path
> {
1609 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1610 impl<'a
> From
<&'a PathBuf
> for Cow
<'a
, Path
> {
1611 /// Creates a clone-on-write pointer from a reference to
1614 /// This conversion does not clone or allocate.
1616 fn from(p
: &'a PathBuf
) -> Cow
<'a
, Path
> {
1617 Cow
::Borrowed(p
.as_path())
1621 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1622 impl<'a
> From
<Cow
<'a
, Path
>> for PathBuf
{
1623 /// Converts a clone-on-write pointer to an owned path.
1625 /// Converting from a `Cow::Owned` does not clone or allocate.
1627 fn from(p
: Cow
<'a
, Path
>) -> Self {
1632 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1633 impl From
<PathBuf
> for Arc
<Path
> {
1634 /// Converts a [`PathBuf`] into an [`Arc`] by moving the [`PathBuf`] data into a new [`Arc`] buffer.
1636 fn from(s
: PathBuf
) -> Arc
<Path
> {
1637 let arc
: Arc
<OsStr
> = Arc
::from(s
.into_os_string());
1638 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1642 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1643 impl From
<&Path
> for Arc
<Path
> {
1644 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1646 fn from(s
: &Path
) -> Arc
<Path
> {
1647 let arc
: Arc
<OsStr
> = Arc
::from(s
.as_os_str());
1648 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1652 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1653 impl From
<PathBuf
> for Rc
<Path
> {
1654 /// Converts a [`PathBuf`] into an [`Rc`] by moving the [`PathBuf`] data into a new `Rc` buffer.
1656 fn from(s
: PathBuf
) -> Rc
<Path
> {
1657 let rc
: Rc
<OsStr
> = Rc
::from(s
.into_os_string());
1658 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1662 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1663 impl From
<&Path
> for Rc
<Path
> {
1664 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new `Rc` buffer.
1666 fn from(s
: &Path
) -> Rc
<Path
> {
1667 let rc
: Rc
<OsStr
> = Rc
::from(s
.as_os_str());
1668 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 impl ToOwned
for Path
{
1674 type Owned
= PathBuf
;
1676 fn to_owned(&self) -> PathBuf
{
1680 fn clone_into(&self, target
: &mut PathBuf
) {
1681 self.inner
.clone_into(&mut target
.inner
);
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl cmp
::PartialEq
for PathBuf
{
1688 fn eq(&self, other
: &PathBuf
) -> bool
{
1689 self.components() == other
.components()
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 impl Hash
for PathBuf
{
1695 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
1696 self.as_path().hash(h
)
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 impl cmp
::Eq
for PathBuf {}
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 impl cmp
::PartialOrd
for PathBuf
{
1706 fn partial_cmp(&self, other
: &PathBuf
) -> Option
<cmp
::Ordering
> {
1707 self.components().partial_cmp(other
.components())
1711 #[stable(feature = "rust1", since = "1.0.0")]
1712 impl cmp
::Ord
for PathBuf
{
1714 fn cmp(&self, other
: &PathBuf
) -> cmp
::Ordering
{
1715 self.components().cmp(other
.components())
1719 #[stable(feature = "rust1", since = "1.0.0")]
1720 impl AsRef
<OsStr
> for PathBuf
{
1722 fn as_ref(&self) -> &OsStr
{
1727 /// A slice of a path (akin to [`str`]).
1729 /// This type supports a number of operations for inspecting a path, including
1730 /// breaking the path into its components (separated by `/` on Unix and by either
1731 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1732 /// is absolute, and so on.
1734 /// This is an *unsized* type, meaning that it must always be used behind a
1735 /// pointer like `&` or [`Box`]. For an owned version of this type,
1736 /// see [`PathBuf`].
1738 /// More details about the overall approach can be found in
1739 /// the [module documentation](self).
1744 /// use std::path::Path;
1745 /// use std::ffi::OsStr;
1747 /// // Note: this example does work on Windows
1748 /// let path = Path::new("./foo/bar.txt");
1750 /// let parent = path.parent();
1751 /// assert_eq!(parent, Some(Path::new("./foo")));
1753 /// let file_stem = path.file_stem();
1754 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1756 /// let extension = path.extension();
1757 /// assert_eq!(extension, Some(OsStr::new("txt")));
1759 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1760 #[stable(feature = "rust1", since = "1.0.0")]
1762 // `Path::new` current implementation relies
1763 // on `Path` being layout-compatible with `OsStr`.
1764 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1765 // Anyway, `Path` representation and layout are considered implementation detail, are
1766 // not documented and must not be relied upon.
1771 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1773 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1774 /// See its documentation for more.
1776 /// [`strip_prefix`]: Path::strip_prefix
1777 #[derive(Debug, Clone, PartialEq, Eq)]
1778 #[stable(since = "1.7.0", feature = "strip_prefix")]
1779 pub struct StripPrefixError(());
1782 // The following (private!) function allows construction of a path from a u8
1783 // slice, which is only safe when it is known to follow the OsStr encoding.
1784 unsafe fn from_u8_slice(s
: &[u8]) -> &Path
{
1785 unsafe { Path::new(u8_slice_as_os_str(s)) }
1787 // The following (private!) function reveals the byte encoding used for OsStr.
1788 fn as_u8_slice(&self) -> &[u8] {
1789 os_str_as_u8_slice(&self.inner
)
1792 /// Directly wraps a string slice as a `Path` slice.
1794 /// This is a cost-free conversion.
1799 /// use std::path::Path;
1801 /// Path::new("foo.txt");
1804 /// You can create `Path`s from `String`s, or even other `Path`s:
1807 /// use std::path::Path;
1809 /// let string = String::from("foo.txt");
1810 /// let from_string = Path::new(&string);
1811 /// let from_path = Path::new(&from_string);
1812 /// assert_eq!(from_string, from_path);
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 pub fn new
<S
: AsRef
<OsStr
> + ?Sized
>(s
: &S
) -> &Path
{
1816 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1819 /// Yields the underlying [`OsStr`] slice.
1824 /// use std::path::Path;
1826 /// let os_str = Path::new("foo.txt").as_os_str();
1827 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1829 #[stable(feature = "rust1", since = "1.0.0")]
1831 pub fn as_os_str(&self) -> &OsStr
{
1835 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1837 /// This conversion may entail doing a check for UTF-8 validity.
1838 /// Note that validation is performed because non-UTF-8 strings are
1839 /// perfectly valid for some OS.
1846 /// use std::path::Path;
1848 /// let path = Path::new("foo.txt");
1849 /// assert_eq!(path.to_str(), Some("foo.txt"));
1851 #[stable(feature = "rust1", since = "1.0.0")]
1853 pub fn to_str(&self) -> Option
<&str> {
1857 /// Converts a `Path` to a [`Cow<str>`].
1859 /// Any non-Unicode sequences are replaced with
1860 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1862 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1866 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1869 /// use std::path::Path;
1871 /// let path = Path::new("foo.txt");
1872 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1875 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1876 /// have returned `"fo�.txt"`.
1877 #[stable(feature = "rust1", since = "1.0.0")]
1879 pub fn to_string_lossy(&self) -> Cow
<'_
, str> {
1880 self.inner
.to_string_lossy()
1883 /// Converts a `Path` to an owned [`PathBuf`].
1888 /// use std::path::Path;
1890 /// let path_buf = Path::new("foo.txt").to_path_buf();
1891 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1893 #[rustc_conversion_suggestion]
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 pub fn to_path_buf(&self) -> PathBuf
{
1896 PathBuf
::from(self.inner
.to_os_string())
1899 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1900 /// the current directory.
1902 /// * On Unix, a path is absolute if it starts with the root, so
1903 /// `is_absolute` and [`has_root`] are equivalent.
1905 /// * On Windows, a path is absolute if it has a prefix and starts with the
1906 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1911 /// use std::path::Path;
1913 /// assert!(!Path::new("foo.txt").is_absolute());
1916 /// [`has_root`]: Path::has_root
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 #[allow(deprecated)]
1919 pub fn is_absolute(&self) -> bool
{
1920 if cfg
!(target_os
= "redox") {
1921 // FIXME: Allow Redox prefixes
1922 self.has_root() || has_redox_scheme(self.as_u8_slice())
1924 self.has_root() && (cfg
!(any(unix
, target_os
= "wasi")) || self.prefix().is_some())
1928 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1930 /// See [`is_absolute`]'s documentation for more details.
1935 /// use std::path::Path;
1937 /// assert!(Path::new("foo.txt").is_relative());
1940 /// [`is_absolute`]: Path::is_absolute
1941 #[stable(feature = "rust1", since = "1.0.0")]
1943 pub fn is_relative(&self) -> bool
{
1947 fn prefix(&self) -> Option
<Prefix
<'_
>> {
1948 self.components().prefix
1951 /// Returns `true` if the `Path` has a root.
1953 /// * On Unix, a path has a root if it begins with `/`.
1955 /// * On Windows, a path has a root if it:
1956 /// * has no prefix and begins with a separator, e.g., `\windows`
1957 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1958 /// * has any non-disk prefix, e.g., `\\server\share`
1963 /// use std::path::Path;
1965 /// assert!(Path::new("/etc/passwd").has_root());
1967 #[stable(feature = "rust1", since = "1.0.0")]
1969 pub fn has_root(&self) -> bool
{
1970 self.components().has_root()
1973 /// Returns the `Path` without its final component, if there is one.
1975 /// Returns [`None`] if the path terminates in a root or prefix.
1980 /// use std::path::Path;
1982 /// let path = Path::new("/foo/bar");
1983 /// let parent = path.parent().unwrap();
1984 /// assert_eq!(parent, Path::new("/foo"));
1986 /// let grand_parent = parent.parent().unwrap();
1987 /// assert_eq!(grand_parent, Path::new("/"));
1988 /// assert_eq!(grand_parent.parent(), None);
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 pub fn parent(&self) -> Option
<&Path
> {
1992 let mut comps
= self.components();
1993 let comp
= comps
.next_back();
1994 comp
.and_then(|p
| match p
{
1995 Component
::Normal(_
) | Component
::CurDir
| Component
::ParentDir
=> {
1996 Some(comps
.as_path())
2002 /// Produces an iterator over `Path` and its ancestors.
2004 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2005 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2006 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2007 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2013 /// use std::path::Path;
2015 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2016 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2017 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2018 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2019 /// assert_eq!(ancestors.next(), None);
2021 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2022 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2023 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2024 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2025 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2026 /// assert_eq!(ancestors.next(), None);
2029 /// [`parent`]: Path::parent
2030 #[stable(feature = "path_ancestors", since = "1.28.0")]
2032 pub fn ancestors(&self) -> Ancestors
<'_
> {
2033 Ancestors { next: Some(&self) }
2036 /// Returns the final component of the `Path`, if there is one.
2038 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2039 /// is the directory name.
2041 /// Returns [`None`] if the path terminates in `..`.
2046 /// use std::path::Path;
2047 /// use std::ffi::OsStr;
2049 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2050 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2051 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2052 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2053 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2054 /// assert_eq!(None, Path::new("/").file_name());
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 pub fn file_name(&self) -> Option
<&OsStr
> {
2058 self.components().next_back().and_then(|p
| match p
{
2059 Component
::Normal(p
) => Some(p
),
2064 /// Returns a path that, when joined onto `base`, yields `self`.
2068 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2069 /// returns `false`), returns [`Err`].
2071 /// [`starts_with`]: Path::starts_with
2076 /// use std::path::{Path, PathBuf};
2078 /// let path = Path::new("/test/haha/foo.txt");
2080 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2081 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2082 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2083 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2084 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2086 /// assert!(path.strip_prefix("test").is_err());
2087 /// assert!(path.strip_prefix("/haha").is_err());
2089 /// let prefix = PathBuf::from("/test/");
2090 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2092 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2093 pub fn strip_prefix
<P
>(&self, base
: P
) -> Result
<&Path
, StripPrefixError
>
2097 self._strip_prefix(base
.as_ref())
2100 fn _strip_prefix(&self, base
: &Path
) -> Result
<&Path
, StripPrefixError
> {
2101 iter_after(self.components(), base
.components())
2102 .map(|c
| c
.as_path())
2103 .ok_or(StripPrefixError(()))
2106 /// Determines whether `base` is a prefix of `self`.
2108 /// Only considers whole path components to match.
2113 /// use std::path::Path;
2115 /// let path = Path::new("/etc/passwd");
2117 /// assert!(path.starts_with("/etc"));
2118 /// assert!(path.starts_with("/etc/"));
2119 /// assert!(path.starts_with("/etc/passwd"));
2120 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2121 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2123 /// assert!(!path.starts_with("/e"));
2124 /// assert!(!path.starts_with("/etc/passwd.txt"));
2126 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 pub fn starts_with
<P
: AsRef
<Path
>>(&self, base
: P
) -> bool
{
2130 self._starts_with(base
.as_ref())
2133 fn _starts_with(&self, base
: &Path
) -> bool
{
2134 iter_after(self.components(), base
.components()).is_some()
2137 /// Determines whether `child` is a suffix of `self`.
2139 /// Only considers whole path components to match.
2144 /// use std::path::Path;
2146 /// let path = Path::new("/etc/resolv.conf");
2148 /// assert!(path.ends_with("resolv.conf"));
2149 /// assert!(path.ends_with("etc/resolv.conf"));
2150 /// assert!(path.ends_with("/etc/resolv.conf"));
2152 /// assert!(!path.ends_with("/resolv.conf"));
2153 /// assert!(!path.ends_with("conf")); // use .extension() instead
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 pub fn ends_with
<P
: AsRef
<Path
>>(&self, child
: P
) -> bool
{
2157 self._ends_with(child
.as_ref())
2160 fn _ends_with(&self, child
: &Path
) -> bool
{
2161 iter_after(self.components().rev(), child
.components().rev()).is_some()
2164 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2166 /// [`self.file_name`]: Path::file_name
2170 /// * [`None`], if there is no file name;
2171 /// * The entire file name if there is no embedded `.`;
2172 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2173 /// * Otherwise, the portion of the file name before the final `.`
2178 /// use std::path::Path;
2180 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2181 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 pub fn file_stem(&self) -> Option
<&OsStr
> {
2185 self.file_name().map(split_file_at_dot
).and_then(|(before
, after
)| before
.or(after
))
2188 /// Extracts the extension of [`self.file_name`], if possible.
2190 /// The extension is:
2192 /// * [`None`], if there is no file name;
2193 /// * [`None`], if there is no embedded `.`;
2194 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2195 /// * Otherwise, the portion of the file name after the final `.`
2197 /// [`self.file_name`]: Path::file_name
2202 /// use std::path::Path;
2204 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2205 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 pub fn extension(&self) -> Option
<&OsStr
> {
2209 self.file_name().map(split_file_at_dot
).and_then(|(before
, after
)| before
.and(after
))
2212 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2214 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2219 /// use std::path::{Path, PathBuf};
2221 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2223 #[stable(feature = "rust1", since = "1.0.0")]
2225 pub fn join
<P
: AsRef
<Path
>>(&self, path
: P
) -> PathBuf
{
2226 self._join(path
.as_ref())
2229 fn _join(&self, path
: &Path
) -> PathBuf
{
2230 let mut buf
= self.to_path_buf();
2235 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2237 /// See [`PathBuf::set_file_name`] for more details.
2242 /// use std::path::{Path, PathBuf};
2244 /// let path = Path::new("/tmp/foo.txt");
2245 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2247 /// let path = Path::new("/tmp");
2248 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2250 #[stable(feature = "rust1", since = "1.0.0")]
2251 pub fn with_file_name
<S
: AsRef
<OsStr
>>(&self, file_name
: S
) -> PathBuf
{
2252 self._with_file_name(file_name
.as_ref())
2255 fn _with_file_name(&self, file_name
: &OsStr
) -> PathBuf
{
2256 let mut buf
= self.to_path_buf();
2257 buf
.set_file_name(file_name
);
2261 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2263 /// See [`PathBuf::set_extension`] for more details.
2268 /// use std::path::{Path, PathBuf};
2270 /// let path = Path::new("foo.rs");
2271 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2273 /// let path = Path::new("foo.tar.gz");
2274 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2275 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2276 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 pub fn with_extension
<S
: AsRef
<OsStr
>>(&self, extension
: S
) -> PathBuf
{
2280 self._with_extension(extension
.as_ref())
2283 fn _with_extension(&self, extension
: &OsStr
) -> PathBuf
{
2284 let mut buf
= self.to_path_buf();
2285 buf
.set_extension(extension
);
2289 /// Produces an iterator over the [`Component`]s of the path.
2291 /// When parsing the path, there is a small amount of normalization:
2293 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2294 /// `a` and `b` as components.
2296 /// * Occurrences of `.` are normalized away, except if they are at the
2297 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2298 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2299 /// an additional [`CurDir`] component.
2301 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2303 /// Note that no other normalization takes place; in particular, `a/c`
2304 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2305 /// is a symbolic link (so its parent isn't `a`).
2310 /// use std::path::{Path, Component};
2311 /// use std::ffi::OsStr;
2313 /// let mut components = Path::new("/tmp/foo.txt").components();
2315 /// assert_eq!(components.next(), Some(Component::RootDir));
2316 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2317 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2318 /// assert_eq!(components.next(), None)
2321 /// [`CurDir`]: Component::CurDir
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 pub fn components(&self) -> Components
<'_
> {
2324 let prefix
= parse_prefix(self.as_os_str());
2326 path
: self.as_u8_slice(),
2328 has_physical_root
: has_physical_root(self.as_u8_slice(), prefix
)
2329 || has_redox_scheme(self.as_u8_slice()),
2330 front
: State
::Prefix
,
2335 /// Produces an iterator over the path's components viewed as [`OsStr`]
2338 /// For more information about the particulars of how the path is separated
2339 /// into components, see [`components`].
2341 /// [`components`]: Path::components
2346 /// use std::path::{self, Path};
2347 /// use std::ffi::OsStr;
2349 /// let mut it = Path::new("/tmp/foo.txt").iter();
2350 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2351 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2352 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2353 /// assert_eq!(it.next(), None)
2355 #[stable(feature = "rust1", since = "1.0.0")]
2357 pub fn iter(&self) -> Iter
<'_
> {
2358 Iter { inner: self.components() }
2361 /// Returns an object that implements [`Display`] for safely printing paths
2362 /// that may contain non-Unicode data. This may perform lossy conversion,
2363 /// depending on the platform. If you would like an implementation which
2364 /// escapes the path please use [`Debug`] instead.
2366 /// [`Display`]: fmt::Display
2371 /// use std::path::Path;
2373 /// let path = Path::new("/tmp/foo.rs");
2375 /// println!("{}", path.display());
2377 #[stable(feature = "rust1", since = "1.0.0")]
2379 pub fn display(&self) -> Display
<'_
> {
2380 Display { path: self }
2383 /// Queries the file system to get information about a file, directory, etc.
2385 /// This function will traverse symbolic links to query information about the
2386 /// destination file.
2388 /// This is an alias to [`fs::metadata`].
2393 /// use std::path::Path;
2395 /// let path = Path::new("/Minas/tirith");
2396 /// let metadata = path.metadata().expect("metadata call failed");
2397 /// println!("{:?}", metadata.file_type());
2399 #[stable(feature = "path_ext", since = "1.5.0")]
2401 pub fn metadata(&self) -> io
::Result
<fs
::Metadata
> {
2405 /// Queries the metadata about a file without following symlinks.
2407 /// This is an alias to [`fs::symlink_metadata`].
2412 /// use std::path::Path;
2414 /// let path = Path::new("/Minas/tirith");
2415 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2416 /// println!("{:?}", metadata.file_type());
2418 #[stable(feature = "path_ext", since = "1.5.0")]
2420 pub fn symlink_metadata(&self) -> io
::Result
<fs
::Metadata
> {
2421 fs
::symlink_metadata(self)
2424 /// Returns the canonical, absolute form of the path with all intermediate
2425 /// components normalized and symbolic links resolved.
2427 /// This is an alias to [`fs::canonicalize`].
2432 /// use std::path::{Path, PathBuf};
2434 /// let path = Path::new("/foo/test/../test/bar.rs");
2435 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2437 #[stable(feature = "path_ext", since = "1.5.0")]
2439 pub fn canonicalize(&self) -> io
::Result
<PathBuf
> {
2440 fs
::canonicalize(self)
2443 /// Reads a symbolic link, returning the file that the link points to.
2445 /// This is an alias to [`fs::read_link`].
2450 /// use std::path::Path;
2452 /// let path = Path::new("/laputa/sky_castle.rs");
2453 /// let path_link = path.read_link().expect("read_link call failed");
2455 #[stable(feature = "path_ext", since = "1.5.0")]
2457 pub fn read_link(&self) -> io
::Result
<PathBuf
> {
2461 /// Returns an iterator over the entries within a directory.
2463 /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
2464 /// errors may be encountered after an iterator is initially constructed.
2466 /// This is an alias to [`fs::read_dir`].
2471 /// use std::path::Path;
2473 /// let path = Path::new("/laputa");
2474 /// for entry in path.read_dir().expect("read_dir call failed") {
2475 /// if let Ok(entry) = entry {
2476 /// println!("{:?}", entry.path());
2480 #[stable(feature = "path_ext", since = "1.5.0")]
2482 pub fn read_dir(&self) -> io
::Result
<fs
::ReadDir
> {
2486 /// Returns `true` if the path points at an existing entity.
2488 /// This function will traverse symbolic links to query information about the
2489 /// destination file.
2491 /// If you cannot access the metadata of the file, e.g. because of a
2492 /// permission error or broken symbolic links, this will return `false`.
2497 /// use std::path::Path;
2498 /// assert!(!Path::new("does_not_exist.txt").exists());
2503 /// This is a convenience function that coerces errors to false. If you want to
2504 /// check errors, call [`fs::metadata`].
2505 #[stable(feature = "path_ext", since = "1.5.0")]
2507 pub fn exists(&self) -> bool
{
2508 fs
::metadata(self).is_ok()
2511 /// Returns `Ok(true)` if the path points at an existing entity.
2513 /// This function will traverse symbolic links to query information about the
2514 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2516 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2517 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2518 /// denied on some of the parent directories.)
2523 /// #![feature(path_try_exists)]
2525 /// use std::path::Path;
2526 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2527 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2529 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2531 #[unstable(feature = "path_try_exists", issue = "83186")]
2533 pub fn try_exists(&self) -> io
::Result
<bool
> {
2534 fs
::try_exists(self)
2537 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2539 /// This function will traverse symbolic links to query information about the
2540 /// destination file.
2542 /// If you cannot access the metadata of the file, e.g. because of a
2543 /// permission error or broken symbolic links, this will return `false`.
2548 /// use std::path::Path;
2549 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2550 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2555 /// This is a convenience function that coerces errors to false. If you want to
2556 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2557 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2559 /// When the goal is simply to read from (or write to) the source, the most
2560 /// reliable way to test the source can be read (or written to) is to open
2561 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2562 /// a Unix-like system for example. See [`fs::File::open`] or
2563 /// [`fs::OpenOptions::open`] for more information.
2564 #[stable(feature = "path_ext", since = "1.5.0")]
2565 pub fn is_file(&self) -> bool
{
2566 fs
::metadata(self).map(|m
| m
.is_file()).unwrap_or(false)
2569 /// Returns `true` if the path exists on disk and is pointing at a directory.
2571 /// This function will traverse symbolic links to query information about the
2572 /// destination file.
2574 /// If you cannot access the metadata of the file, e.g. because of a
2575 /// permission error or broken symbolic links, this will return `false`.
2580 /// use std::path::Path;
2581 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2582 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2587 /// This is a convenience function that coerces errors to false. If you want to
2588 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2589 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2590 #[stable(feature = "path_ext", since = "1.5.0")]
2591 pub fn is_dir(&self) -> bool
{
2592 fs
::metadata(self).map(|m
| m
.is_dir()).unwrap_or(false)
2595 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2597 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2598 pub fn into_path_buf(self: Box
<Path
>) -> PathBuf
{
2599 let rw
= Box
::into_raw(self) as *mut OsStr
;
2600 let inner
= unsafe { Box::from_raw(rw) }
;
2601 PathBuf { inner: OsString::from(inner) }
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 impl AsRef
<OsStr
> for Path
{
2608 fn as_ref(&self) -> &OsStr
{
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 impl fmt
::Debug
for Path
{
2615 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2616 fmt
::Debug
::fmt(&self.inner
, formatter
)
2620 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2622 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2623 /// [`Display`] trait in a way that mitigates that. It is created by the
2624 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2625 /// conversion, depending on the platform. If you would like an implementation
2626 /// which escapes the path please use [`Debug`] instead.
2631 /// use std::path::Path;
2633 /// let path = Path::new("/tmp/foo.rs");
2635 /// println!("{}", path.display());
2638 /// [`Display`]: fmt::Display
2639 /// [`format!`]: crate::format
2640 #[stable(feature = "rust1", since = "1.0.0")]
2641 pub struct Display
<'a
> {
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 impl fmt
::Debug
for Display
<'_
> {
2647 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2648 fmt
::Debug
::fmt(&self.path
, f
)
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 impl fmt
::Display
for Display
<'_
> {
2654 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2655 self.path
.inner
.display(f
)
2659 #[stable(feature = "rust1", since = "1.0.0")]
2660 impl cmp
::PartialEq
for Path
{
2662 fn eq(&self, other
: &Path
) -> bool
{
2663 self.components().eq(other
.components())
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl Hash
for Path
{
2669 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
2670 for component
in self.components() {
2676 #[stable(feature = "rust1", since = "1.0.0")]
2677 impl cmp
::Eq
for Path {}
2679 #[stable(feature = "rust1", since = "1.0.0")]
2680 impl cmp
::PartialOrd
for Path
{
2682 fn partial_cmp(&self, other
: &Path
) -> Option
<cmp
::Ordering
> {
2683 self.components().partial_cmp(other
.components())
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 impl cmp
::Ord
for Path
{
2690 fn cmp(&self, other
: &Path
) -> cmp
::Ordering
{
2691 self.components().cmp(other
.components())
2695 #[stable(feature = "rust1", since = "1.0.0")]
2696 impl AsRef
<Path
> for Path
{
2698 fn as_ref(&self) -> &Path
{
2703 #[stable(feature = "rust1", since = "1.0.0")]
2704 impl AsRef
<Path
> for OsStr
{
2706 fn as_ref(&self) -> &Path
{
2711 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2712 impl AsRef
<Path
> for Cow
<'_
, OsStr
> {
2714 fn as_ref(&self) -> &Path
{
2719 #[stable(feature = "rust1", since = "1.0.0")]
2720 impl AsRef
<Path
> for OsString
{
2722 fn as_ref(&self) -> &Path
{
2727 #[stable(feature = "rust1", since = "1.0.0")]
2728 impl AsRef
<Path
> for str {
2730 fn as_ref(&self) -> &Path
{
2735 #[stable(feature = "rust1", since = "1.0.0")]
2736 impl AsRef
<Path
> for String
{
2738 fn as_ref(&self) -> &Path
{
2743 #[stable(feature = "rust1", since = "1.0.0")]
2744 impl AsRef
<Path
> for PathBuf
{
2746 fn as_ref(&self) -> &Path
{
2751 #[stable(feature = "path_into_iter", since = "1.6.0")]
2752 impl<'a
> IntoIterator
for &'a PathBuf
{
2753 type Item
= &'a OsStr
;
2754 type IntoIter
= Iter
<'a
>;
2756 fn into_iter(self) -> Iter
<'a
> {
2761 #[stable(feature = "path_into_iter", since = "1.6.0")]
2762 impl<'a
> IntoIterator
for &'a Path
{
2763 type Item
= &'a OsStr
;
2764 type IntoIter
= Iter
<'a
>;
2766 fn into_iter(self) -> Iter
<'a
> {
2771 macro_rules
! impl_cmp
{
2772 ($lhs
:ty
, $rhs
: ty
) => {
2773 #[stable(feature = "partialeq_path", since = "1.6.0")]
2774 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
2776 fn eq(&self, other
: &$rhs
) -> bool
{
2777 <Path
as PartialEq
>::eq(self, other
)
2781 #[stable(feature = "partialeq_path", since = "1.6.0")]
2782 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
2784 fn eq(&self, other
: &$lhs
) -> bool
{
2785 <Path
as PartialEq
>::eq(self, other
)
2789 #[stable(feature = "cmp_path", since = "1.8.0")]
2790 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
2792 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
2793 <Path
as PartialOrd
>::partial_cmp(self, other
)
2797 #[stable(feature = "cmp_path", since = "1.8.0")]
2798 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
2800 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
2801 <Path
as PartialOrd
>::partial_cmp(self, other
)
2807 impl_cmp
!(PathBuf
, Path
);
2808 impl_cmp
!(PathBuf
, &'a Path
);
2809 impl_cmp
!(Cow
<'a
, Path
>, Path
);
2810 impl_cmp
!(Cow
<'a
, Path
>, &'b Path
);
2811 impl_cmp
!(Cow
<'a
, Path
>, PathBuf
);
2813 macro_rules
! impl_cmp_os_str
{
2814 ($lhs
:ty
, $rhs
: ty
) => {
2815 #[stable(feature = "cmp_path", since = "1.8.0")]
2816 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
2818 fn eq(&self, other
: &$rhs
) -> bool
{
2819 <Path
as PartialEq
>::eq(self, other
.as_ref())
2823 #[stable(feature = "cmp_path", since = "1.8.0")]
2824 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
2826 fn eq(&self, other
: &$lhs
) -> bool
{
2827 <Path
as PartialEq
>::eq(self.as_ref(), other
)
2831 #[stable(feature = "cmp_path", since = "1.8.0")]
2832 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
2834 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
2835 <Path
as PartialOrd
>::partial_cmp(self, other
.as_ref())
2839 #[stable(feature = "cmp_path", since = "1.8.0")]
2840 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
2842 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
2843 <Path
as PartialOrd
>::partial_cmp(self.as_ref(), other
)
2849 impl_cmp_os_str
!(PathBuf
, OsStr
);
2850 impl_cmp_os_str
!(PathBuf
, &'a OsStr
);
2851 impl_cmp_os_str
!(PathBuf
, Cow
<'a
, OsStr
>);
2852 impl_cmp_os_str
!(PathBuf
, OsString
);
2853 impl_cmp_os_str
!(Path
, OsStr
);
2854 impl_cmp_os_str
!(Path
, &'a OsStr
);
2855 impl_cmp_os_str
!(Path
, Cow
<'a
, OsStr
>);
2856 impl_cmp_os_str
!(Path
, OsString
);
2857 impl_cmp_os_str
!(&'a Path
, OsStr
);
2858 impl_cmp_os_str
!(&'a Path
, Cow
<'b
, OsStr
>);
2859 impl_cmp_os_str
!(&'a Path
, OsString
);
2860 impl_cmp_os_str
!(Cow
<'a
, Path
>, OsStr
);
2861 impl_cmp_os_str
!(Cow
<'a
, Path
>, &'b OsStr
);
2862 impl_cmp_os_str
!(Cow
<'a
, Path
>, OsString
);
2864 #[stable(since = "1.7.0", feature = "strip_prefix")]
2865 impl fmt
::Display
for StripPrefixError
{
2866 #[allow(deprecated, deprecated_in_future)]
2867 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2868 self.description().fmt(f
)
2872 #[stable(since = "1.7.0", feature = "strip_prefix")]
2873 impl Error
for StripPrefixError
{
2874 #[allow(deprecated)]
2875 fn description(&self) -> &str {