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.
15 //! ## Case sensitivity
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
24 //! Path manipulation includes both parsing components from slices and building
27 //! To parse a path, you can create a [`Path`] slice from a [`str`]
28 //! slice and start asking questions:
31 //! use std::path::Path;
32 //! use std::ffi::OsStr;
34 //! let path = Path::new("/tmp/foo/bar.txt");
36 //! let parent = path.parent();
37 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
39 //! let file_stem = path.file_stem();
40 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
42 //! let extension = path.extension();
43 //! assert_eq!(extension, Some(OsStr::new("txt")));
46 //! To build or modify paths, use [`PathBuf`]:
49 //! use std::path::PathBuf;
51 //! // This way works...
52 //! let mut path = PathBuf::from("c:\\");
54 //! path.push("windows");
55 //! path.push("system32");
57 //! path.set_extension("dll");
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();
64 //! [`components`]: Path::components
65 //! [`push`]: PathBuf::push
67 #![stable(feature = "rust1", since = "1.0.0")]
68 #![deny(unsafe_op_in_unsafe_fn)]
73 use crate::borrow
::{Borrow, Cow}
;
75 use crate::collections
::TryReserveError
;
76 use crate::error
::Error
;
79 use crate::hash
::{Hash, Hasher}
;
81 use crate::iter
::{self, FusedIterator}
;
82 use crate::ops
::{self, Deref}
;
84 use crate::str::FromStr
;
87 use crate::ffi
::{OsStr, OsString}
;
89 use crate::sys
::path
::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR}
;
91 ////////////////////////////////////////////////////////////////////////////////
93 ////////////////////////////////////////////////////////////////////////////////
95 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
96 // taking advantage of the fact that OsStr always encodes ASCII characters
97 // as-is. Eventually, this transmutation should be replaced by direct uses of
98 // OsStr APIs for parsing, but it will take a while for those to become
101 ////////////////////////////////////////////////////////////////////////////////
103 ////////////////////////////////////////////////////////////////////////////////
105 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
107 /// Windows uses a variety of path prefix styles, including references to drive
108 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
109 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
110 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
111 /// no normalization is performed.
116 /// use std::path::{Component, Path, Prefix};
117 /// use std::path::Prefix::*;
118 /// use std::ffi::OsStr;
120 /// fn get_path_prefix(s: &str) -> Prefix {
121 /// let path = Path::new(s);
122 /// match path.components().next().unwrap() {
123 /// Component::Prefix(prefix_component) => prefix_component.kind(),
128 /// # if cfg!(windows) {
129 /// assert_eq!(Verbatim(OsStr::new("pictures")),
130 /// get_path_prefix(r"\\?\pictures\kittens"));
131 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
132 /// get_path_prefix(r"\\?\UNC\server\share"));
133 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
134 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
135 /// get_path_prefix(r"\\.\BrainInterface"));
136 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
137 /// get_path_prefix(r"\\server\share"));
138 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
141 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub enum Prefix
<'a
> {
144 /// Verbatim prefix, e.g., `\\?\cat_pics`.
146 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
148 #[stable(feature = "rust1", since = "1.0.0")]
149 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
151 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
152 /// e.g., `\\?\UNC\server\share`.
154 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
155 /// server's hostname and a share name.
156 #[stable(feature = "rust1", since = "1.0.0")]
158 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
159 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
162 /// Verbatim disk prefix, e.g., `\\?\C:`.
164 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
165 /// drive letter and `:`.
166 #[stable(feature = "rust1", since = "1.0.0")]
167 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
169 /// Device namespace prefix, e.g., `\\.\COM42`.
171 /// Device namespace prefixes consist of `\\.\` (possibly using `/`
172 /// instead of `\`), immediately followed by the device name.
173 #[stable(feature = "rust1", since = "1.0.0")]
174 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
176 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
177 /// `\\server\share`.
179 /// UNC prefixes consist of the server's hostname and a share name.
180 #[stable(feature = "rust1", since = "1.0.0")]
182 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
183 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
186 /// Prefix `C:` for the given disk drive.
187 #[stable(feature = "rust1", since = "1.0.0")]
188 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
191 impl<'a
> Prefix
<'a
> {
193 fn len(&self) -> usize {
195 fn os_str_len(s
: &OsStr
) -> usize {
199 Verbatim(x
) => 4 + os_str_len(x
),
200 VerbatimUNC(x
, y
) => {
201 8 + os_str_len(x
) + if os_str_len(y
) > 0 { 1 + os_str_len(y) }
else { 0 }
203 VerbatimDisk(_
) => 6,
204 UNC(x
, y
) => 2 + os_str_len(x
) + if os_str_len(y
) > 0 { 1 + os_str_len(y) }
else { 0 }
,
205 DeviceNS(x
) => 4 + os_str_len(x
),
210 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
215 /// use std::path::Prefix::*;
216 /// use std::ffi::OsStr;
218 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
219 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
220 /// assert!(VerbatimDisk(b'C').is_verbatim());
221 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
222 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
223 /// assert!(!Disk(b'C').is_verbatim());
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn is_verbatim(&self) -> bool
{
230 matches
!(*self, Verbatim(_
) | VerbatimDisk(_
) | VerbatimUNC(..))
234 fn is_drive(&self) -> bool
{
235 matches
!(*self, Prefix
::Disk(_
))
239 fn has_implicit_root(&self) -> bool
{
244 ////////////////////////////////////////////////////////////////////////////////
245 // Exposed parsing helpers
246 ////////////////////////////////////////////////////////////////////////////////
248 /// Determines whether the character is one of the permitted path
249 /// separators for the current platform.
256 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
257 /// assert!(!path::is_separator('❤'));
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn is_separator(c
: char) -> bool
{
262 c
.is_ascii() && is_sep_byte(c
as u8)
265 /// The primary separator of path components for the current platform.
267 /// For example, `/` on Unix and `\` on Windows.
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub const MAIN_SEPARATOR
: char = crate::sys
::path
::MAIN_SEP
;
271 /// The primary separator of path components for the current platform.
273 /// For example, `/` on Unix and `\` on Windows.
274 #[unstable(feature = "main_separator_str", issue = "94071")]
275 pub const MAIN_SEPARATOR_STR
: &str = crate::sys
::path
::MAIN_SEP_STR
;
277 ////////////////////////////////////////////////////////////////////////////////
279 ////////////////////////////////////////////////////////////////////////////////
281 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
282 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
283 // `iter` after having exhausted `prefix`.
284 fn iter_after
<'a
, 'b
, I
, J
>(mut iter
: I
, mut prefix
: J
) -> Option
<I
>
286 I
: Iterator
<Item
= Component
<'a
>> + Clone
,
287 J
: Iterator
<Item
= Component
<'b
>>,
290 let mut iter_next
= iter
.clone();
291 match (iter_next
.next(), prefix
.next()) {
292 (Some(ref x
), Some(ref y
)) if x
== y
=> (),
293 (Some(_
), Some(_
)) => return None
,
294 (Some(_
), None
) => return Some(iter
),
295 (None
, None
) => return Some(iter
),
296 (None
, Some(_
)) => return None
,
302 unsafe fn u8_slice_as_os_str(s
: &[u8]) -> &OsStr
{
303 // SAFETY: See note at the top of this module to understand why this and
304 // `OsStr::bytes` are used:
306 // This casts are safe as OsStr is internally a wrapper around [u8] on all
309 // Note that currently this relies on the special knowledge that libstd has;
310 // these types are single-element structs but are not marked
311 // repr(transparent) or repr(C) which would make these casts not allowable
313 unsafe { &*(s as *const [u8] as *const OsStr) }
316 // Detect scheme on Redox
317 fn has_redox_scheme(s
: &[u8]) -> bool
{
318 cfg
!(target_os
= "redox") && s
.contains(&b'
:'
)
321 ////////////////////////////////////////////////////////////////////////////////
322 // Cross-platform, iterator-independent parsing
323 ////////////////////////////////////////////////////////////////////////////////
325 /// Says whether the first byte after the prefix is a separator.
326 fn has_physical_root(s
: &[u8], prefix
: Option
<Prefix
<'_
>>) -> bool
{
327 let path
= if let Some(p
) = prefix { &s[p.len()..] }
else { s }
;
328 !path
.is_empty() && is_sep_byte(path
[0])
331 // basic workhorse for splitting stem and extension
332 fn rsplit_file_at_dot(file
: &OsStr
) -> (Option
<&OsStr
>, Option
<&OsStr
>) {
333 if file
.bytes() == b
".." {
334 return (Some(file
), None
);
337 // The unsafety here stems from converting between &OsStr and &[u8]
338 // and back. This is safe to do because (1) we only look at ASCII
339 // contents of the encoding and (2) new &OsStr values are produced
340 // only from ASCII-bounded slices of existing &OsStr values.
341 let mut iter
= file
.bytes().rsplitn(2, |b
| *b
== b'
.'
);
342 let after
= iter
.next();
343 let before
= iter
.next();
344 if before
== Some(b
"") {
347 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
351 fn split_file_at_dot(file
: &OsStr
) -> (&OsStr
, Option
<&OsStr
>) {
352 let slice
= file
.bytes();
357 // The unsafety here stems from converting between &OsStr and &[u8]
358 // and back. This is safe to do because (1) we only look at ASCII
359 // contents of the encoding and (2) new &OsStr values are produced
360 // only from ASCII-bounded slices of existing &OsStr values.
361 let i
= match slice
[1..].iter().position(|b
| *b
== b'
.'
) {
363 None
=> return (file
, None
),
365 let before
= &slice
[..i
];
366 let after
= &slice
[i
+ 1..];
367 unsafe { (u8_slice_as_os_str(before), Some(u8_slice_as_os_str(after))) }
370 ////////////////////////////////////////////////////////////////////////////////
371 // The core iterators
372 ////////////////////////////////////////////////////////////////////////////////
374 /// Component parsing works by a double-ended state machine; the cursors at the
375 /// front and back of the path each keep track of what parts of the path have
376 /// been consumed so far.
378 /// Going front to back, a path is made up of a prefix, a starting
379 /// directory component, and a body (of normal components)
380 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
383 StartDir
= 1, // / or . or nothing
384 Body
= 2, // foo/bar/baz
388 /// A structure wrapping a Windows path prefix as well as its unparsed string
391 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
392 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
393 /// returned by [`as_os_str`].
395 /// Instances of this `struct` can be obtained by matching against the
396 /// [`Prefix` variant] on [`Component`].
398 /// Does not occur on Unix.
403 /// # if cfg!(windows) {
404 /// use std::path::{Component, Path, Prefix};
405 /// use std::ffi::OsStr;
407 /// let path = Path::new(r"c:\you\later\");
408 /// match path.components().next().unwrap() {
409 /// Component::Prefix(prefix_component) => {
410 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
411 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
413 /// _ => unreachable!(),
418 /// [`as_os_str`]: PrefixComponent::as_os_str
419 /// [`kind`]: PrefixComponent::kind
420 /// [`Prefix` variant]: Component::Prefix
421 #[stable(feature = "rust1", since = "1.0.0")]
422 #[derive(Copy, Clone, Eq, Debug)]
423 pub struct PrefixComponent
<'a
> {
424 /// The prefix as an unparsed `OsStr` slice.
427 /// The parsed prefix data.
431 impl<'a
> PrefixComponent
<'a
> {
432 /// Returns the parsed prefix data.
434 /// See [`Prefix`]'s documentation for more information on the different
435 /// kinds of prefixes.
436 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn kind(&self) -> Prefix
<'a
> {
443 /// Returns the raw [`OsStr`] slice for this prefix.
444 #[stable(feature = "rust1", since = "1.0.0")]
447 pub fn as_os_str(&self) -> &'a OsStr
{
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<'a
> cmp
::PartialEq
for PrefixComponent
<'a
> {
455 fn eq(&self, other
: &PrefixComponent
<'a
>) -> bool
{
456 cmp
::PartialEq
::eq(&self.parsed
, &other
.parsed
)
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl<'a
> cmp
::PartialOrd
for PrefixComponent
<'a
> {
463 fn partial_cmp(&self, other
: &PrefixComponent
<'a
>) -> Option
<cmp
::Ordering
> {
464 cmp
::PartialOrd
::partial_cmp(&self.parsed
, &other
.parsed
)
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl cmp
::Ord
for PrefixComponent
<'_
> {
471 fn cmp(&self, other
: &Self) -> cmp
::Ordering
{
472 cmp
::Ord
::cmp(&self.parsed
, &other
.parsed
)
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl Hash
for PrefixComponent
<'_
> {
478 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
483 /// A single component of a path.
485 /// A `Component` roughly corresponds to a substring between path separators
488 /// This `enum` is created by iterating over [`Components`], which in turn is
489 /// created by the [`components`](Path::components) method on [`Path`].
494 /// use std::path::{Component, Path};
496 /// let path = Path::new("/tmp/foo/bar.txt");
497 /// let components = path.components().collect::<Vec<_>>();
498 /// assert_eq!(&components, &[
499 /// Component::RootDir,
500 /// Component::Normal("tmp".as_ref()),
501 /// Component::Normal("foo".as_ref()),
502 /// Component::Normal("bar.txt".as_ref()),
505 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub enum Component
<'a
> {
508 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
510 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
513 /// Does not occur on Unix.
514 #[stable(feature = "rust1", since = "1.0.0")]
515 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
517 /// The root directory component, appears after any prefix and before anything else.
519 /// It represents a separator that designates that a path starts from root.
520 #[stable(feature = "rust1", since = "1.0.0")]
523 /// A reference to the current directory, i.e., `.`.
524 #[stable(feature = "rust1", since = "1.0.0")]
527 /// A reference to the parent directory, i.e., `..`.
528 #[stable(feature = "rust1", since = "1.0.0")]
531 /// A normal component, e.g., `a` and `b` in `a/b`.
533 /// This variant is the most common one, it represents references to files
535 #[stable(feature = "rust1", since = "1.0.0")]
536 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
539 impl<'a
> Component
<'a
> {
540 /// Extracts the underlying [`OsStr`] slice.
545 /// use std::path::Path;
547 /// let path = Path::new("./tmp/foo/bar.txt");
548 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
549 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
551 #[must_use = "`self` will be dropped if the result is not used"]
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn as_os_str(self) -> &'a OsStr
{
555 Component
::Prefix(p
) => p
.as_os_str(),
556 Component
::RootDir
=> OsStr
::new(MAIN_SEP_STR
),
557 Component
::CurDir
=> OsStr
::new("."),
558 Component
::ParentDir
=> OsStr
::new(".."),
559 Component
::Normal(path
) => path
,
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl AsRef
<OsStr
> for Component
<'_
> {
567 fn as_ref(&self) -> &OsStr
{
572 #[stable(feature = "path_component_asref", since = "1.25.0")]
573 impl AsRef
<Path
> for Component
<'_
> {
575 fn as_ref(&self) -> &Path
{
576 self.as_os_str().as_ref()
580 /// An iterator over the [`Component`]s of a [`Path`].
582 /// This `struct` is created by the [`components`] method on [`Path`].
583 /// See its documentation for more.
588 /// use std::path::Path;
590 /// let path = Path::new("/tmp/foo/bar.txt");
592 /// for component in path.components() {
593 /// println!("{component:?}");
597 /// [`components`]: Path::components
599 #[must_use = "iterators are lazy and do nothing unless consumed"]
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub struct Components
<'a
> {
602 // The path left to parse components from
605 // The prefix as it was originally parsed, if any
606 prefix
: Option
<Prefix
<'a
>>,
608 // true if path *physically* has a root separator; for most Windows
609 // prefixes, it may have a "logical" root separator for the purposes of
610 // normalization, e.g., \\server\share == \\server\share\.
611 has_physical_root
: bool
,
613 // The iterator is double-ended, and these two states keep track of what has
614 // been produced from either end
619 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
621 /// This `struct` is created by the [`iter`] method on [`Path`].
622 /// See its documentation for more.
624 /// [`iter`]: Path::iter
626 #[must_use = "iterators are lazy and do nothing unless consumed"]
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub struct Iter
<'a
> {
629 inner
: Components
<'a
>,
632 #[stable(feature = "path_components_debug", since = "1.13.0")]
633 impl fmt
::Debug
for Components
<'_
> {
634 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
635 struct DebugHelper
<'a
>(&'a Path
);
637 impl fmt
::Debug
for DebugHelper
<'_
> {
638 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
639 f
.debug_list().entries(self.0.components()).finish()
643 f
.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
647 impl<'a
> Components
<'a
> {
648 // how long is the prefix, if any?
650 fn prefix_len(&self) -> usize {
651 self.prefix
.as_ref().map(Prefix
::len
).unwrap_or(0)
655 fn prefix_verbatim(&self) -> bool
{
656 self.prefix
.as_ref().map(Prefix
::is_verbatim
).unwrap_or(false)
659 /// how much of the prefix is left from the point of view of iteration?
661 fn prefix_remaining(&self) -> usize {
662 if self.front
== State
::Prefix { self.prefix_len() }
else { 0 }
665 // Given the iteration so far, how much of the pre-State::Body path is left?
667 fn len_before_body(&self) -> usize {
668 let root
= if self.front
<= State
::StartDir
&& self.has_physical_root { 1 }
else { 0 }
;
669 let cur_dir
= if self.front
<= State
::StartDir
&& self.include_cur_dir() { 1 }
else { 0 }
;
670 self.prefix_remaining() + root
+ cur_dir
673 // is the iteration complete?
675 fn finished(&self) -> bool
{
676 self.front
== State
::Done
|| self.back
== State
::Done
|| self.front
> self.back
680 fn is_sep_byte(&self, b
: u8) -> bool
{
681 if self.prefix_verbatim() { is_verbatim_sep(b) }
else { is_sep_byte(b) }
684 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
689 /// use std::path::Path;
691 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
692 /// components.next();
693 /// components.next();
695 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
698 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn as_path(&self) -> &'a Path
{
700 let mut comps
= self.clone();
701 if comps
.front
== State
::Body
{
704 if comps
.back
== State
::Body
{
707 unsafe { Path::from_u8_slice(comps.path) }
710 /// Is the *original* path rooted?
711 fn has_root(&self) -> bool
{
712 if self.has_physical_root
{
715 if let Some(p
) = self.prefix
{
716 if p
.has_implicit_root() {
723 /// Should the normalized path include a leading . ?
724 fn include_cur_dir(&self) -> bool
{
728 let mut iter
= self.path
[self.prefix_remaining()..].iter();
729 match (iter
.next(), iter
.next()) {
730 (Some(&b'
.'
), None
) => true,
731 (Some(&b'
.'
), Some(&b
)) => self.is_sep_byte(b
),
736 // parse a given byte sequence into the corresponding path component
737 fn parse_single_component
<'b
>(&self, comp
: &'b
[u8]) -> Option
<Component
<'b
>> {
739 b
"." if self.prefix_verbatim() => Some(Component
::CurDir
),
740 b
"." => None
, // . components are normalized away, except at
741 // the beginning of a path, which is treated
742 // separately via `include_cur_dir`
743 b
".." => Some(Component
::ParentDir
),
745 _
=> Some(Component
::Normal(unsafe { u8_slice_as_os_str(comp) }
)),
749 // parse a component from the left, saying how many bytes to consume to
750 // remove the component
751 fn parse_next_component(&self) -> (usize, Option
<Component
<'a
>>) {
752 debug_assert
!(self.front
== State
::Body
);
753 let (extra
, comp
) = match self.path
.iter().position(|b
| self.is_sep_byte(*b
)) {
754 None
=> (0, self.path
),
755 Some(i
) => (1, &self.path
[..i
]),
757 (comp
.len() + extra
, self.parse_single_component(comp
))
760 // parse a component from the right, saying how many bytes to consume to
761 // remove the component
762 fn parse_next_component_back(&self) -> (usize, Option
<Component
<'a
>>) {
763 debug_assert
!(self.back
== State
::Body
);
764 let start
= self.len_before_body();
765 let (extra
, comp
) = match self.path
[start
..].iter().rposition(|b
| self.is_sep_byte(*b
)) {
766 None
=> (0, &self.path
[start
..]),
767 Some(i
) => (1, &self.path
[start
+ i
+ 1..]),
769 (comp
.len() + extra
, self.parse_single_component(comp
))
772 // trim away repeated separators (i.e., empty components) on the left
773 fn trim_left(&mut self) {
774 while !self.path
.is_empty() {
775 let (size
, comp
) = self.parse_next_component();
779 self.path
= &self.path
[size
..];
784 // trim away repeated separators (i.e., empty components) on the right
785 fn trim_right(&mut self) {
786 while self.path
.len() > self.len_before_body() {
787 let (size
, comp
) = self.parse_next_component_back();
791 self.path
= &self.path
[..self.path
.len() - size
];
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl AsRef
<Path
> for Components
<'_
> {
800 fn as_ref(&self) -> &Path
{
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl AsRef
<OsStr
> for Components
<'_
> {
808 fn as_ref(&self) -> &OsStr
{
809 self.as_path().as_os_str()
813 #[stable(feature = "path_iter_debug", since = "1.13.0")]
814 impl fmt
::Debug
for Iter
<'_
> {
815 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
816 struct DebugHelper
<'a
>(&'a Path
);
818 impl fmt
::Debug
for DebugHelper
<'_
> {
819 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
820 f
.debug_list().entries(self.0.iter
()).finish()
824 f
.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
829 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
834 /// use std::path::Path;
836 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
840 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
842 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn as_path(&self) -> &'a Path
{
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl AsRef
<Path
> for Iter
<'_
> {
853 fn as_ref(&self) -> &Path
{
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl AsRef
<OsStr
> for Iter
<'_
> {
861 fn as_ref(&self) -> &OsStr
{
862 self.as_path().as_os_str()
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a
> Iterator
for Iter
<'a
> {
868 type Item
= &'a OsStr
;
871 fn next(&mut self) -> Option
<&'a OsStr
> {
872 self.inner
.next().map(Component
::as_os_str
)
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<'a
> DoubleEndedIterator
for Iter
<'a
> {
879 fn next_back(&mut self) -> Option
<&'a OsStr
> {
880 self.inner
.next_back().map(Component
::as_os_str
)
884 #[stable(feature = "fused", since = "1.26.0")]
885 impl FusedIterator
for Iter
<'_
> {}
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl<'a
> Iterator
for Components
<'a
> {
889 type Item
= Component
<'a
>;
891 fn next(&mut self) -> Option
<Component
<'a
>> {
892 while !self.finished() {
894 State
::Prefix
if self.prefix_len() > 0 => {
895 self.front
= State
::StartDir
;
896 debug_assert
!(self.prefix_len() <= self.path
.len());
897 let raw
= &self.path
[..self.prefix_len()];
898 self.path
= &self.path
[self.prefix_len()..];
899 return Some(Component
::Prefix(PrefixComponent
{
900 raw
: unsafe { u8_slice_as_os_str(raw) }
,
901 parsed
: self.prefix
.unwrap(),
905 self.front
= State
::StartDir
;
908 self.front
= State
::Body
;
909 if self.has_physical_root
{
910 debug_assert
!(!self.path
.is_empty());
911 self.path
= &self.path
[1..];
912 return Some(Component
::RootDir
);
913 } else if let Some(p
) = self.prefix
{
914 if p
.has_implicit_root() && !p
.is_verbatim() {
915 return Some(Component
::RootDir
);
917 } else if self.include_cur_dir() {
918 debug_assert
!(!self.path
.is_empty());
919 self.path
= &self.path
[1..];
920 return Some(Component
::CurDir
);
923 State
::Body
if !self.path
.is_empty() => {
924 let (size
, comp
) = self.parse_next_component();
925 self.path
= &self.path
[size
..];
931 self.front
= State
::Done
;
933 State
::Done
=> unreachable
!(),
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl<'a
> DoubleEndedIterator
for Components
<'a
> {
942 fn next_back(&mut self) -> Option
<Component
<'a
>> {
943 while !self.finished() {
945 State
::Body
if self.path
.len() > self.len_before_body() => {
946 let (size
, comp
) = self.parse_next_component_back();
947 self.path
= &self.path
[..self.path
.len() - size
];
953 self.back
= State
::StartDir
;
956 self.back
= State
::Prefix
;
957 if self.has_physical_root
{
958 self.path
= &self.path
[..self.path
.len() - 1];
959 return Some(Component
::RootDir
);
960 } else if let Some(p
) = self.prefix
{
961 if p
.has_implicit_root() && !p
.is_verbatim() {
962 return Some(Component
::RootDir
);
964 } else if self.include_cur_dir() {
965 self.path
= &self.path
[..self.path
.len() - 1];
966 return Some(Component
::CurDir
);
969 State
::Prefix
if self.prefix_len() > 0 => {
970 self.back
= State
::Done
;
971 return Some(Component
::Prefix(PrefixComponent
{
972 raw
: unsafe { u8_slice_as_os_str(self.path) }
,
973 parsed
: self.prefix
.unwrap(),
977 self.back
= State
::Done
;
980 State
::Done
=> unreachable
!(),
987 #[stable(feature = "fused", since = "1.26.0")]
988 impl FusedIterator
for Components
<'_
> {}
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<'a
> cmp
::PartialEq
for Components
<'a
> {
993 fn eq(&self, other
: &Components
<'a
>) -> bool
{
994 let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ }
= self;
996 // Fast path for exact matches, e.g. for hashmap lookups.
997 // Don't explicitly compare the prefix or has_physical_root fields since they'll
998 // either be covered by the `path` buffer or are only relevant for `prefix_verbatim()`.
999 if self.path
.len() == other
.path
.len()
1000 && self.front
== other
.front
1001 && self.back
== State
::Body
1002 && other
.back
== State
::Body
1003 && self.prefix_verbatim() == other
.prefix_verbatim()
1005 // possible future improvement: this could bail out earlier if there were a
1006 // reverse memcmp/bcmp comparing back to front
1007 if self.path
== other
.path
{
1012 // compare back to front since absolute paths often share long prefixes
1013 Iterator
::eq(self.clone().rev(), other
.clone().rev())
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl cmp
::Eq
for Components
<'_
> {}
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a
> cmp
::PartialOrd
for Components
<'a
> {
1023 fn partial_cmp(&self, other
: &Components
<'a
>) -> Option
<cmp
::Ordering
> {
1024 Some(compare_components(self.clone(), other
.clone()))
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 impl cmp
::Ord
for Components
<'_
> {
1031 fn cmp(&self, other
: &Self) -> cmp
::Ordering
{
1032 compare_components(self.clone(), other
.clone())
1036 fn compare_components(mut left
: Components
<'_
>, mut right
: Components
<'_
>) -> cmp
::Ordering
{
1037 // Fast path for long shared prefixes
1039 // - compare raw bytes to find first mismatch
1040 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1041 // - if found update state to only do a component-wise comparison on the remainder,
1042 // otherwise do it on the full path
1044 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1045 // the middle of one
1046 if left
.prefix
.is_none() && right
.prefix
.is_none() && left
.front
== right
.front
{
1047 // possible future improvement: a [u8]::first_mismatch simd implementation
1048 let first_difference
= match left
.path
.iter().zip(right
.path
).position(|(&a
, &b
)| a
!= b
) {
1049 None
if left
.path
.len() == right
.path
.len() => return cmp
::Ordering
::Equal
,
1050 None
=> left
.path
.len().min(right
.path
.len()),
1054 if let Some(previous_sep
) =
1055 left
.path
[..first_difference
].iter().rposition(|&b
| left
.is_sep_byte(b
))
1057 let mismatched_component_start
= previous_sep
+ 1;
1058 left
.path
= &left
.path
[mismatched_component_start
..];
1059 left
.front
= State
::Body
;
1060 right
.path
= &right
.path
[mismatched_component_start
..];
1061 right
.front
= State
::Body
;
1065 Iterator
::cmp(left
, right
)
1068 /// An iterator over [`Path`] and its ancestors.
1070 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1071 /// See its documentation for more.
1076 /// use std::path::Path;
1078 /// let path = Path::new("/foo/bar");
1080 /// for ancestor in path.ancestors() {
1081 /// println!("{}", ancestor.display());
1085 /// [`ancestors`]: Path::ancestors
1086 #[derive(Copy, Clone, Debug)]
1087 #[must_use = "iterators are lazy and do nothing unless consumed"]
1088 #[stable(feature = "path_ancestors", since = "1.28.0")]
1089 pub struct Ancestors
<'a
> {
1090 next
: Option
<&'a Path
>,
1093 #[stable(feature = "path_ancestors", since = "1.28.0")]
1094 impl<'a
> Iterator
for Ancestors
<'a
> {
1095 type Item
= &'a Path
;
1098 fn next(&mut self) -> Option
<Self::Item
> {
1099 let next
= self.next
;
1100 self.next
= next
.and_then(Path
::parent
);
1105 #[stable(feature = "path_ancestors", since = "1.28.0")]
1106 impl FusedIterator
for Ancestors
<'_
> {}
1108 ////////////////////////////////////////////////////////////////////////////////
1109 // Basic types and traits
1110 ////////////////////////////////////////////////////////////////////////////////
1112 /// An owned, mutable path (akin to [`String`]).
1114 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1115 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1116 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1118 /// [`push`]: PathBuf::push
1119 /// [`set_extension`]: PathBuf::set_extension
1121 /// More details about the overall approach can be found in
1122 /// the [module documentation](self).
1126 /// You can use [`push`] to build up a `PathBuf` from
1130 /// use std::path::PathBuf;
1132 /// let mut path = PathBuf::new();
1134 /// path.push(r"C:\");
1135 /// path.push("windows");
1136 /// path.push("system32");
1138 /// path.set_extension("dll");
1141 /// However, [`push`] is best used for dynamic situations. This is a better way
1142 /// to do this when you know all of the components ahead of time:
1145 /// use std::path::PathBuf;
1147 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1150 /// We can still do better than this! Since these are all strings, we can use
1154 /// use std::path::PathBuf;
1156 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1159 /// Which method works best depends on what kind of situation you're in.
1160 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1161 #[stable(feature = "rust1", since = "1.0.0")]
1163 // `PathBuf::as_mut_vec` current implementation relies
1164 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1165 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1166 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1167 // not documented and must not be relied upon.
1168 pub struct PathBuf
{
1174 fn as_mut_vec(&mut self) -> &mut Vec
<u8> {
1175 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1178 /// Allocates an empty `PathBuf`.
1183 /// use std::path::PathBuf;
1185 /// let path = PathBuf::new();
1187 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn new() -> PathBuf
{
1191 PathBuf { inner: OsString::new() }
1194 /// Creates a new `PathBuf` with a given capacity used to create the
1195 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1200 /// use std::path::PathBuf;
1202 /// let mut path = PathBuf::with_capacity(10);
1203 /// let capacity = path.capacity();
1205 /// // This push is done without reallocating
1206 /// path.push(r"C:\");
1208 /// assert_eq!(capacity, path.capacity());
1211 /// [`with_capacity`]: OsString::with_capacity
1212 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1215 pub fn with_capacity(capacity
: usize) -> PathBuf
{
1216 PathBuf { inner: OsString::with_capacity(capacity) }
1219 /// Coerces to a [`Path`] slice.
1224 /// use std::path::{Path, PathBuf};
1226 /// let p = PathBuf::from("/test");
1227 /// assert_eq!(Path::new("/test"), p.as_path());
1229 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub fn as_path(&self) -> &Path
{
1236 /// Extends `self` with `path`.
1238 /// If `path` is absolute, it replaces the current path.
1242 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1243 /// replaces everything except for the prefix (if any) of `self`.
1244 /// * if `path` has a prefix but no root, it replaces `self`.
1245 /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
1246 /// and `path` is not empty, the new path is normalized: all references
1247 /// to `.` and `..` are removed.
1251 /// Pushing a relative path extends the existing path:
1254 /// use std::path::PathBuf;
1256 /// let mut path = PathBuf::from("/tmp");
1257 /// path.push("file.bk");
1258 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1261 /// Pushing an absolute path replaces the existing path:
1264 /// use std::path::PathBuf;
1266 /// let mut path = PathBuf::from("/tmp");
1267 /// path.push("/etc");
1268 /// assert_eq!(path, PathBuf::from("/etc"));
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 pub fn push
<P
: AsRef
<Path
>>(&mut self, path
: P
) {
1272 self._push(path
.as_ref())
1275 fn _push(&mut self, path
: &Path
) {
1276 // in general, a separator is needed if the rightmost byte is not a separator
1277 let mut need_sep
= self.as_mut_vec().last().map(|c
| !is_sep_byte(*c
)).unwrap_or(false);
1279 // in the special case of `C:` on Windows, do *not* add a separator
1280 let comps
= self.components();
1282 if comps
.prefix_len() > 0
1283 && comps
.prefix_len() == comps
.path
.len()
1284 && comps
.prefix
.unwrap().is_drive()
1289 // absolute `path` replaces `self`
1290 if path
.is_absolute() || path
.prefix().is_some() {
1291 self.as_mut_vec().truncate(0);
1293 // verbatim paths need . and .. removed
1294 } else if comps
.prefix_verbatim() && !path
.inner
.is_empty() {
1295 let mut buf
: Vec
<_
> = comps
.collect();
1296 for c
in path
.components() {
1298 Component
::RootDir
=> {
1302 Component
::CurDir
=> (),
1303 Component
::ParentDir
=> {
1304 if let Some(Component
::Normal(_
)) = buf
.last() {
1312 let mut res
= OsString
::new();
1313 let mut need_sep
= false;
1316 if need_sep
&& c
!= Component
::RootDir
{
1317 res
.push(MAIN_SEP_STR
);
1319 res
.push(c
.as_os_str());
1321 need_sep
= match c
{
1322 Component
::RootDir
=> false,
1323 Component
::Prefix(prefix
) => {
1324 !prefix
.parsed
.is_drive() && prefix
.parsed
.len() > 0
1333 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1334 } else if path
.has_root() {
1335 let prefix_len
= self.components().prefix_remaining();
1336 self.as_mut_vec().truncate(prefix_len
);
1338 // `path` is a pure relative path
1339 } else if need_sep
{
1340 self.inner
.push(MAIN_SEP_STR
);
1343 self.inner
.push(path
);
1346 /// Truncates `self` to [`self.parent`].
1348 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1349 /// Otherwise, returns `true`.
1351 /// [`self.parent`]: Path::parent
1356 /// use std::path::{Path, PathBuf};
1358 /// let mut p = PathBuf::from("/spirited/away.rs");
1361 /// assert_eq!(Path::new("/spirited"), p);
1363 /// assert_eq!(Path::new("/"), p);
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub fn pop(&mut self) -> bool
{
1367 match self.parent().map(|p
| p
.as_u8_slice().len()) {
1369 self.as_mut_vec().truncate(len
);
1376 /// Updates [`self.file_name`] to `file_name`.
1378 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1381 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1382 /// `file_name`. The new path will be a sibling of the original path.
1383 /// (That is, it will have the same parent.)
1385 /// [`self.file_name`]: Path::file_name
1386 /// [`pop`]: PathBuf::pop
1391 /// use std::path::PathBuf;
1393 /// let mut buf = PathBuf::from("/");
1394 /// assert!(buf.file_name() == None);
1395 /// buf.set_file_name("bar");
1396 /// assert!(buf == PathBuf::from("/bar"));
1397 /// assert!(buf.file_name().is_some());
1398 /// buf.set_file_name("baz.txt");
1399 /// assert!(buf == PathBuf::from("/baz.txt"));
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn set_file_name
<S
: AsRef
<OsStr
>>(&mut self, file_name
: S
) {
1403 self._set_file_name(file_name
.as_ref())
1406 fn _set_file_name(&mut self, file_name
: &OsStr
) {
1407 if self.file_name().is_some() {
1408 let popped
= self.pop();
1409 debug_assert
!(popped
);
1411 self.push(file_name
);
1414 /// Updates [`self.extension`] to `extension`.
1416 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1417 /// returns `true` and updates the extension otherwise.
1419 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1422 /// [`self.file_name`]: Path::file_name
1423 /// [`self.extension`]: Path::extension
1428 /// use std::path::{Path, PathBuf};
1430 /// let mut p = PathBuf::from("/feel/the");
1432 /// p.set_extension("force");
1433 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1435 /// p.set_extension("dark_side");
1436 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 pub fn set_extension
<S
: AsRef
<OsStr
>>(&mut self, extension
: S
) -> bool
{
1440 self._set_extension(extension
.as_ref())
1443 fn _set_extension(&mut self, extension
: &OsStr
) -> bool
{
1444 let file_stem
= match self.file_stem() {
1445 None
=> return false,
1446 Some(f
) => f
.bytes(),
1449 // truncate until right after the file stem
1450 let end_file_stem
= file_stem
[file_stem
.len()..].as_ptr().addr();
1451 let start
= self.inner
.bytes().as_ptr().addr();
1452 let v
= self.as_mut_vec();
1453 v
.truncate(end_file_stem
.wrapping_sub(start
));
1455 // add the new extension, if any
1456 let new
= extension
.bytes();
1457 if !new
.is_empty() {
1458 v
.reserve_exact(new
.len() + 1);
1460 v
.extend_from_slice(new
);
1466 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1471 /// use std::path::PathBuf;
1473 /// let p = PathBuf::from("/the/head");
1474 /// let os_str = p.into_os_string();
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 #[must_use = "`self` will be dropped if the result is not used"]
1479 pub fn into_os_string(self) -> OsString
{
1483 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1484 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1485 #[must_use = "`self` will be dropped if the result is not used"]
1487 pub fn into_boxed_path(self) -> Box
<Path
> {
1488 let rw
= Box
::into_raw(self.inner
.into_boxed_os_str()) as *mut Path
;
1489 unsafe { Box::from_raw(rw) }
1492 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1494 /// [`capacity`]: OsString::capacity
1495 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1498 pub fn capacity(&self) -> usize {
1499 self.inner
.capacity()
1502 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1504 /// [`clear`]: OsString::clear
1505 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1507 pub fn clear(&mut self) {
1511 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1513 /// [`reserve`]: OsString::reserve
1514 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1516 pub fn reserve(&mut self, additional
: usize) {
1517 self.inner
.reserve(additional
)
1520 /// Invokes [`try_reserve`] on the underlying instance of [`OsString`].
1522 /// [`try_reserve`]: OsString::try_reserve
1523 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1525 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
1526 self.inner
.try_reserve(additional
)
1529 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1531 /// [`reserve_exact`]: OsString::reserve_exact
1532 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1534 pub fn reserve_exact(&mut self, additional
: usize) {
1535 self.inner
.reserve_exact(additional
)
1538 /// Invokes [`try_reserve_exact`] on the underlying instance of [`OsString`].
1540 /// [`try_reserve_exact`]: OsString::try_reserve_exact
1541 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1543 pub fn try_reserve_exact(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
1544 self.inner
.try_reserve_exact(additional
)
1547 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1549 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1550 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1552 pub fn shrink_to_fit(&mut self) {
1553 self.inner
.shrink_to_fit()
1556 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1558 /// [`shrink_to`]: OsString::shrink_to
1559 #[stable(feature = "shrink_to", since = "1.56.0")]
1561 pub fn shrink_to(&mut self, min_capacity
: usize) {
1562 self.inner
.shrink_to(min_capacity
)
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl Clone
for PathBuf
{
1569 fn clone(&self) -> Self {
1570 PathBuf { inner: self.inner.clone() }
1574 fn clone_from(&mut self, source
: &Self) {
1575 self.inner
.clone_from(&source
.inner
)
1579 #[stable(feature = "box_from_path", since = "1.17.0")]
1580 impl From
<&Path
> for Box
<Path
> {
1581 /// Creates a boxed [`Path`] from a reference.
1583 /// This will allocate and clone `path` to it.
1584 fn from(path
: &Path
) -> Box
<Path
> {
1585 let boxed
: Box
<OsStr
> = path
.inner
.into();
1586 let rw
= Box
::into_raw(boxed
) as *mut Path
;
1587 unsafe { Box::from_raw(rw) }
1591 #[stable(feature = "box_from_cow", since = "1.45.0")]
1592 impl From
<Cow
<'_
, Path
>> for Box
<Path
> {
1593 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1595 /// Converting from a `Cow::Owned` does not clone or allocate.
1597 fn from(cow
: Cow
<'_
, Path
>) -> Box
<Path
> {
1599 Cow
::Borrowed(path
) => Box
::from(path
),
1600 Cow
::Owned(path
) => Box
::from(path
),
1605 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1606 impl From
<Box
<Path
>> for PathBuf
{
1607 /// Converts a <code>[Box]<[Path]></code> into a [`PathBuf`].
1609 /// This conversion does not allocate or copy memory.
1611 fn from(boxed
: Box
<Path
>) -> PathBuf
{
1612 boxed
.into_path_buf()
1616 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1617 impl From
<PathBuf
> for Box
<Path
> {
1618 /// Converts a [`PathBuf`] into a <code>[Box]<[Path]></code>.
1620 /// This conversion currently should not allocate memory,
1621 /// but this behavior is not guaranteed on all platforms or in all future versions.
1623 fn from(p
: PathBuf
) -> Box
<Path
> {
1628 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1629 impl Clone
for Box
<Path
> {
1631 fn clone(&self) -> Self {
1632 self.to_path_buf().into_boxed_path()
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl<T
: ?Sized
+ AsRef
<OsStr
>> From
<&T
> for PathBuf
{
1638 /// Converts a borrowed [`OsStr`] to a [`PathBuf`].
1640 /// Allocates a [`PathBuf`] and copies the data into it.
1642 fn from(s
: &T
) -> PathBuf
{
1643 PathBuf
::from(s
.as_ref().to_os_string())
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl From
<OsString
> for PathBuf
{
1649 /// Converts an [`OsString`] into a [`PathBuf`]
1651 /// This conversion does not allocate or copy memory.
1653 fn from(s
: OsString
) -> PathBuf
{
1654 PathBuf { inner: s }
1658 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1659 impl From
<PathBuf
> for OsString
{
1660 /// Converts a [`PathBuf`] into an [`OsString`]
1662 /// This conversion does not allocate or copy memory.
1664 fn from(path_buf
: PathBuf
) -> OsString
{
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl From
<String
> for PathBuf
{
1671 /// Converts a [`String`] into a [`PathBuf`]
1673 /// This conversion does not allocate or copy memory.
1675 fn from(s
: String
) -> PathBuf
{
1676 PathBuf
::from(OsString
::from(s
))
1680 #[stable(feature = "path_from_str", since = "1.32.0")]
1681 impl FromStr
for PathBuf
{
1682 type Err
= core
::convert
::Infallible
;
1685 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
1686 Ok(PathBuf
::from(s
))
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl<P
: AsRef
<Path
>> iter
::FromIterator
<P
> for PathBuf
{
1692 fn from_iter
<I
: IntoIterator
<Item
= P
>>(iter
: I
) -> PathBuf
{
1693 let mut buf
= PathBuf
::new();
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<P
: AsRef
<Path
>> iter
::Extend
<P
> for PathBuf
{
1701 fn extend
<I
: IntoIterator
<Item
= P
>>(&mut self, iter
: I
) {
1702 iter
.into_iter().for_each(move |p
| self.push(p
.as_ref()));
1706 fn extend_one(&mut self, p
: P
) {
1707 self.push(p
.as_ref());
1711 #[stable(feature = "rust1", since = "1.0.0")]
1712 impl fmt
::Debug
for PathBuf
{
1713 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1714 fmt
::Debug
::fmt(&**self, formatter
)
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl ops
::Deref
for PathBuf
{
1722 fn deref(&self) -> &Path
{
1723 Path
::new(&self.inner
)
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl Borrow
<Path
> for PathBuf
{
1730 fn borrow(&self) -> &Path
{
1735 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1736 impl Default
for PathBuf
{
1738 fn default() -> Self {
1743 #[stable(feature = "cow_from_path", since = "1.6.0")]
1744 impl<'a
> From
<&'a Path
> for Cow
<'a
, Path
> {
1745 /// Creates a clone-on-write pointer from a reference to
1748 /// This conversion does not clone or allocate.
1750 fn from(s
: &'a Path
) -> Cow
<'a
, Path
> {
1755 #[stable(feature = "cow_from_path", since = "1.6.0")]
1756 impl<'a
> From
<PathBuf
> for Cow
<'a
, Path
> {
1757 /// Creates a clone-on-write pointer from an owned
1758 /// instance of [`PathBuf`].
1760 /// This conversion does not clone or allocate.
1762 fn from(s
: PathBuf
) -> Cow
<'a
, Path
> {
1767 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1768 impl<'a
> From
<&'a PathBuf
> for Cow
<'a
, Path
> {
1769 /// Creates a clone-on-write pointer from a reference to
1772 /// This conversion does not clone or allocate.
1774 fn from(p
: &'a PathBuf
) -> Cow
<'a
, Path
> {
1775 Cow
::Borrowed(p
.as_path())
1779 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1780 impl<'a
> From
<Cow
<'a
, Path
>> for PathBuf
{
1781 /// Converts a clone-on-write pointer to an owned path.
1783 /// Converting from a `Cow::Owned` does not clone or allocate.
1785 fn from(p
: Cow
<'a
, Path
>) -> Self {
1790 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1791 impl From
<PathBuf
> for Arc
<Path
> {
1792 /// Converts a [`PathBuf`] into an <code>[Arc]<[Path]></code> by moving the [`PathBuf`] data
1793 /// into a new [`Arc`] buffer.
1795 fn from(s
: PathBuf
) -> Arc
<Path
> {
1796 let arc
: Arc
<OsStr
> = Arc
::from(s
.into_os_string());
1797 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1801 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1802 impl From
<&Path
> for Arc
<Path
> {
1803 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1805 fn from(s
: &Path
) -> Arc
<Path
> {
1806 let arc
: Arc
<OsStr
> = Arc
::from(s
.as_os_str());
1807 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1811 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1812 impl From
<PathBuf
> for Rc
<Path
> {
1813 /// Converts a [`PathBuf`] into an <code>[Rc]<[Path]></code> by moving the [`PathBuf`] data into
1814 /// a new [`Rc`] buffer.
1816 fn from(s
: PathBuf
) -> Rc
<Path
> {
1817 let rc
: Rc
<OsStr
> = Rc
::from(s
.into_os_string());
1818 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1822 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1823 impl From
<&Path
> for Rc
<Path
> {
1824 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new [`Rc`] buffer.
1826 fn from(s
: &Path
) -> Rc
<Path
> {
1827 let rc
: Rc
<OsStr
> = Rc
::from(s
.as_os_str());
1828 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl ToOwned
for Path
{
1834 type Owned
= PathBuf
;
1836 fn to_owned(&self) -> PathBuf
{
1840 fn clone_into(&self, target
: &mut PathBuf
) {
1841 self.inner
.clone_into(&mut target
.inner
);
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl cmp
::PartialEq
for PathBuf
{
1848 fn eq(&self, other
: &PathBuf
) -> bool
{
1849 self.components() == other
.components()
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 impl Hash
for PathBuf
{
1855 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
1856 self.as_path().hash(h
)
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 impl cmp
::Eq
for PathBuf {}
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl cmp
::PartialOrd
for PathBuf
{
1866 fn partial_cmp(&self, other
: &PathBuf
) -> Option
<cmp
::Ordering
> {
1867 Some(compare_components(self.components(), other
.components()))
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl cmp
::Ord
for PathBuf
{
1874 fn cmp(&self, other
: &PathBuf
) -> cmp
::Ordering
{
1875 compare_components(self.components(), other
.components())
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 impl AsRef
<OsStr
> for PathBuf
{
1882 fn as_ref(&self) -> &OsStr
{
1887 /// A slice of a path (akin to [`str`]).
1889 /// This type supports a number of operations for inspecting a path, including
1890 /// breaking the path into its components (separated by `/` on Unix and by either
1891 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1892 /// is absolute, and so on.
1894 /// This is an *unsized* type, meaning that it must always be used behind a
1895 /// pointer like `&` or [`Box`]. For an owned version of this type,
1896 /// see [`PathBuf`].
1898 /// More details about the overall approach can be found in
1899 /// the [module documentation](self).
1904 /// use std::path::Path;
1905 /// use std::ffi::OsStr;
1907 /// // Note: this example does work on Windows
1908 /// let path = Path::new("./foo/bar.txt");
1910 /// let parent = path.parent();
1911 /// assert_eq!(parent, Some(Path::new("./foo")));
1913 /// let file_stem = path.file_stem();
1914 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1916 /// let extension = path.extension();
1917 /// assert_eq!(extension, Some(OsStr::new("txt")));
1919 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1920 #[stable(feature = "rust1", since = "1.0.0")]
1922 // `Path::new` current implementation relies
1923 // on `Path` being layout-compatible with `OsStr`.
1924 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1925 // Anyway, `Path` representation and layout are considered implementation detail, are
1926 // not documented and must not be relied upon.
1931 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1933 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1934 /// See its documentation for more.
1936 /// [`strip_prefix`]: Path::strip_prefix
1937 #[derive(Debug, Clone, PartialEq, Eq)]
1938 #[stable(since = "1.7.0", feature = "strip_prefix")]
1939 pub struct StripPrefixError(());
1942 // The following (private!) function allows construction of a path from a u8
1943 // slice, which is only safe when it is known to follow the OsStr encoding.
1944 unsafe fn from_u8_slice(s
: &[u8]) -> &Path
{
1945 unsafe { Path::new(u8_slice_as_os_str(s)) }
1947 // The following (private!) function reveals the byte encoding used for OsStr.
1948 fn as_u8_slice(&self) -> &[u8] {
1952 /// Directly wraps a string slice as a `Path` slice.
1954 /// This is a cost-free conversion.
1959 /// use std::path::Path;
1961 /// Path::new("foo.txt");
1964 /// You can create `Path`s from `String`s, or even other `Path`s:
1967 /// use std::path::Path;
1969 /// let string = String::from("foo.txt");
1970 /// let from_string = Path::new(&string);
1971 /// let from_path = Path::new(&from_string);
1972 /// assert_eq!(from_string, from_path);
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 pub fn new
<S
: AsRef
<OsStr
> + ?Sized
>(s
: &S
) -> &Path
{
1976 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1979 /// Yields the underlying [`OsStr`] slice.
1984 /// use std::path::Path;
1986 /// let os_str = Path::new("foo.txt").as_os_str();
1987 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1989 #[stable(feature = "rust1", since = "1.0.0")]
1992 pub fn as_os_str(&self) -> &OsStr
{
1996 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1998 /// This conversion may entail doing a check for UTF-8 validity.
1999 /// Note that validation is performed because non-UTF-8 strings are
2000 /// perfectly valid for some OS.
2007 /// use std::path::Path;
2009 /// let path = Path::new("foo.txt");
2010 /// assert_eq!(path.to_str(), Some("foo.txt"));
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 #[must_use = "this returns the result of the operation, \
2014 without modifying the original"]
2016 pub fn to_str(&self) -> Option
<&str> {
2020 /// Converts a `Path` to a [`Cow<str>`].
2022 /// Any non-Unicode sequences are replaced with
2023 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
2025 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
2029 /// Calling `to_string_lossy` on a `Path` with valid unicode:
2032 /// use std::path::Path;
2034 /// let path = Path::new("foo.txt");
2035 /// assert_eq!(path.to_string_lossy(), "foo.txt");
2038 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
2039 /// have returned `"fo�.txt"`.
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 #[must_use = "this returns the result of the operation, \
2042 without modifying the original"]
2044 pub fn to_string_lossy(&self) -> Cow
<'_
, str> {
2045 self.inner
.to_string_lossy()
2048 /// Converts a `Path` to an owned [`PathBuf`].
2053 /// use std::path::Path;
2055 /// let path_buf = Path::new("foo.txt").to_path_buf();
2056 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
2058 #[rustc_conversion_suggestion]
2059 #[must_use = "this returns the result of the operation, \
2060 without modifying the original"]
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 pub fn to_path_buf(&self) -> PathBuf
{
2063 PathBuf
::from(self.inner
.to_os_string())
2066 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
2067 /// the current directory.
2069 /// * On Unix, a path is absolute if it starts with the root, so
2070 /// `is_absolute` and [`has_root`] are equivalent.
2072 /// * On Windows, a path is absolute if it has a prefix and starts with the
2073 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2078 /// use std::path::Path;
2080 /// assert!(!Path::new("foo.txt").is_absolute());
2083 /// [`has_root`]: Path::has_root
2084 #[stable(feature = "rust1", since = "1.0.0")]
2086 #[allow(deprecated)]
2087 pub fn is_absolute(&self) -> bool
{
2088 if cfg
!(target_os
= "redox") {
2089 // FIXME: Allow Redox prefixes
2090 self.has_root() || has_redox_scheme(self.as_u8_slice())
2092 self.has_root() && (cfg
!(any(unix
, target_os
= "wasi")) || self.prefix().is_some())
2096 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2098 /// See [`is_absolute`]'s documentation for more details.
2103 /// use std::path::Path;
2105 /// assert!(Path::new("foo.txt").is_relative());
2108 /// [`is_absolute`]: Path::is_absolute
2109 #[stable(feature = "rust1", since = "1.0.0")]
2112 pub fn is_relative(&self) -> bool
{
2116 fn prefix(&self) -> Option
<Prefix
<'_
>> {
2117 self.components().prefix
2120 /// Returns `true` if the `Path` has a root.
2122 /// * On Unix, a path has a root if it begins with `/`.
2124 /// * On Windows, a path has a root if it:
2125 /// * has no prefix and begins with a separator, e.g., `\windows`
2126 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2127 /// * has any non-disk prefix, e.g., `\\server\share`
2132 /// use std::path::Path;
2134 /// assert!(Path::new("/etc/passwd").has_root());
2136 #[stable(feature = "rust1", since = "1.0.0")]
2139 pub fn has_root(&self) -> bool
{
2140 self.components().has_root()
2143 /// Returns the `Path` without its final component, if there is one.
2145 /// Returns [`None`] if the path terminates in a root or prefix.
2150 /// use std::path::Path;
2152 /// let path = Path::new("/foo/bar");
2153 /// let parent = path.parent().unwrap();
2154 /// assert_eq!(parent, Path::new("/foo"));
2156 /// let grand_parent = parent.parent().unwrap();
2157 /// assert_eq!(grand_parent, Path::new("/"));
2158 /// assert_eq!(grand_parent.parent(), None);
2160 #[stable(feature = "rust1", since = "1.0.0")]
2162 pub fn parent(&self) -> Option
<&Path
> {
2163 let mut comps
= self.components();
2164 let comp
= comps
.next_back();
2165 comp
.and_then(|p
| match p
{
2166 Component
::Normal(_
) | Component
::CurDir
| Component
::ParentDir
=> {
2167 Some(comps
.as_path())
2173 /// Produces an iterator over `Path` and its ancestors.
2175 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2176 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2177 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2178 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2184 /// use std::path::Path;
2186 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2187 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2188 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2189 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2190 /// assert_eq!(ancestors.next(), None);
2192 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2193 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2194 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2195 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2196 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2197 /// assert_eq!(ancestors.next(), None);
2200 /// [`parent`]: Path::parent
2201 #[stable(feature = "path_ancestors", since = "1.28.0")]
2203 pub fn ancestors(&self) -> Ancestors
<'_
> {
2204 Ancestors { next: Some(&self) }
2207 /// Returns the final component of the `Path`, if there is one.
2209 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2210 /// is the directory name.
2212 /// Returns [`None`] if the path terminates in `..`.
2217 /// use std::path::Path;
2218 /// use std::ffi::OsStr;
2220 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2221 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2222 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2223 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2224 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2225 /// assert_eq!(None, Path::new("/").file_name());
2227 #[stable(feature = "rust1", since = "1.0.0")]
2229 pub fn file_name(&self) -> Option
<&OsStr
> {
2230 self.components().next_back().and_then(|p
| match p
{
2231 Component
::Normal(p
) => Some(p
),
2236 /// Returns a path that, when joined onto `base`, yields `self`.
2240 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2241 /// returns `false`), returns [`Err`].
2243 /// [`starts_with`]: Path::starts_with
2248 /// use std::path::{Path, PathBuf};
2250 /// let path = Path::new("/test/haha/foo.txt");
2252 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2253 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2254 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2255 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2256 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2258 /// assert!(path.strip_prefix("test").is_err());
2259 /// assert!(path.strip_prefix("/haha").is_err());
2261 /// let prefix = PathBuf::from("/test/");
2262 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2264 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2265 pub fn strip_prefix
<P
>(&self, base
: P
) -> Result
<&Path
, StripPrefixError
>
2269 self._strip_prefix(base
.as_ref())
2272 fn _strip_prefix(&self, base
: &Path
) -> Result
<&Path
, StripPrefixError
> {
2273 iter_after(self.components(), base
.components())
2274 .map(|c
| c
.as_path())
2275 .ok_or(StripPrefixError(()))
2278 /// Determines whether `base` is a prefix of `self`.
2280 /// Only considers whole path components to match.
2285 /// use std::path::Path;
2287 /// let path = Path::new("/etc/passwd");
2289 /// assert!(path.starts_with("/etc"));
2290 /// assert!(path.starts_with("/etc/"));
2291 /// assert!(path.starts_with("/etc/passwd"));
2292 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2293 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2295 /// assert!(!path.starts_with("/e"));
2296 /// assert!(!path.starts_with("/etc/passwd.txt"));
2298 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2300 #[stable(feature = "rust1", since = "1.0.0")]
2302 pub fn starts_with
<P
: AsRef
<Path
>>(&self, base
: P
) -> bool
{
2303 self._starts_with(base
.as_ref())
2306 fn _starts_with(&self, base
: &Path
) -> bool
{
2307 iter_after(self.components(), base
.components()).is_some()
2310 /// Determines whether `child` is a suffix of `self`.
2312 /// Only considers whole path components to match.
2317 /// use std::path::Path;
2319 /// let path = Path::new("/etc/resolv.conf");
2321 /// assert!(path.ends_with("resolv.conf"));
2322 /// assert!(path.ends_with("etc/resolv.conf"));
2323 /// assert!(path.ends_with("/etc/resolv.conf"));
2325 /// assert!(!path.ends_with("/resolv.conf"));
2326 /// assert!(!path.ends_with("conf")); // use .extension() instead
2328 #[stable(feature = "rust1", since = "1.0.0")]
2330 pub fn ends_with
<P
: AsRef
<Path
>>(&self, child
: P
) -> bool
{
2331 self._ends_with(child
.as_ref())
2334 fn _ends_with(&self, child
: &Path
) -> bool
{
2335 iter_after(self.components().rev(), child
.components().rev()).is_some()
2338 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2340 /// [`self.file_name`]: Path::file_name
2344 /// * [`None`], if there is no file name;
2345 /// * The entire file name if there is no embedded `.`;
2346 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2347 /// * Otherwise, the portion of the file name before the final `.`
2352 /// use std::path::Path;
2354 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2355 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2359 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2360 /// before the *first* `.`
2362 /// [`Path::file_prefix`]: Path::file_prefix
2364 #[stable(feature = "rust1", since = "1.0.0")]
2366 pub fn file_stem(&self) -> Option
<&OsStr
> {
2367 self.file_name().map(rsplit_file_at_dot
).and_then(|(before
, after
)| before
.or(after
))
2370 /// Extracts the prefix of [`self.file_name`].
2374 /// * [`None`], if there is no file name;
2375 /// * The entire file name if there is no embedded `.`;
2376 /// * The portion of the file name before the first non-beginning `.`;
2377 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2378 /// * The portion of the file name before the second `.` if the file name begins with `.`
2380 /// [`self.file_name`]: Path::file_name
2385 /// # #![feature(path_file_prefix)]
2386 /// use std::path::Path;
2388 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2389 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2393 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2394 /// before the *last* `.`
2396 /// [`Path::file_stem`]: Path::file_stem
2398 #[unstable(feature = "path_file_prefix", issue = "86319")]
2400 pub fn file_prefix(&self) -> Option
<&OsStr
> {
2401 self.file_name().map(split_file_at_dot
).and_then(|(before
, _after
)| Some(before
))
2404 /// Extracts the extension of [`self.file_name`], if possible.
2406 /// The extension is:
2408 /// * [`None`], if there is no file name;
2409 /// * [`None`], if there is no embedded `.`;
2410 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2411 /// * Otherwise, the portion of the file name after the final `.`
2413 /// [`self.file_name`]: Path::file_name
2418 /// use std::path::Path;
2420 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2421 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2423 #[stable(feature = "rust1", since = "1.0.0")]
2425 pub fn extension(&self) -> Option
<&OsStr
> {
2426 self.file_name().map(rsplit_file_at_dot
).and_then(|(before
, after
)| before
.and(after
))
2429 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2431 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2436 /// use std::path::{Path, PathBuf};
2438 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2440 #[stable(feature = "rust1", since = "1.0.0")]
2442 pub fn join
<P
: AsRef
<Path
>>(&self, path
: P
) -> PathBuf
{
2443 self._join(path
.as_ref())
2446 fn _join(&self, path
: &Path
) -> PathBuf
{
2447 let mut buf
= self.to_path_buf();
2452 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2454 /// See [`PathBuf::set_file_name`] for more details.
2459 /// use std::path::{Path, PathBuf};
2461 /// let path = Path::new("/tmp/foo.txt");
2462 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2464 /// let path = Path::new("/tmp");
2465 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2467 #[stable(feature = "rust1", since = "1.0.0")]
2469 pub fn with_file_name
<S
: AsRef
<OsStr
>>(&self, file_name
: S
) -> PathBuf
{
2470 self._with_file_name(file_name
.as_ref())
2473 fn _with_file_name(&self, file_name
: &OsStr
) -> PathBuf
{
2474 let mut buf
= self.to_path_buf();
2475 buf
.set_file_name(file_name
);
2479 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2481 /// See [`PathBuf::set_extension`] for more details.
2486 /// use std::path::{Path, PathBuf};
2488 /// let path = Path::new("foo.rs");
2489 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2491 /// let path = Path::new("foo.tar.gz");
2492 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2493 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2494 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2496 #[stable(feature = "rust1", since = "1.0.0")]
2497 pub fn with_extension
<S
: AsRef
<OsStr
>>(&self, extension
: S
) -> PathBuf
{
2498 self._with_extension(extension
.as_ref())
2501 fn _with_extension(&self, extension
: &OsStr
) -> PathBuf
{
2502 let mut buf
= self.to_path_buf();
2503 buf
.set_extension(extension
);
2507 /// Produces an iterator over the [`Component`]s of the path.
2509 /// When parsing the path, there is a small amount of normalization:
2511 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2512 /// `a` and `b` as components.
2514 /// * Occurrences of `.` are normalized away, except if they are at the
2515 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2516 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2517 /// an additional [`CurDir`] component.
2519 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2521 /// Note that no other normalization takes place; in particular, `a/c`
2522 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2523 /// is a symbolic link (so its parent isn't `a`).
2528 /// use std::path::{Path, Component};
2529 /// use std::ffi::OsStr;
2531 /// let mut components = Path::new("/tmp/foo.txt").components();
2533 /// assert_eq!(components.next(), Some(Component::RootDir));
2534 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2535 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2536 /// assert_eq!(components.next(), None)
2539 /// [`CurDir`]: Component::CurDir
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 pub fn components(&self) -> Components
<'_
> {
2542 let prefix
= parse_prefix(self.as_os_str());
2544 path
: self.as_u8_slice(),
2546 has_physical_root
: has_physical_root(self.as_u8_slice(), prefix
)
2547 || has_redox_scheme(self.as_u8_slice()),
2548 front
: State
::Prefix
,
2553 /// Produces an iterator over the path's components viewed as [`OsStr`]
2556 /// For more information about the particulars of how the path is separated
2557 /// into components, see [`components`].
2559 /// [`components`]: Path::components
2564 /// use std::path::{self, Path};
2565 /// use std::ffi::OsStr;
2567 /// let mut it = Path::new("/tmp/foo.txt").iter();
2568 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2569 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2570 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2571 /// assert_eq!(it.next(), None)
2573 #[stable(feature = "rust1", since = "1.0.0")]
2575 pub fn iter(&self) -> Iter
<'_
> {
2576 Iter { inner: self.components() }
2579 /// Returns an object that implements [`Display`] for safely printing paths
2580 /// that may contain non-Unicode data. This may perform lossy conversion,
2581 /// depending on the platform. If you would like an implementation which
2582 /// escapes the path please use [`Debug`] instead.
2584 /// [`Display`]: fmt::Display
2589 /// use std::path::Path;
2591 /// let path = Path::new("/tmp/foo.rs");
2593 /// println!("{}", path.display());
2595 #[stable(feature = "rust1", since = "1.0.0")]
2596 #[must_use = "this does not display the path, \
2597 it returns an object that can be displayed"]
2599 pub fn display(&self) -> Display
<'_
> {
2600 Display { path: self }
2603 /// Queries the file system to get information about a file, directory, etc.
2605 /// This function will traverse symbolic links to query information about the
2606 /// destination file.
2608 /// This is an alias to [`fs::metadata`].
2613 /// use std::path::Path;
2615 /// let path = Path::new("/Minas/tirith");
2616 /// let metadata = path.metadata().expect("metadata call failed");
2617 /// println!("{:?}", metadata.file_type());
2619 #[stable(feature = "path_ext", since = "1.5.0")]
2621 pub fn metadata(&self) -> io
::Result
<fs
::Metadata
> {
2625 /// Queries the metadata about a file without following symlinks.
2627 /// This is an alias to [`fs::symlink_metadata`].
2632 /// use std::path::Path;
2634 /// let path = Path::new("/Minas/tirith");
2635 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2636 /// println!("{:?}", metadata.file_type());
2638 #[stable(feature = "path_ext", since = "1.5.0")]
2640 pub fn symlink_metadata(&self) -> io
::Result
<fs
::Metadata
> {
2641 fs
::symlink_metadata(self)
2644 /// Returns the canonical, absolute form of the path with all intermediate
2645 /// components normalized and symbolic links resolved.
2647 /// This is an alias to [`fs::canonicalize`].
2652 /// use std::path::{Path, PathBuf};
2654 /// let path = Path::new("/foo/test/../test/bar.rs");
2655 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2657 #[stable(feature = "path_ext", since = "1.5.0")]
2659 pub fn canonicalize(&self) -> io
::Result
<PathBuf
> {
2660 fs
::canonicalize(self)
2663 /// Reads a symbolic link, returning the file that the link points to.
2665 /// This is an alias to [`fs::read_link`].
2670 /// use std::path::Path;
2672 /// let path = Path::new("/laputa/sky_castle.rs");
2673 /// let path_link = path.read_link().expect("read_link call failed");
2675 #[stable(feature = "path_ext", since = "1.5.0")]
2677 pub fn read_link(&self) -> io
::Result
<PathBuf
> {
2681 /// Returns an iterator over the entries within a directory.
2683 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
2684 /// errors may be encountered after an iterator is initially constructed.
2686 /// This is an alias to [`fs::read_dir`].
2691 /// use std::path::Path;
2693 /// let path = Path::new("/laputa");
2694 /// for entry in path.read_dir().expect("read_dir call failed") {
2695 /// if let Ok(entry) = entry {
2696 /// println!("{:?}", entry.path());
2700 #[stable(feature = "path_ext", since = "1.5.0")]
2702 pub fn read_dir(&self) -> io
::Result
<fs
::ReadDir
> {
2706 /// Returns `true` if the path points at an existing entity.
2708 /// Warning: this method may be error-prone, consider using [`try_exists()`] instead!
2709 /// It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.
2711 /// This function will traverse symbolic links to query information about the
2712 /// destination file.
2714 /// If you cannot access the metadata of the file, e.g. because of a
2715 /// permission error or broken symbolic links, this will return `false`.
2720 /// use std::path::Path;
2721 /// assert!(!Path::new("does_not_exist.txt").exists());
2726 /// This is a convenience function that coerces errors to false. If you want to
2727 /// check errors, call [`Path::try_exists`].
2729 /// [`try_exists()`]: Self::try_exists
2730 #[stable(feature = "path_ext", since = "1.5.0")]
2733 pub fn exists(&self) -> bool
{
2734 fs
::metadata(self).is_ok()
2737 /// Returns `Ok(true)` if the path points at an existing entity.
2739 /// This function will traverse symbolic links to query information about the
2740 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2742 /// As opposed to the [`exists()`] method, this one doesn't silently ignore errors
2743 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2744 /// denied on some of the parent directories.)
2746 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
2747 /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
2748 /// where those bugs are not an issue.
2753 /// use std::path::Path;
2754 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2755 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2758 /// [`exists()`]: Self::exists
2759 #[stable(feature = "path_try_exists", since = "1.63.0")]
2761 pub fn try_exists(&self) -> io
::Result
<bool
> {
2762 fs
::try_exists(self)
2765 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2767 /// This function will traverse symbolic links to query information about the
2768 /// destination file.
2770 /// If you cannot access the metadata of the file, e.g. because of a
2771 /// permission error or broken symbolic links, this will return `false`.
2776 /// use std::path::Path;
2777 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2778 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2783 /// This is a convenience function that coerces errors to false. If you want to
2784 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2785 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2787 /// When the goal is simply to read from (or write to) the source, the most
2788 /// reliable way to test the source can be read (or written to) is to open
2789 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2790 /// a Unix-like system for example. See [`fs::File::open`] or
2791 /// [`fs::OpenOptions::open`] for more information.
2792 #[stable(feature = "path_ext", since = "1.5.0")]
2794 pub fn is_file(&self) -> bool
{
2795 fs
::metadata(self).map(|m
| m
.is_file()).unwrap_or(false)
2798 /// Returns `true` if the path exists on disk and is pointing at a directory.
2800 /// This function will traverse symbolic links to query information about the
2801 /// destination file.
2803 /// If you cannot access the metadata of the file, e.g. because of a
2804 /// permission error or broken symbolic links, this will return `false`.
2809 /// use std::path::Path;
2810 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2811 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2816 /// This is a convenience function that coerces errors to false. If you want to
2817 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2818 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2819 #[stable(feature = "path_ext", since = "1.5.0")]
2821 pub fn is_dir(&self) -> bool
{
2822 fs
::metadata(self).map(|m
| m
.is_dir()).unwrap_or(false)
2825 /// Returns `true` if the path exists on disk and is pointing at a symbolic link.
2827 /// This function will not traverse symbolic links.
2828 /// In case of a broken symbolic link this will also return true.
2830 /// If you cannot access the directory containing the file, e.g., because of a
2831 /// permission error, this will return false.
2835 #[cfg_attr(unix, doc = "```no_run")]
2836 #[cfg_attr(not(unix), doc = "```ignore")]
2837 /// use std::path::Path;
2838 /// use std::os::unix::fs::symlink;
2840 /// let link_path = Path::new("link");
2841 /// symlink("/origin_does_not_exist/", link_path).unwrap();
2842 /// assert_eq!(link_path.is_symlink(), true);
2843 /// assert_eq!(link_path.exists(), false);
2848 /// This is a convenience function that coerces errors to false. If you want to
2849 /// check errors, call [`fs::symlink_metadata`] and handle its [`Result`]. Then call
2850 /// [`fs::Metadata::is_symlink`] if it was [`Ok`].
2852 #[stable(feature = "is_symlink", since = "1.58.0")]
2853 pub fn is_symlink(&self) -> bool
{
2854 fs
::symlink_metadata(self).map(|m
| m
.is_symlink()).unwrap_or(false)
2857 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2859 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2860 #[must_use = "`self` will be dropped if the result is not used"]
2861 pub fn into_path_buf(self: Box
<Path
>) -> PathBuf
{
2862 let rw
= Box
::into_raw(self) as *mut OsStr
;
2863 let inner
= unsafe { Box::from_raw(rw) }
;
2864 PathBuf { inner: OsString::from(inner) }
2868 #[stable(feature = "rust1", since = "1.0.0")]
2869 impl AsRef
<OsStr
> for Path
{
2871 fn as_ref(&self) -> &OsStr
{
2876 #[stable(feature = "rust1", since = "1.0.0")]
2877 impl fmt
::Debug
for Path
{
2878 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2879 fmt
::Debug
::fmt(&self.inner
, formatter
)
2883 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2885 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2886 /// [`Display`] trait in a way that mitigates that. It is created by the
2887 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2888 /// conversion, depending on the platform. If you would like an implementation
2889 /// which escapes the path please use [`Debug`] instead.
2894 /// use std::path::Path;
2896 /// let path = Path::new("/tmp/foo.rs");
2898 /// println!("{}", path.display());
2901 /// [`Display`]: fmt::Display
2902 /// [`format!`]: crate::format
2903 #[stable(feature = "rust1", since = "1.0.0")]
2904 pub struct Display
<'a
> {
2908 #[stable(feature = "rust1", since = "1.0.0")]
2909 impl fmt
::Debug
for Display
<'_
> {
2910 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2911 fmt
::Debug
::fmt(&self.path
, f
)
2915 #[stable(feature = "rust1", since = "1.0.0")]
2916 impl fmt
::Display
for Display
<'_
> {
2917 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2918 self.path
.inner
.display(f
)
2922 #[stable(feature = "rust1", since = "1.0.0")]
2923 impl cmp
::PartialEq
for Path
{
2925 fn eq(&self, other
: &Path
) -> bool
{
2926 self.components() == other
.components()
2930 #[stable(feature = "rust1", since = "1.0.0")]
2931 impl Hash
for Path
{
2932 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
2933 let bytes
= self.as_u8_slice();
2934 let (prefix_len
, verbatim
) = match parse_prefix(&self.inner
) {
2937 (prefix
.len(), prefix
.is_verbatim())
2941 let bytes
= &bytes
[prefix_len
..];
2943 let mut component_start
= 0;
2944 let mut bytes_hashed
= 0;
2946 for i
in 0..bytes
.len() {
2947 let is_sep
= if verbatim { is_verbatim_sep(bytes[i]) }
else { is_sep_byte(bytes[i]) }
;
2949 if i
> component_start
{
2950 let to_hash
= &bytes
[component_start
..i
];
2952 bytes_hashed
+= to_hash
.len();
2955 // skip over separator and optionally a following CurDir item
2956 // since components() would normalize these away.
2957 component_start
= i
+ 1;
2959 let tail
= &bytes
[component_start
..];
2962 component_start
+= match tail
{
2964 [b'
.'
, sep @ _
, ..] if is_sep_byte(*sep
) => 1,
2971 if component_start
< bytes
.len() {
2972 let to_hash
= &bytes
[component_start
..];
2974 bytes_hashed
+= to_hash
.len();
2977 h
.write_usize(bytes_hashed
);
2981 #[stable(feature = "rust1", since = "1.0.0")]
2982 impl cmp
::Eq
for Path {}
2984 #[stable(feature = "rust1", since = "1.0.0")]
2985 impl cmp
::PartialOrd
for Path
{
2987 fn partial_cmp(&self, other
: &Path
) -> Option
<cmp
::Ordering
> {
2988 Some(compare_components(self.components(), other
.components()))
2992 #[stable(feature = "rust1", since = "1.0.0")]
2993 impl cmp
::Ord
for Path
{
2995 fn cmp(&self, other
: &Path
) -> cmp
::Ordering
{
2996 compare_components(self.components(), other
.components())
3000 #[stable(feature = "rust1", since = "1.0.0")]
3001 impl AsRef
<Path
> for Path
{
3003 fn as_ref(&self) -> &Path
{
3008 #[stable(feature = "rust1", since = "1.0.0")]
3009 impl AsRef
<Path
> for OsStr
{
3011 fn as_ref(&self) -> &Path
{
3016 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
3017 impl AsRef
<Path
> for Cow
<'_
, OsStr
> {
3019 fn as_ref(&self) -> &Path
{
3024 #[stable(feature = "rust1", since = "1.0.0")]
3025 impl AsRef
<Path
> for OsString
{
3027 fn as_ref(&self) -> &Path
{
3032 #[stable(feature = "rust1", since = "1.0.0")]
3033 impl AsRef
<Path
> for str {
3035 fn as_ref(&self) -> &Path
{
3040 #[stable(feature = "rust1", since = "1.0.0")]
3041 impl AsRef
<Path
> for String
{
3043 fn as_ref(&self) -> &Path
{
3048 #[stable(feature = "rust1", since = "1.0.0")]
3049 impl AsRef
<Path
> for PathBuf
{
3051 fn as_ref(&self) -> &Path
{
3056 #[stable(feature = "path_into_iter", since = "1.6.0")]
3057 impl<'a
> IntoIterator
for &'a PathBuf
{
3058 type Item
= &'a OsStr
;
3059 type IntoIter
= Iter
<'a
>;
3061 fn into_iter(self) -> Iter
<'a
> {
3066 #[stable(feature = "path_into_iter", since = "1.6.0")]
3067 impl<'a
> IntoIterator
for &'a Path
{
3068 type Item
= &'a OsStr
;
3069 type IntoIter
= Iter
<'a
>;
3071 fn into_iter(self) -> Iter
<'a
> {
3076 macro_rules
! impl_cmp
{
3077 ($lhs
:ty
, $rhs
: ty
) => {
3078 #[stable(feature = "partialeq_path", since = "1.6.0")]
3079 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
3081 fn eq(&self, other
: &$rhs
) -> bool
{
3082 <Path
as PartialEq
>::eq(self, other
)
3086 #[stable(feature = "partialeq_path", since = "1.6.0")]
3087 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
3089 fn eq(&self, other
: &$lhs
) -> bool
{
3090 <Path
as PartialEq
>::eq(self, other
)
3094 #[stable(feature = "cmp_path", since = "1.8.0")]
3095 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
3097 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
3098 <Path
as PartialOrd
>::partial_cmp(self, other
)
3102 #[stable(feature = "cmp_path", since = "1.8.0")]
3103 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
3105 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
3106 <Path
as PartialOrd
>::partial_cmp(self, other
)
3112 impl_cmp
!(PathBuf
, Path
);
3113 impl_cmp
!(PathBuf
, &'a Path
);
3114 impl_cmp
!(Cow
<'a
, Path
>, Path
);
3115 impl_cmp
!(Cow
<'a
, Path
>, &'b Path
);
3116 impl_cmp
!(Cow
<'a
, Path
>, PathBuf
);
3118 macro_rules
! impl_cmp_os_str
{
3119 ($lhs
:ty
, $rhs
: ty
) => {
3120 #[stable(feature = "cmp_path", since = "1.8.0")]
3121 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
3123 fn eq(&self, other
: &$rhs
) -> bool
{
3124 <Path
as PartialEq
>::eq(self, other
.as_ref())
3128 #[stable(feature = "cmp_path", since = "1.8.0")]
3129 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
3131 fn eq(&self, other
: &$lhs
) -> bool
{
3132 <Path
as PartialEq
>::eq(self.as_ref(), other
)
3136 #[stable(feature = "cmp_path", since = "1.8.0")]
3137 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
3139 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
3140 <Path
as PartialOrd
>::partial_cmp(self, other
.as_ref())
3144 #[stable(feature = "cmp_path", since = "1.8.0")]
3145 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
3147 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
3148 <Path
as PartialOrd
>::partial_cmp(self.as_ref(), other
)
3154 impl_cmp_os_str
!(PathBuf
, OsStr
);
3155 impl_cmp_os_str
!(PathBuf
, &'a OsStr
);
3156 impl_cmp_os_str
!(PathBuf
, Cow
<'a
, OsStr
>);
3157 impl_cmp_os_str
!(PathBuf
, OsString
);
3158 impl_cmp_os_str
!(Path
, OsStr
);
3159 impl_cmp_os_str
!(Path
, &'a OsStr
);
3160 impl_cmp_os_str
!(Path
, Cow
<'a
, OsStr
>);
3161 impl_cmp_os_str
!(Path
, OsString
);
3162 impl_cmp_os_str
!(&'a Path
, OsStr
);
3163 impl_cmp_os_str
!(&'a Path
, Cow
<'b
, OsStr
>);
3164 impl_cmp_os_str
!(&'a Path
, OsString
);
3165 impl_cmp_os_str
!(Cow
<'a
, Path
>, OsStr
);
3166 impl_cmp_os_str
!(Cow
<'a
, Path
>, &'b OsStr
);
3167 impl_cmp_os_str
!(Cow
<'a
, Path
>, OsString
);
3169 #[stable(since = "1.7.0", feature = "strip_prefix")]
3170 impl fmt
::Display
for StripPrefixError
{
3171 #[allow(deprecated, deprecated_in_future)]
3172 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3173 self.description().fmt(f
)
3177 #[stable(since = "1.7.0", feature = "strip_prefix")]
3178 impl Error
for StripPrefixError
{
3179 #[allow(deprecated)]
3180 fn description(&self) -> &str {
3185 /// Makes the path absolute without accessing the filesystem.
3187 /// If the path is relative, the current directory is used as the base directory.
3188 /// All intermediate components will be resolved according to platforms-specific
3189 /// rules but unlike [`canonicalize`][crate::fs::canonicalize] this does not
3190 /// resolve symlinks and may succeed even if the path does not exist.
3192 /// If the `path` is empty or getting the
3193 /// [current directory][crate::env::current_dir] fails then an error will be
3201 /// #![feature(absolute_path)]
3203 /// fn main() -> std::io::Result<()> {
3204 /// use std::path::{self, Path};
3206 /// // Relative to absolute
3207 /// let absolute = path::absolute("foo/./bar")?;
3208 /// assert!(absolute.ends_with("foo/bar"));
3210 /// // Absolute to absolute
3211 /// let absolute = path::absolute("/foo//test/.././bar.rs")?;
3212 /// assert_eq!(absolute, Path::new("/foo/test/../bar.rs"));
3215 /// # #[cfg(not(unix))]
3219 /// The path is resolved using [POSIX semantics][posix-semantics] except that
3220 /// it stops short of resolving symlinks. This means it will keep `..`
3221 /// components and trailing slashes.
3223 /// ## Windows paths
3226 /// #![feature(absolute_path)]
3227 /// # #[cfg(windows)]
3228 /// fn main() -> std::io::Result<()> {
3229 /// use std::path::{self, Path};
3231 /// // Relative to absolute
3232 /// let absolute = path::absolute("foo/./bar")?;
3233 /// assert!(absolute.ends_with(r"foo\bar"));
3235 /// // Absolute to absolute
3236 /// let absolute = path::absolute(r"C:\foo//test\..\./bar.rs")?;
3238 /// assert_eq!(absolute, Path::new(r"C:\foo\bar.rs"));
3241 /// # #[cfg(not(windows))]
3245 /// For verbatim paths this will simply return the path as given. For other
3246 /// paths this is currently equivalent to calling [`GetFullPathNameW`][windows-path]
3247 /// This may change in the future.
3249 /// [posix-semantics]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
3250 /// [windows-path]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
3251 #[unstable(feature = "absolute_path", issue = "92750")]
3252 pub fn absolute
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<PathBuf
> {
3253 let path
= path
.as_ref();
3254 if path
.as_os_str().is_empty() {
3255 Err(io
::const_io_error
!(io
::ErrorKind
::InvalidInput
, "cannot make an empty path absolute",))
3257 sys
::path
::absolute(path
)