1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Cross-platform path manipulation.
13 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
14 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
15 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
18 //! Paths can be parsed into [`Component`]s by iterating over the structure
19 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
20 //! correspond to the substrings between path separators (`/` or `\`). You can
21 //! reconstruct an equivalent path from components with the [`push`] method on
22 //! [`PathBuf`]; note that the paths may differ syntactically by the
23 //! normalization described in the documentation for the [`components`] method.
27 //! Path manipulation includes both parsing components from slices and building
30 //! To parse a path, you can create a [`Path`] slice from a [`str`]
31 //! slice and start asking questions:
34 //! use std::path::Path;
35 //! use std::ffi::OsStr;
37 //! let path = Path::new("/tmp/foo/bar.txt");
39 //! let parent = path.parent();
40 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
42 //! let file_stem = path.file_stem();
43 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
45 //! let extension = path.extension();
46 //! assert_eq!(extension, Some(OsStr::new("txt")));
49 //! To build or modify paths, use [`PathBuf`]:
52 //! use std::path::PathBuf;
54 //! // This way works...
55 //! let mut path = PathBuf::from("c:\\");
57 //! path.push("windows");
58 //! path.push("system32");
60 //! path.set_extension("dll");
62 //! // ... but push is best used if you don't know everything up
63 //! // front. If you do, this way is better:
64 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
67 //! [`Component`]: ../../std/path/enum.Component.html
68 //! [`components`]: ../../std/path/struct.Path.html#method.components
69 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
70 //! [`Path`]: ../../std/path/struct.Path.html
71 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
72 //! [`String`]: ../../std/string/struct.String.html
74 //! [`str`]: ../../std/primitive.str.html
75 //! [`OsString`]: ../../std/ffi/struct.OsString.html
76 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
78 #![stable(feature = "rust1", since = "1.0.0")]
81 use borrow
::{Borrow, Cow}
;
86 use hash
::{Hash, Hasher}
;
88 use iter
::{self, FusedIterator}
;
90 use ops
::{self, Deref}
;
92 use ffi
::{OsStr, OsString}
;
94 use sys
::path
::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix}
;
96 ////////////////////////////////////////////////////////////////////////////////
98 ////////////////////////////////////////////////////////////////////////////////
100 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
101 // taking advantage of the fact that OsStr always encodes ASCII characters
102 // as-is. Eventually, this transmutation should be replaced by direct uses of
103 // OsStr APIs for parsing, but it will take a while for those to become
106 ////////////////////////////////////////////////////////////////////////////////
108 ////////////////////////////////////////////////////////////////////////////////
110 /// Windows path prefixes, e.g. `C:` or `\\server\share`.
112 /// Windows uses a variety of path prefix styles, including references to drive
113 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
114 /// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
115 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
116 /// no normalization is performed.
121 /// use std::path::{Component, Path, Prefix};
122 /// use std::path::Prefix::*;
123 /// use std::ffi::OsStr;
125 /// fn get_path_prefix(s: &str) -> Prefix {
126 /// let path = Path::new(s);
127 /// match path.components().next().unwrap() {
128 /// Component::Prefix(prefix_component) => prefix_component.kind(),
133 /// # if cfg!(windows) {
134 /// assert_eq!(Verbatim(OsStr::new("pictures")),
135 /// get_path_prefix(r"\\?\pictures\kittens"));
136 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
137 /// get_path_prefix(r"\\?\UNC\server\share"));
138 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
139 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
140 /// get_path_prefix(r"\\.\BrainInterface"));
141 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
142 /// get_path_prefix(r"\\server\share"));
143 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
146 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub enum Prefix
<'a
> {
149 /// Verbatim prefix, e.g. `\\?\cat_pics`.
151 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
153 #[stable(feature = "rust1", since = "1.0.0")]
154 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
156 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
157 /// e.g. `\\?\UNC\server\share`.
159 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
160 /// server's hostname and a share name.
161 #[stable(feature = "rust1", since = "1.0.0")]
163 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
164 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
167 /// Verbatim disk prefix, e.g. `\\?\C:\`.
169 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
170 /// drive letter and `:\`.
171 #[stable(feature = "rust1", since = "1.0.0")]
172 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
174 /// Device namespace prefix, e.g. `\\.\COM42`.
176 /// Device namespace prefixes consist of `\\.\` immediately followed by the
178 #[stable(feature = "rust1", since = "1.0.0")]
179 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
181 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
182 /// `\\server\share`.
184 /// UNC prefixes consist of the server's hostname and a share name.
185 #[stable(feature = "rust1", since = "1.0.0")]
187 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
188 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
191 /// Prefix `C:` for the given disk drive.
192 #[stable(feature = "rust1", since = "1.0.0")]
193 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
196 impl<'a
> Prefix
<'a
> {
198 fn len(&self) -> usize {
200 fn os_str_len(s
: &OsStr
) -> usize {
201 os_str_as_u8_slice(s
).len()
204 Verbatim(x
) => 4 + os_str_len(x
),
205 VerbatimUNC(x
, y
) => {
207 if os_str_len(y
) > 0 {
213 VerbatimDisk(_
) => 6,
216 if os_str_len(y
) > 0 {
222 DeviceNS(x
) => 4 + os_str_len(x
),
228 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
233 /// use std::path::Prefix::*;
234 /// use std::ffi::OsStr;
236 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
237 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
238 /// assert!(VerbatimDisk(b'C').is_verbatim());
239 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
240 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
241 /// assert!(!Disk(b'C').is_verbatim());
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn is_verbatim(&self) -> bool
{
248 Verbatim(_
) | VerbatimDisk(_
) | VerbatimUNC(..) => true,
254 fn is_drive(&self) -> bool
{
256 Prefix
::Disk(_
) => true,
262 fn has_implicit_root(&self) -> bool
{
267 ////////////////////////////////////////////////////////////////////////////////
268 // Exposed parsing helpers
269 ////////////////////////////////////////////////////////////////////////////////
271 /// Determines whether the character is one of the permitted path
272 /// separators for the current platform.
279 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
280 /// assert!(!path::is_separator('❤'));
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn is_separator(c
: char) -> bool
{
284 c
.is_ascii() && is_sep_byte(c
as u8)
287 /// The primary separator of path components for the current platform.
289 /// For example, `/` on Unix and `\` on Windows.
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub const MAIN_SEPARATOR
: char = ::sys
::path
::MAIN_SEP
;
293 ////////////////////////////////////////////////////////////////////////////////
295 ////////////////////////////////////////////////////////////////////////////////
297 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
298 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
299 // `iter` after having exhausted `prefix`.
300 fn iter_after
<A
, I
, J
>(mut iter
: I
, mut prefix
: J
) -> Option
<I
>
301 where I
: Iterator
<Item
= A
> + Clone
,
302 J
: Iterator
<Item
= A
>,
306 let mut iter_next
= iter
.clone();
307 match (iter_next
.next(), prefix
.next()) {
308 (Some(ref x
), Some(ref y
)) if x
== y
=> (),
309 (Some(_
), Some(_
)) => return None
,
310 (Some(_
), None
) => return Some(iter
),
311 (None
, None
) => return Some(iter
),
312 (None
, Some(_
)) => return None
,
318 // See note at the top of this module to understand why these are used:
319 fn os_str_as_u8_slice(s
: &OsStr
) -> &[u8] {
320 unsafe { mem::transmute(s) }
322 unsafe fn u8_slice_as_os_str(s
: &[u8]) -> &OsStr
{
326 ////////////////////////////////////////////////////////////////////////////////
327 // Cross-platform, iterator-independent parsing
328 ////////////////////////////////////////////////////////////////////////////////
330 /// Says whether the first byte after the prefix is a separator.
331 fn has_physical_root(s
: &[u8], prefix
: Option
<Prefix
>) -> bool
{
332 let path
= if let Some(p
) = prefix
{
337 !path
.is_empty() && is_sep_byte(path
[0])
340 // basic workhorse for splitting stem and extension
341 fn split_file_at_dot(file
: &OsStr
) -> (Option
<&OsStr
>, Option
<&OsStr
>) {
343 if os_str_as_u8_slice(file
) == b
".." {
344 return (Some(file
), None
);
347 // The unsafety here stems from converting between &OsStr and &[u8]
348 // and back. This is safe to do because (1) we only look at ASCII
349 // contents of the encoding and (2) new &OsStr values are produced
350 // only from ASCII-bounded slices of existing &OsStr values.
352 let mut iter
= os_str_as_u8_slice(file
).rsplitn(2, |b
| *b
== b'
.'
);
353 let after
= iter
.next();
354 let before
= iter
.next();
355 if before
== Some(b
"") {
358 (before
.map(|s
| u8_slice_as_os_str(s
)),
359 after
.map(|s
| u8_slice_as_os_str(s
)))
364 ////////////////////////////////////////////////////////////////////////////////
365 // The core iterators
366 ////////////////////////////////////////////////////////////////////////////////
368 /// Component parsing works by a double-ended state machine; the cursors at the
369 /// front and back of the path each keep track of what parts of the path have
370 /// been consumed so far.
372 /// Going front to back, a path is made up of a prefix, a starting
373 /// directory component, and a body (of normal components)
374 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
377 StartDir
= 1, // / or . or nothing
378 Body
= 2, // foo/bar/baz
382 /// A structure wrapping a Windows path prefix as well as its unparsed string
385 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
386 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
387 /// returned by [`as_os_str`].
389 /// Instances of this `struct` can be obtained by matching against the
390 /// [`Prefix` variant] on [`Component`].
392 /// Does not occur on Unix.
397 /// # if cfg!(windows) {
398 /// use std::path::{Component, Path, Prefix};
399 /// use std::ffi::OsStr;
401 /// let path = Path::new(r"c:\you\later\");
402 /// match path.components().next().unwrap() {
403 /// Component::Prefix(prefix_component) => {
404 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
405 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
407 /// _ => unreachable!(),
412 /// [`as_os_str`]: #method.as_os_str
413 /// [`Component`]: enum.Component.html
414 /// [`kind`]: #method.kind
415 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
416 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
417 /// [`Prefix`]: enum.Prefix.html
418 #[stable(feature = "rust1", since = "1.0.0")]
419 #[derive(Copy, Clone, Eq, Debug)]
420 pub struct PrefixComponent
<'a
> {
421 /// The prefix as an unparsed `OsStr` slice.
424 /// The parsed prefix data.
428 impl<'a
> PrefixComponent
<'a
> {
429 /// Returns the parsed prefix data.
431 /// See [`Prefix`]'s documentation for more information on the different
432 /// kinds of prefixes.
434 /// [`Prefix`]: enum.Prefix.html
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn kind(&self) -> Prefix
<'a
> {
440 /// Returns the raw [`OsStr`] slice for this prefix.
442 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn as_os_str(&self) -> &'a OsStr
{
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl<'a
> cmp
::PartialEq
for PrefixComponent
<'a
> {
451 fn eq(&self, other
: &PrefixComponent
<'a
>) -> bool
{
452 cmp
::PartialEq
::eq(&self.parsed
, &other
.parsed
)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<'a
> cmp
::PartialOrd
for PrefixComponent
<'a
> {
458 fn partial_cmp(&self, other
: &PrefixComponent
<'a
>) -> Option
<cmp
::Ordering
> {
459 cmp
::PartialOrd
::partial_cmp(&self.parsed
, &other
.parsed
)
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl<'a
> cmp
::Ord
for PrefixComponent
<'a
> {
465 fn cmp(&self, other
: &PrefixComponent
<'a
>) -> cmp
::Ordering
{
466 cmp
::Ord
::cmp(&self.parsed
, &other
.parsed
)
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<'a
> Hash
for PrefixComponent
<'a
> {
472 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
477 /// A single component of a path.
479 /// A `Component` roughtly corresponds to a substring between path separators
482 /// This `enum` is created by iterating over [`Components`], which in turn is
483 /// created by the [`components`][`Path::components`] method on [`Path`].
488 /// use std::path::{Component, Path};
490 /// let path = Path::new("/tmp/foo/bar.txt");
491 /// let components = path.components().collect::<Vec<_>>();
492 /// assert_eq!(&components, &[
493 /// Component::RootDir,
494 /// Component::Normal("tmp".as_ref()),
495 /// Component::Normal("foo".as_ref()),
496 /// Component::Normal("bar.txt".as_ref()),
500 /// [`Components`]: struct.Components.html
501 /// [`Path`]: struct.Path.html
502 /// [`Path::components`]: struct.Path.html#method.components
503 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub enum Component
<'a
> {
506 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
508 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
511 /// Does not occur on Unix.
513 /// [`Prefix`]: enum.Prefix.html
514 #[stable(feature = "rust1", since = "1.0.0")]
516 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
519 /// The root directory component, appears after any prefix and before anything else.
521 /// It represents a separator that designates that a path starts from root.
522 #[stable(feature = "rust1", since = "1.0.0")]
525 /// A reference to the current directory, i.e. `.`.
526 #[stable(feature = "rust1", since = "1.0.0")]
529 /// A reference to the parent directory, i.e. `..`.
530 #[stable(feature = "rust1", since = "1.0.0")]
533 /// A normal component, e.g. `a` and `b` in `a/b`.
535 /// This variant is the most common one, it represents references to files
537 #[stable(feature = "rust1", since = "1.0.0")]
538 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
541 impl<'a
> Component
<'a
> {
542 /// Extracts the underlying [`OsStr`] slice.
547 /// use std::path::Path;
549 /// let path = Path::new("./tmp/foo/bar.txt");
550 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
551 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
554 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub fn as_os_str(self) -> &'a OsStr
{
558 Component
::Prefix(p
) => p
.as_os_str(),
559 Component
::RootDir
=> OsStr
::new(MAIN_SEP_STR
),
560 Component
::CurDir
=> OsStr
::new("."),
561 Component
::ParentDir
=> OsStr
::new(".."),
562 Component
::Normal(path
) => path
,
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl<'a
> AsRef
<OsStr
> for Component
<'a
> {
569 fn as_ref(&self) -> &OsStr
{
574 /// An interator over the [`Component`]s of a [`Path`].
576 /// This `struct` is created by the [`components`] method on [`Path`].
577 /// See its documentation for more.
582 /// use std::path::Path;
584 /// let path = Path::new("/tmp/foo/bar.txt");
586 /// for component in path.components() {
587 /// println!("{:?}", component);
591 /// [`Component`]: enum.Component.html
592 /// [`components`]: struct.Path.html#method.components
593 /// [`Path`]: struct.Path.html
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub struct Components
<'a
> {
597 // The path left to parse components from
600 // The prefix as it was originally parsed, if any
601 prefix
: Option
<Prefix
<'a
>>,
603 // true if path *physically* has a root separator; for most Windows
604 // prefixes, it may have a "logical" rootseparator for the purposes of
605 // normalization, e.g. \\server\share == \\server\share\.
606 has_physical_root
: bool
,
608 // The iterator is double-ended, and these two states keep track of what has
609 // been produced from either end
614 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
616 /// This `struct` is created by the [`iter`] method on [`Path`].
617 /// See its documentation for more.
619 /// [`Component`]: enum.Component.html
620 /// [`iter`]: struct.Path.html#method.iter
621 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
622 /// [`Path`]: struct.Path.html
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub struct Iter
<'a
> {
626 inner
: Components
<'a
>,
629 #[stable(feature = "path_components_debug", since = "1.13.0")]
630 impl<'a
> fmt
::Debug
for Components
<'a
> {
631 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
632 struct DebugHelper
<'a
>(&'a Path
);
634 impl<'a
> fmt
::Debug
for DebugHelper
<'a
> {
635 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
637 .entries(self.0.components())
642 f
.debug_tuple("Components")
643 .field(&DebugHelper(self.as_path()))
648 impl<'a
> Components
<'a
> {
649 // how long is the prefix, if any?
651 fn prefix_len(&self) -> usize {
652 self.prefix
.as_ref().map(Prefix
::len
).unwrap_or(0)
656 fn prefix_verbatim(&self) -> bool
{
657 self.prefix
.as_ref().map(Prefix
::is_verbatim
).unwrap_or(false)
660 /// how much of the prefix is left from the point of view of iteration?
662 fn prefix_remaining(&self) -> usize {
663 if self.front
== State
::Prefix
{
670 // Given the iteration so far, how much of the pre-State::Body path is left?
672 fn len_before_body(&self) -> usize {
673 let root
= if self.front
<= State
::StartDir
&& self.has_physical_root
{
678 let cur_dir
= if self.front
<= State
::StartDir
&& self.include_cur_dir() {
683 self.prefix_remaining() + root
+ cur_dir
686 // is the iteration complete?
688 fn finished(&self) -> bool
{
689 self.front
== State
::Done
|| self.back
== State
::Done
|| self.front
> self.back
693 fn is_sep_byte(&self, b
: u8) -> bool
{
694 if self.prefix_verbatim() {
701 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
706 /// use std::path::Path;
708 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
709 /// components.next();
710 /// components.next();
712 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn as_path(&self) -> &'a Path
{
716 let mut comps
= self.clone();
717 if comps
.front
== State
::Body
{
720 if comps
.back
== State
::Body
{
723 unsafe { Path::from_u8_slice(comps.path) }
726 /// Is the *original* path rooted?
727 fn has_root(&self) -> bool
{
728 if self.has_physical_root
{
731 if let Some(p
) = self.prefix
{
732 if p
.has_implicit_root() {
739 /// Should the normalized path include a leading . ?
740 fn include_cur_dir(&self) -> bool
{
744 let mut iter
= self.path
[self.prefix_len()..].iter();
745 match (iter
.next(), iter
.next()) {
746 (Some(&b'
.'
), None
) => true,
747 (Some(&b'
.'
), Some(&b
)) => self.is_sep_byte(b
),
752 // parse a given byte sequence into the corresponding path component
753 fn parse_single_component
<'b
>(&self, comp
: &'b
[u8]) -> Option
<Component
<'b
>> {
755 b
"." if self.prefix_verbatim() => Some(Component
::CurDir
),
756 b
"." => None
, // . components are normalized away, except at
757 // the beginning of a path, which is treated
758 // separately via `include_cur_dir`
759 b
".." => Some(Component
::ParentDir
),
761 _
=> Some(Component
::Normal(unsafe { u8_slice_as_os_str(comp) }
)),
765 // parse a component from the left, saying how many bytes to consume to
766 // remove the component
767 fn parse_next_component(&self) -> (usize, Option
<Component
<'a
>>) {
768 debug_assert
!(self.front
== State
::Body
);
769 let (extra
, comp
) = match self.path
.iter().position(|b
| self.is_sep_byte(*b
)) {
770 None
=> (0, self.path
),
771 Some(i
) => (1, &self.path
[..i
]),
773 (comp
.len() + extra
, self.parse_single_component(comp
))
776 // parse a component from the right, saying how many bytes to consume to
777 // remove the component
778 fn parse_next_component_back(&self) -> (usize, Option
<Component
<'a
>>) {
779 debug_assert
!(self.back
== State
::Body
);
780 let start
= self.len_before_body();
781 let (extra
, comp
) = match self.path
[start
..].iter().rposition(|b
| self.is_sep_byte(*b
)) {
782 None
=> (0, &self.path
[start
..]),
783 Some(i
) => (1, &self.path
[start
+ i
+ 1..]),
785 (comp
.len() + extra
, self.parse_single_component(comp
))
788 // trim away repeated separators (i.e. empty components) on the left
789 fn trim_left(&mut self) {
790 while !self.path
.is_empty() {
791 let (size
, comp
) = self.parse_next_component();
795 self.path
= &self.path
[size
..];
800 // trim away repeated separators (i.e. empty components) on the right
801 fn trim_right(&mut self) {
802 while self.path
.len() > self.len_before_body() {
803 let (size
, comp
) = self.parse_next_component_back();
807 self.path
= &self.path
[..self.path
.len() - size
];
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl<'a
> AsRef
<Path
> for Components
<'a
> {
815 fn as_ref(&self) -> &Path
{
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a
> AsRef
<OsStr
> for Components
<'a
> {
822 fn as_ref(&self) -> &OsStr
{
823 self.as_path().as_os_str()
827 #[stable(feature = "path_iter_debug", since = "1.13.0")]
828 impl<'a
> fmt
::Debug
for Iter
<'a
> {
829 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
830 struct DebugHelper
<'a
>(&'a Path
);
832 impl<'a
> fmt
::Debug
for DebugHelper
<'a
> {
833 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
835 .entries(self.0.iter
())
840 f
.debug_tuple("Iter")
841 .field(&DebugHelper(self.as_path()))
847 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
852 /// use std::path::Path;
854 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
858 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub fn as_path(&self) -> &'a Path
{
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a
> AsRef
<Path
> for Iter
<'a
> {
868 fn as_ref(&self) -> &Path
{
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a
> AsRef
<OsStr
> for Iter
<'a
> {
875 fn as_ref(&self) -> &OsStr
{
876 self.as_path().as_os_str()
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<'a
> Iterator
for Iter
<'a
> {
882 type Item
= &'a OsStr
;
884 fn next(&mut self) -> Option
<&'a OsStr
> {
885 self.inner
.next().map(Component
::as_os_str
)
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<'a
> DoubleEndedIterator
for Iter
<'a
> {
891 fn next_back(&mut self) -> Option
<&'a OsStr
> {
892 self.inner
.next_back().map(Component
::as_os_str
)
896 #[unstable(feature = "fused", issue = "35602")]
897 impl<'a
> FusedIterator
for Iter
<'a
> {}
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<'a
> Iterator
for Components
<'a
> {
901 type Item
= Component
<'a
>;
903 fn next(&mut self) -> Option
<Component
<'a
>> {
904 while !self.finished() {
906 State
::Prefix
if self.prefix_len() > 0 => {
907 self.front
= State
::StartDir
;
908 debug_assert
!(self.prefix_len() <= self.path
.len());
909 let raw
= &self.path
[..self.prefix_len()];
910 self.path
= &self.path
[self.prefix_len()..];
911 return Some(Component
::Prefix(PrefixComponent
{
912 raw
: unsafe { u8_slice_as_os_str(raw) }
,
913 parsed
: self.prefix
.unwrap(),
917 self.front
= State
::StartDir
;
920 self.front
= State
::Body
;
921 if self.has_physical_root
{
922 debug_assert
!(!self.path
.is_empty());
923 self.path
= &self.path
[1..];
924 return Some(Component
::RootDir
);
925 } else if let Some(p
) = self.prefix
{
926 if p
.has_implicit_root() && !p
.is_verbatim() {
927 return Some(Component
::RootDir
);
929 } else if self.include_cur_dir() {
930 debug_assert
!(!self.path
.is_empty());
931 self.path
= &self.path
[1..];
932 return Some(Component
::CurDir
);
935 State
::Body
if !self.path
.is_empty() => {
936 let (size
, comp
) = self.parse_next_component();
937 self.path
= &self.path
[size
..];
943 self.front
= State
::Done
;
945 State
::Done
=> unreachable
!(),
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a
> DoubleEndedIterator
for Components
<'a
> {
954 fn next_back(&mut self) -> Option
<Component
<'a
>> {
955 while !self.finished() {
957 State
::Body
if self.path
.len() > self.len_before_body() => {
958 let (size
, comp
) = self.parse_next_component_back();
959 self.path
= &self.path
[..self.path
.len() - size
];
965 self.back
= State
::StartDir
;
968 self.back
= State
::Prefix
;
969 if self.has_physical_root
{
970 self.path
= &self.path
[..self.path
.len() - 1];
971 return Some(Component
::RootDir
);
972 } else if let Some(p
) = self.prefix
{
973 if p
.has_implicit_root() && !p
.is_verbatim() {
974 return Some(Component
::RootDir
);
976 } else if self.include_cur_dir() {
977 self.path
= &self.path
[..self.path
.len() - 1];
978 return Some(Component
::CurDir
);
981 State
::Prefix
if self.prefix_len() > 0 => {
982 self.back
= State
::Done
;
983 return Some(Component
::Prefix(PrefixComponent
{
984 raw
: unsafe { u8_slice_as_os_str(self.path) }
,
985 parsed
: self.prefix
.unwrap(),
989 self.back
= State
::Done
;
992 State
::Done
=> unreachable
!(),
999 #[unstable(feature = "fused", issue = "35602")]
1000 impl<'a
> FusedIterator
for Components
<'a
> {}
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<'a
> cmp
::PartialEq
for Components
<'a
> {
1004 fn eq(&self, other
: &Components
<'a
>) -> bool
{
1005 Iterator
::eq(self.clone(), other
.clone())
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl<'a
> cmp
::Eq
for Components
<'a
> {}
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<'a
> cmp
::PartialOrd
for Components
<'a
> {
1014 fn partial_cmp(&self, other
: &Components
<'a
>) -> Option
<cmp
::Ordering
> {
1015 Iterator
::partial_cmp(self.clone(), other
.clone())
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl<'a
> cmp
::Ord
for Components
<'a
> {
1021 fn cmp(&self, other
: &Components
<'a
>) -> cmp
::Ordering
{
1022 Iterator
::cmp(self.clone(), other
.clone())
1026 ////////////////////////////////////////////////////////////////////////////////
1027 // Basic types and traits
1028 ////////////////////////////////////////////////////////////////////////////////
1030 /// An owned, mutable path (akin to [`String`]).
1032 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1033 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1034 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1036 /// [`String`]: ../string/struct.String.html
1037 /// [`Path`]: struct.Path.html
1038 /// [`push`]: struct.PathBuf.html#method.push
1039 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1040 /// [`Deref`]: ../ops/trait.Deref.html
1042 /// More details about the overall approach can be found in
1043 /// the [module documentation](index.html).
1047 /// You can use [`push`] to build up a `PathBuf` from
1051 /// use std::path::PathBuf;
1053 /// let mut path = PathBuf::new();
1055 /// path.push(r"C:\");
1056 /// path.push("windows");
1057 /// path.push("system32");
1059 /// path.set_extension("dll");
1062 /// However, [`push`] is best used for dynamic situations. This is a better way
1063 /// to do this when you know all of the components ahead of time:
1066 /// use std::path::PathBuf;
1068 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1071 /// We can still do better than this! Since these are all strings, we can use
1075 /// use std::path::PathBuf;
1077 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1080 /// Which method works best depends on what kind of situation you're in.
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 pub struct PathBuf
{
1088 fn as_mut_vec(&mut self) -> &mut Vec
<u8> {
1089 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1092 /// Allocates an empty `PathBuf`.
1097 /// use std::path::PathBuf;
1099 /// let path = PathBuf::new();
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 pub fn new() -> PathBuf
{
1103 PathBuf { inner: OsString::new() }
1106 /// Coerces to a [`Path`] slice.
1108 /// [`Path`]: struct.Path.html
1113 /// use std::path::{Path, PathBuf};
1115 /// let p = PathBuf::from("/test");
1116 /// assert_eq!(Path::new("/test"), p.as_path());
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub fn as_path(&self) -> &Path
{
1123 /// Extends `self` with `path`.
1125 /// If `path` is absolute, it replaces the current path.
1129 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1130 /// replaces everything except for the prefix (if any) of `self`.
1131 /// * if `path` has a prefix but no root, it replaces `self`.
1135 /// Pushing a relative path extends the existing path:
1138 /// use std::path::PathBuf;
1140 /// let mut path = PathBuf::from("/tmp");
1141 /// path.push("file.bk");
1142 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1145 /// Pushing an absolute path replaces the existing path:
1148 /// use std::path::PathBuf;
1150 /// let mut path = PathBuf::from("/tmp");
1151 /// path.push("/etc");
1152 /// assert_eq!(path, PathBuf::from("/etc"));
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn push
<P
: AsRef
<Path
>>(&mut self, path
: P
) {
1156 self._push(path
.as_ref())
1159 fn _push(&mut self, path
: &Path
) {
1160 // in general, a separator is needed if the rightmost byte is not a separator
1161 let mut need_sep
= self.as_mut_vec().last().map(|c
| !is_sep_byte(*c
)).unwrap_or(false);
1163 // in the special case of `C:` on Windows, do *not* add a separator
1165 let comps
= self.components();
1166 if comps
.prefix_len() > 0 && comps
.prefix_len() == comps
.path
.len() &&
1167 comps
.prefix
.unwrap().is_drive() {
1172 // absolute `path` replaces `self`
1173 if path
.is_absolute() || path
.prefix().is_some() {
1174 self.as_mut_vec().truncate(0);
1176 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1177 } else if path
.has_root() {
1178 let prefix_len
= self.components().prefix_remaining();
1179 self.as_mut_vec().truncate(prefix_len
);
1181 // `path` is a pure relative path
1182 } else if need_sep
{
1183 self.inner
.push(MAIN_SEP_STR
);
1186 self.inner
.push(path
);
1189 /// Truncates `self` to [`self.parent`].
1191 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1192 /// Otherwise, returns `true`.
1194 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1195 /// [`self.parent`]: struct.PathBuf.html#method.parent
1196 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1201 /// use std::path::{Path, PathBuf};
1203 /// let mut p = PathBuf::from("/test/test.rs");
1206 /// assert_eq!(Path::new("/test"), p);
1208 /// assert_eq!(Path::new("/"), p);
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub fn pop(&mut self) -> bool
{
1212 match self.parent().map(|p
| p
.as_u8_slice().len()) {
1214 self.as_mut_vec().truncate(len
);
1221 /// Updates [`self.file_name`] to `file_name`.
1223 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1226 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1227 /// `file_name`. The new path will be a sibling of the original path.
1228 /// (That is, it will have the same parent.)
1230 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1231 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1232 /// [`pop`]: struct.PathBuf.html#method.pop
1237 /// use std::path::PathBuf;
1239 /// let mut buf = PathBuf::from("/");
1240 /// assert!(buf.file_name() == None);
1241 /// buf.set_file_name("bar");
1242 /// assert!(buf == PathBuf::from("/bar"));
1243 /// assert!(buf.file_name().is_some());
1244 /// buf.set_file_name("baz.txt");
1245 /// assert!(buf == PathBuf::from("/baz.txt"));
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 pub fn set_file_name
<S
: AsRef
<OsStr
>>(&mut self, file_name
: S
) {
1249 self._set_file_name(file_name
.as_ref())
1252 fn _set_file_name(&mut self, file_name
: &OsStr
) {
1253 if self.file_name().is_some() {
1254 let popped
= self.pop();
1255 debug_assert
!(popped
);
1257 self.push(file_name
);
1260 /// Updates [`self.extension`] to `extension`.
1262 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1263 /// returns `true` and updates the extension otherwise.
1265 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1268 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1269 /// [`self.extension`]: struct.PathBuf.html#method.extension
1270 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1275 /// use std::path::{Path, PathBuf};
1277 /// let mut p = PathBuf::from("/feel/the");
1279 /// p.set_extension("force");
1280 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1282 /// p.set_extension("dark_side");
1283 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub fn set_extension
<S
: AsRef
<OsStr
>>(&mut self, extension
: S
) -> bool
{
1287 self._set_extension(extension
.as_ref())
1290 fn _set_extension(&mut self, extension
: &OsStr
) -> bool
{
1291 if self.file_name().is_none() {
1295 let mut stem
= match self.file_stem() {
1296 Some(stem
) => stem
.to_os_string(),
1297 None
=> OsString
::new(),
1300 if !os_str_as_u8_slice(extension
).is_empty() {
1302 stem
.push(extension
);
1304 self.set_file_name(&stem
);
1309 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1311 /// [`OsString`]: ../ffi/struct.OsString.html
1316 /// use std::path::PathBuf;
1318 /// let p = PathBuf::from("/the/head");
1319 /// let os_str = p.into_os_string();
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub fn into_os_string(self) -> OsString
{
1326 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1328 /// [`Box`]: ../../std/boxed/struct.Box.html
1329 /// [`Path`]: struct.Path.html
1330 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1331 pub fn into_boxed_path(self) -> Box
<Path
> {
1332 unsafe { mem::transmute(self.inner.into_boxed_os_str()) }
1336 #[stable(feature = "box_from_path", since = "1.17.0")]
1337 impl<'a
> From
<&'a Path
> for Box
<Path
> {
1338 fn from(path
: &'a Path
) -> Box
<Path
> {
1339 let boxed
: Box
<OsStr
> = path
.inner
.into();
1340 unsafe { mem::transmute(boxed) }
1344 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1345 impl From
<Box
<Path
>> for PathBuf
{
1346 fn from(boxed
: Box
<Path
>) -> PathBuf
{
1347 boxed
.into_path_buf()
1351 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1352 impl From
<PathBuf
> for Box
<Path
> {
1353 fn from(p
: PathBuf
) -> Box
<Path
> {
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<'a
, T
: ?Sized
+ AsRef
<OsStr
>> From
<&'a T
> for PathBuf
{
1360 fn from(s
: &'a T
) -> PathBuf
{
1361 PathBuf
::from(s
.as_ref().to_os_string())
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl From
<OsString
> for PathBuf
{
1367 fn from(s
: OsString
) -> PathBuf
{
1368 PathBuf { inner: s }
1372 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1373 impl From
<PathBuf
> for OsString
{
1374 fn from(path_buf
: PathBuf
) -> OsString
{
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl From
<String
> for PathBuf
{
1381 fn from(s
: String
) -> PathBuf
{
1382 PathBuf
::from(OsString
::from(s
))
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl<P
: AsRef
<Path
>> iter
::FromIterator
<P
> for PathBuf
{
1388 fn from_iter
<I
: IntoIterator
<Item
= P
>>(iter
: I
) -> PathBuf
{
1389 let mut buf
= PathBuf
::new();
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl<P
: AsRef
<Path
>> iter
::Extend
<P
> for PathBuf
{
1397 fn extend
<I
: IntoIterator
<Item
= P
>>(&mut self, iter
: I
) {
1399 self.push(p
.as_ref())
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl fmt
::Debug
for PathBuf
{
1406 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
1407 fmt
::Debug
::fmt(&**self, formatter
)
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl ops
::Deref
for PathBuf
{
1415 fn deref(&self) -> &Path
{
1416 Path
::new(&self.inner
)
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl Borrow
<Path
> for PathBuf
{
1422 fn borrow(&self) -> &Path
{
1427 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1428 impl Default
for PathBuf
{
1429 fn default() -> Self {
1434 #[stable(feature = "cow_from_path", since = "1.6.0")]
1435 impl<'a
> From
<&'a Path
> for Cow
<'a
, Path
> {
1437 fn from(s
: &'a Path
) -> Cow
<'a
, Path
> {
1442 #[stable(feature = "cow_from_path", since = "1.6.0")]
1443 impl<'a
> From
<PathBuf
> for Cow
<'a
, Path
> {
1445 fn from(s
: PathBuf
) -> Cow
<'a
, Path
> {
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 impl ToOwned
for Path
{
1452 type Owned
= PathBuf
;
1453 fn to_owned(&self) -> PathBuf
{
1456 fn clone_into(&self, target
: &mut PathBuf
) {
1457 self.inner
.clone_into(&mut target
.inner
);
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl cmp
::PartialEq
for PathBuf
{
1463 fn eq(&self, other
: &PathBuf
) -> bool
{
1464 self.components() == other
.components()
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl Hash
for PathBuf
{
1470 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
1471 self.as_path().hash(h
)
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl cmp
::Eq
for PathBuf {}
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl cmp
::PartialOrd
for PathBuf
{
1480 fn partial_cmp(&self, other
: &PathBuf
) -> Option
<cmp
::Ordering
> {
1481 self.components().partial_cmp(other
.components())
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl cmp
::Ord
for PathBuf
{
1487 fn cmp(&self, other
: &PathBuf
) -> cmp
::Ordering
{
1488 self.components().cmp(other
.components())
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl AsRef
<OsStr
> for PathBuf
{
1494 fn as_ref(&self) -> &OsStr
{
1499 /// A slice of a path (akin to [`str`]).
1501 /// This type supports a number of operations for inspecting a path, including
1502 /// breaking the path into its components (separated by `/` on Unix and by either
1503 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1504 /// is absolute, and so on.
1506 /// This is an *unsized* type, meaning that it must always be used behind a
1507 /// pointer like `&` or [`Box`]. For an owned version of this type,
1508 /// see [`PathBuf`].
1510 /// [`str`]: ../primitive.str.html
1511 /// [`Box`]: ../boxed/struct.Box.html
1512 /// [`PathBuf`]: struct.PathBuf.html
1514 /// More details about the overall approach can be found in
1515 /// the [module documentation](index.html).
1520 /// use std::path::Path;
1521 /// use std::ffi::OsStr;
1523 /// // Note: this example does work on Windows
1524 /// let path = Path::new("./foo/bar.txt");
1526 /// let parent = path.parent();
1527 /// assert_eq!(parent, Some(Path::new("./foo")));
1529 /// let file_stem = path.file_stem();
1530 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1532 /// let extension = path.extension();
1533 /// assert_eq!(extension, Some(OsStr::new("txt")));
1535 #[stable(feature = "rust1", since = "1.0.0")]
1540 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1543 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1544 /// See its documentation for more.
1546 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1547 /// [`Path`]: struct.Path.html
1548 #[derive(Debug, Clone, PartialEq, Eq)]
1549 #[stable(since = "1.7.0", feature = "strip_prefix")]
1550 pub struct StripPrefixError(());
1553 // The following (private!) function allows construction of a path from a u8
1554 // slice, which is only safe when it is known to follow the OsStr encoding.
1555 unsafe fn from_u8_slice(s
: &[u8]) -> &Path
{
1556 Path
::new(u8_slice_as_os_str(s
))
1558 // The following (private!) function reveals the byte encoding used for OsStr.
1559 fn as_u8_slice(&self) -> &[u8] {
1560 os_str_as_u8_slice(&self.inner
)
1563 /// Directly wraps a string slice as a `Path` slice.
1565 /// This is a cost-free conversion.
1570 /// use std::path::Path;
1572 /// Path::new("foo.txt");
1575 /// You can create `Path`s from `String`s, or even other `Path`s:
1578 /// use std::path::Path;
1580 /// let string = String::from("foo.txt");
1581 /// let from_string = Path::new(&string);
1582 /// let from_path = Path::new(&from_string);
1583 /// assert_eq!(from_string, from_path);
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 pub fn new
<S
: AsRef
<OsStr
> + ?Sized
>(s
: &S
) -> &Path
{
1587 unsafe { mem::transmute(s.as_ref()) }
1590 /// Yields the underlying [`OsStr`] slice.
1592 /// [`OsStr`]: ../ffi/struct.OsStr.html
1597 /// use std::path::Path;
1599 /// let os_str = Path::new("foo.txt").as_os_str();
1600 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 pub fn as_os_str(&self) -> &OsStr
{
1607 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1609 /// This conversion may entail doing a check for UTF-8 validity.
1611 /// [`&str`]: ../primitive.str.html
1616 /// use std::path::Path;
1618 /// let path = Path::new("foo.txt");
1619 /// assert_eq!(path.to_str(), Some("foo.txt"));
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 pub fn to_str(&self) -> Option
<&str> {
1626 /// Converts a `Path` to a [`Cow<str>`].
1628 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1630 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1634 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1637 /// use std::path::Path;
1639 /// let path = Path::new("foo.txt");
1640 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1643 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1644 /// have returned `"fo�.txt"`.
1645 #[stable(feature = "rust1", since = "1.0.0")]
1646 pub fn to_string_lossy(&self) -> Cow
<str> {
1647 self.inner
.to_string_lossy()
1650 /// Converts a `Path` to an owned [`PathBuf`].
1652 /// [`PathBuf`]: struct.PathBuf.html
1657 /// use std::path::Path;
1659 /// let path_buf = Path::new("foo.txt").to_path_buf();
1660 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 pub fn to_path_buf(&self) -> PathBuf
{
1664 PathBuf
::from(self.inner
.to_os_string())
1667 /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1668 /// the current directory.
1670 /// * On Unix, a path is absolute if it starts with the root, so
1671 /// `is_absolute` and [`has_root`] are equivalent.
1673 /// * On Windows, a path is absolute if it has a prefix and starts with the
1674 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1679 /// use std::path::Path;
1681 /// assert!(!Path::new("foo.txt").is_absolute());
1684 /// [`has_root`]: #method.has_root
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 #[allow(deprecated)]
1687 pub fn is_absolute(&self) -> bool
{
1688 // FIXME: Remove target_os = "redox" and allow Redox prefixes
1689 self.has_root() && (cfg
!(unix
) || cfg
!(target_os
= "redox") || self.prefix().is_some())
1692 /// Returns `true` if the `Path` is relative, i.e. not absolute.
1694 /// See [`is_absolute`]'s documentation for more details.
1699 /// use std::path::Path;
1701 /// assert!(Path::new("foo.txt").is_relative());
1704 /// [`is_absolute`]: #method.is_absolute
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn is_relative(&self) -> bool
{
1710 fn prefix(&self) -> Option
<Prefix
> {
1711 self.components().prefix
1714 /// Returns `true` if the `Path` has a root.
1716 /// * On Unix, a path has a root if it begins with `/`.
1718 /// * On Windows, a path has a root if it:
1719 /// * has no prefix and begins with a separator, e.g. `\\windows`
1720 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1721 /// * has any non-disk prefix, e.g. `\\server\share`
1726 /// use std::path::Path;
1728 /// assert!(Path::new("/etc/passwd").has_root());
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 pub fn has_root(&self) -> bool
{
1732 self.components().has_root()
1735 /// Returns the `Path` without its final component, if there is one.
1737 /// Returns [`None`] if the path terminates in a root or prefix.
1739 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1744 /// use std::path::Path;
1746 /// let path = Path::new("/foo/bar");
1747 /// let parent = path.parent().unwrap();
1748 /// assert_eq!(parent, Path::new("/foo"));
1750 /// let grand_parent = parent.parent().unwrap();
1751 /// assert_eq!(grand_parent, Path::new("/"));
1752 /// assert_eq!(grand_parent.parent(), None);
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 pub fn parent(&self) -> Option
<&Path
> {
1756 let mut comps
= self.components();
1757 let comp
= comps
.next_back();
1760 Component
::Normal(_
) |
1762 Component
::ParentDir
=> Some(comps
.as_path()),
1768 /// Returns the final component of the `Path`, if there is one.
1770 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1771 /// is the directory name.
1773 /// Returns [`None`] If the path terminates in `..`.
1775 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1780 /// use std::path::Path;
1781 /// use std::ffi::OsStr;
1783 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1784 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1785 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1786 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1787 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1788 /// assert_eq!(None, Path::new("/").file_name());
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 pub fn file_name(&self) -> Option
<&OsStr
> {
1792 self.components().next_back().and_then(|p
| {
1794 Component
::Normal(p
) => Some(p
.as_ref()),
1800 /// Returns a path that, when joined onto `base`, yields `self`.
1804 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1805 /// returns `false`), returns [`Err`].
1807 /// [`starts_with`]: #method.starts_with
1808 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1813 /// use std::path::Path;
1815 /// let path = Path::new("/test/haha/foo.txt");
1817 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1818 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1819 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1821 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1822 pub fn strip_prefix
<'a
, P
: ?Sized
>(&'a
self, base
: &'a P
)
1823 -> Result
<&'a Path
, StripPrefixError
>
1824 where P
: AsRef
<Path
>
1826 self._strip_prefix(base
.as_ref())
1829 fn _strip_prefix
<'a
>(&'a
self, base
: &'a Path
)
1830 -> Result
<&'a Path
, StripPrefixError
> {
1831 iter_after(self.components(), base
.components())
1832 .map(|c
| c
.as_path())
1833 .ok_or(StripPrefixError(()))
1836 /// Determines whether `base` is a prefix of `self`.
1838 /// Only considers whole path components to match.
1843 /// use std::path::Path;
1845 /// let path = Path::new("/etc/passwd");
1847 /// assert!(path.starts_with("/etc"));
1849 /// assert!(!path.starts_with("/e"));
1851 #[stable(feature = "rust1", since = "1.0.0")]
1852 pub fn starts_with
<P
: AsRef
<Path
>>(&self, base
: P
) -> bool
{
1853 self._starts_with(base
.as_ref())
1856 fn _starts_with(&self, base
: &Path
) -> bool
{
1857 iter_after(self.components(), base
.components()).is_some()
1860 /// Determines whether `child` is a suffix of `self`.
1862 /// Only considers whole path components to match.
1867 /// use std::path::Path;
1869 /// let path = Path::new("/etc/passwd");
1871 /// assert!(path.ends_with("passwd"));
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub fn ends_with
<P
: AsRef
<Path
>>(&self, child
: P
) -> bool
{
1875 self._ends_with(child
.as_ref())
1878 fn _ends_with(&self, child
: &Path
) -> bool
{
1879 iter_after(self.components().rev(), child
.components().rev()).is_some()
1882 /// Extracts the stem (non-extension) portion of [`self.file_name`].
1884 /// [`self.file_name`]: struct.Path.html#method.file_name
1888 /// * [`None`], if there is no file name;
1889 /// * The entire file name if there is no embedded `.`;
1890 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1891 /// * Otherwise, the portion of the file name before the final `.`
1893 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1898 /// use std::path::Path;
1900 /// let path = Path::new("foo.rs");
1902 /// assert_eq!("foo", path.file_stem().unwrap());
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn file_stem(&self) -> Option
<&OsStr
> {
1906 self.file_name().map(split_file_at_dot
).and_then(|(before
, after
)| before
.or(after
))
1909 /// Extracts the extension of [`self.file_name`], if possible.
1911 /// The extension is:
1913 /// * [`None`], if there is no file name;
1914 /// * [`None`], if there is no embedded `.`;
1915 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1916 /// * Otherwise, the portion of the file name after the final `.`
1918 /// [`self.file_name`]: struct.Path.html#method.file_name
1919 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1924 /// use std::path::Path;
1926 /// let path = Path::new("foo.rs");
1928 /// assert_eq!("rs", path.extension().unwrap());
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 pub fn extension(&self) -> Option
<&OsStr
> {
1932 self.file_name().map(split_file_at_dot
).and_then(|(before
, after
)| before
.and(after
))
1935 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1937 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1939 /// [`PathBuf`]: struct.PathBuf.html
1940 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1945 /// use std::path::{Path, PathBuf};
1947 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 pub fn join
<P
: AsRef
<Path
>>(&self, path
: P
) -> PathBuf
{
1951 self._join(path
.as_ref())
1954 fn _join(&self, path
: &Path
) -> PathBuf
{
1955 let mut buf
= self.to_path_buf();
1960 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1962 /// See [`PathBuf::set_file_name`] for more details.
1964 /// [`PathBuf`]: struct.PathBuf.html
1965 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1970 /// use std::path::{Path, PathBuf};
1972 /// let path = Path::new("/tmp/foo.txt");
1973 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1975 /// let path = Path::new("/tmp");
1976 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
1978 #[stable(feature = "rust1", since = "1.0.0")]
1979 pub fn with_file_name
<S
: AsRef
<OsStr
>>(&self, file_name
: S
) -> PathBuf
{
1980 self._with_file_name(file_name
.as_ref())
1983 fn _with_file_name(&self, file_name
: &OsStr
) -> PathBuf
{
1984 let mut buf
= self.to_path_buf();
1985 buf
.set_file_name(file_name
);
1989 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1991 /// See [`PathBuf::set_extension`] for more details.
1993 /// [`PathBuf`]: struct.PathBuf.html
1994 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1999 /// use std::path::{Path, PathBuf};
2001 /// let path = Path::new("foo.rs");
2002 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 pub fn with_extension
<S
: AsRef
<OsStr
>>(&self, extension
: S
) -> PathBuf
{
2006 self._with_extension(extension
.as_ref())
2009 fn _with_extension(&self, extension
: &OsStr
) -> PathBuf
{
2010 let mut buf
= self.to_path_buf();
2011 buf
.set_extension(extension
);
2015 /// Produces an iterator over the [`Component`]s of the path.
2017 /// When parsing the path, there is a small amount of normalization:
2019 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2020 /// `a` and `b` as components.
2022 /// * Occurences of `.` are normalized away, except if they are at the
2023 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2024 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2025 /// an additional [`CurDir`] component.
2027 /// Note that no other normalization takes place; in particular, `a/c`
2028 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2029 /// is a symbolic link (so its parent isn't `a`).
2034 /// use std::path::{Path, Component};
2035 /// use std::ffi::OsStr;
2037 /// let mut components = Path::new("/tmp/foo.txt").components();
2039 /// assert_eq!(components.next(), Some(Component::RootDir));
2040 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2041 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2042 /// assert_eq!(components.next(), None)
2045 /// [`Component`]: enum.Component.html
2046 /// [`CurDir`]: enum.Component.html#variant.CurDir
2047 #[stable(feature = "rust1", since = "1.0.0")]
2048 pub fn components(&self) -> Components
{
2049 let prefix
= parse_prefix(self.as_os_str());
2051 path
: self.as_u8_slice(),
2053 has_physical_root
: has_physical_root(self.as_u8_slice(), prefix
),
2054 front
: State
::Prefix
,
2059 /// Produces an iterator over the path's components viewed as [`OsStr`]
2062 /// For more information about the particulars of how the path is separated
2063 /// into components, see [`components`].
2065 /// [`components`]: #method.components
2066 /// [`OsStr`]: ../ffi/struct.OsStr.html
2071 /// use std::path::{self, Path};
2072 /// use std::ffi::OsStr;
2074 /// let mut it = Path::new("/tmp/foo.txt").iter();
2075 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2076 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2077 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2078 /// assert_eq!(it.next(), None)
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub fn iter(&self) -> Iter
{
2082 Iter { inner: self.components() }
2085 /// Returns an object that implements [`Display`] for safely printing paths
2086 /// that may contain non-Unicode data.
2088 /// [`Display`]: ../fmt/trait.Display.html
2093 /// use std::path::Path;
2095 /// let path = Path::new("/tmp/foo.rs");
2097 /// println!("{}", path.display());
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 pub fn display(&self) -> Display
{
2101 Display { path: self }
2104 /// Queries the file system to get information about a file, directory, etc.
2106 /// This function will traverse symbolic links to query information about the
2107 /// destination file.
2109 /// This is an alias to [`fs::metadata`].
2111 /// [`fs::metadata`]: ../fs/fn.metadata.html
2116 /// use std::path::Path;
2118 /// let path = Path::new("/Minas/tirith");
2119 /// let metadata = path.metadata().expect("metadata call failed");
2120 /// println!("{:?}", metadata.file_type());
2122 #[stable(feature = "path_ext", since = "1.5.0")]
2123 pub fn metadata(&self) -> io
::Result
<fs
::Metadata
> {
2127 /// Queries the metadata about a file without following symlinks.
2129 /// This is an alias to [`fs::symlink_metadata`].
2131 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2136 /// use std::path::Path;
2138 /// let path = Path::new("/Minas/tirith");
2139 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2140 /// println!("{:?}", metadata.file_type());
2142 #[stable(feature = "path_ext", since = "1.5.0")]
2143 pub fn symlink_metadata(&self) -> io
::Result
<fs
::Metadata
> {
2144 fs
::symlink_metadata(self)
2147 /// Returns the canonical form of the path with all intermediate components
2148 /// normalized and symbolic links resolved.
2150 /// This is an alias to [`fs::canonicalize`].
2152 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2157 /// use std::path::{Path, PathBuf};
2159 /// let path = Path::new("/foo/test/../test/bar.rs");
2160 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2162 #[stable(feature = "path_ext", since = "1.5.0")]
2163 pub fn canonicalize(&self) -> io
::Result
<PathBuf
> {
2164 fs
::canonicalize(self)
2167 /// Reads a symbolic link, returning the file that the link points to.
2169 /// This is an alias to [`fs::read_link`].
2171 /// [`fs::read_link`]: ../fs/fn.read_link.html
2176 /// use std::path::Path;
2178 /// let path = Path::new("/laputa/sky_castle.rs");
2179 /// let path_link = path.read_link().expect("read_link call failed");
2181 #[stable(feature = "path_ext", since = "1.5.0")]
2182 pub fn read_link(&self) -> io
::Result
<PathBuf
> {
2186 /// Returns an iterator over the entries within a directory.
2188 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2189 /// errors may be encountered after an iterator is initially constructed.
2191 /// This is an alias to [`fs::read_dir`].
2193 /// [`io::Result`]: ../io/type.Result.html
2194 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2195 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2200 /// use std::path::Path;
2202 /// let path = Path::new("/laputa");
2203 /// for entry in path.read_dir().expect("read_dir call failed") {
2204 /// if let Ok(entry) = entry {
2205 /// println!("{:?}", entry.path());
2209 #[stable(feature = "path_ext", since = "1.5.0")]
2210 pub fn read_dir(&self) -> io
::Result
<fs
::ReadDir
> {
2214 /// Returns whether the path points at an existing entity.
2216 /// This function will traverse symbolic links to query information about the
2217 /// destination file. In case of broken symbolic links this will return `false`.
2219 /// If you cannot access the directory containing the file, e.g. because of a
2220 /// permission error, this will return `false`.
2225 /// use std::path::Path;
2226 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2231 /// This is a convenience function that coerces errors to false. If you want to
2232 /// check errors, call [fs::metadata].
2234 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2235 #[stable(feature = "path_ext", since = "1.5.0")]
2236 pub fn exists(&self) -> bool
{
2237 fs
::metadata(self).is_ok()
2240 /// Returns whether the path is pointing at a regular file.
2242 /// This function will traverse symbolic links to query information about the
2243 /// destination file. In case of broken symbolic links this will return `false`.
2245 /// If you cannot access the directory containing the file, e.g. because of a
2246 /// permission error, this will return `false`.
2251 /// use std::path::Path;
2252 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2253 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2258 /// This is a convenience function that coerces errors to false. If you want to
2259 /// check errors, call [fs::metadata] and handle its Result. Then call
2260 /// [fs::Metadata::is_file] if it was Ok.
2262 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2263 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2264 #[stable(feature = "path_ext", since = "1.5.0")]
2265 pub fn is_file(&self) -> bool
{
2266 fs
::metadata(self).map(|m
| m
.is_file()).unwrap_or(false)
2269 /// Returns whether the path is pointing at a directory.
2271 /// This function will traverse symbolic links to query information about the
2272 /// destination file. In case of broken symbolic links this will return `false`.
2274 /// If you cannot access the directory containing the file, e.g. because of a
2275 /// permission error, this will return `false`.
2280 /// use std::path::Path;
2281 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2282 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2287 /// This is a convenience function that coerces errors to false. If you want to
2288 /// check errors, call [fs::metadata] and handle its Result. Then call
2289 /// [fs::Metadata::is_dir] if it was Ok.
2291 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2292 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2293 #[stable(feature = "path_ext", since = "1.5.0")]
2294 pub fn is_dir(&self) -> bool
{
2295 fs
::metadata(self).map(|m
| m
.is_dir()).unwrap_or(false)
2298 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2301 /// [`Box`]: ../../std/boxed/struct.Box.html
2302 /// [`PathBuf`]: struct.PathBuf.html
2303 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2304 pub fn into_path_buf(self: Box
<Path
>) -> PathBuf
{
2305 let inner
: Box
<OsStr
> = unsafe { mem::transmute(self) }
;
2306 PathBuf { inner: OsString::from(inner) }
2310 #[stable(feature = "rust1", since = "1.0.0")]
2311 impl AsRef
<OsStr
> for Path
{
2312 fn as_ref(&self) -> &OsStr
{
2317 #[stable(feature = "rust1", since = "1.0.0")]
2318 impl fmt
::Debug
for Path
{
2319 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
2320 fmt
::Debug
::fmt(&self.inner
, formatter
)
2324 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2326 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2327 /// [`Display`] trait in a way that mitigates that. It is created by the
2328 /// [`display`][`Path::display`] method on [`Path`].
2333 /// use std::path::Path;
2335 /// let path = Path::new("/tmp/foo.rs");
2337 /// println!("{}", path.display());
2340 /// [`Display`]: ../../std/fmt/trait.Display.html
2341 /// [`format!`]: ../../std/macro.format.html
2342 /// [`Path`]: struct.Path.html
2343 /// [`Path::display`]: struct.Path.html#method.display
2344 #[stable(feature = "rust1", since = "1.0.0")]
2345 pub struct Display
<'a
> {
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<'a
> fmt
::Debug
for Display
<'a
> {
2351 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2352 fmt
::Debug
::fmt(&self.path
, f
)
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl<'a
> fmt
::Display
for Display
<'a
> {
2358 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2359 self.path
.inner
.display(f
)
2363 #[stable(feature = "rust1", since = "1.0.0")]
2364 impl cmp
::PartialEq
for Path
{
2365 fn eq(&self, other
: &Path
) -> bool
{
2366 self.components().eq(other
.components())
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 impl Hash
for Path
{
2372 fn hash
<H
: Hasher
>(&self, h
: &mut H
) {
2373 for component
in self.components() {
2379 #[stable(feature = "rust1", since = "1.0.0")]
2380 impl cmp
::Eq
for Path {}
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 impl cmp
::PartialOrd
for Path
{
2384 fn partial_cmp(&self, other
: &Path
) -> Option
<cmp
::Ordering
> {
2385 self.components().partial_cmp(other
.components())
2389 #[stable(feature = "rust1", since = "1.0.0")]
2390 impl cmp
::Ord
for Path
{
2391 fn cmp(&self, other
: &Path
) -> cmp
::Ordering
{
2392 self.components().cmp(other
.components())
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 impl AsRef
<Path
> for Path
{
2398 fn as_ref(&self) -> &Path
{
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 impl AsRef
<Path
> for OsStr
{
2405 fn as_ref(&self) -> &Path
{
2410 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2411 impl<'a
> AsRef
<Path
> for Cow
<'a
, OsStr
> {
2412 fn as_ref(&self) -> &Path
{
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 impl AsRef
<Path
> for OsString
{
2419 fn as_ref(&self) -> &Path
{
2424 #[stable(feature = "rust1", since = "1.0.0")]
2425 impl AsRef
<Path
> for str {
2426 fn as_ref(&self) -> &Path
{
2431 #[stable(feature = "rust1", since = "1.0.0")]
2432 impl AsRef
<Path
> for String
{
2433 fn as_ref(&self) -> &Path
{
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl AsRef
<Path
> for PathBuf
{
2440 fn as_ref(&self) -> &Path
{
2445 #[stable(feature = "path_into_iter", since = "1.6.0")]
2446 impl<'a
> IntoIterator
for &'a PathBuf
{
2447 type Item
= &'a OsStr
;
2448 type IntoIter
= Iter
<'a
>;
2449 fn into_iter(self) -> Iter
<'a
> { self.iter() }
2452 #[stable(feature = "path_into_iter", since = "1.6.0")]
2453 impl<'a
> IntoIterator
for &'a Path
{
2454 type Item
= &'a OsStr
;
2455 type IntoIter
= Iter
<'a
>;
2456 fn into_iter(self) -> Iter
<'a
> { self.iter() }
2459 macro_rules
! impl_cmp
{
2460 ($lhs
:ty
, $rhs
: ty
) => {
2461 #[stable(feature = "partialeq_path", since = "1.6.0")]
2462 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
2464 fn eq(&self, other
: &$rhs
) -> bool { <Path as PartialEq>::eq(self, other) }
2467 #[stable(feature = "partialeq_path", since = "1.6.0")]
2468 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
2470 fn eq(&self, other
: &$lhs
) -> bool { <Path as PartialEq>::eq(self, other) }
2473 #[stable(feature = "cmp_path", since = "1.8.0")]
2474 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
2476 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
2477 <Path
as PartialOrd
>::partial_cmp(self, other
)
2481 #[stable(feature = "cmp_path", since = "1.8.0")]
2482 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
2484 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
2485 <Path
as PartialOrd
>::partial_cmp(self, other
)
2491 impl_cmp
!(PathBuf
, Path
);
2492 impl_cmp
!(PathBuf
, &'a Path
);
2493 impl_cmp
!(Cow
<'a
, Path
>, Path
);
2494 impl_cmp
!(Cow
<'a
, Path
>, &'b Path
);
2495 impl_cmp
!(Cow
<'a
, Path
>, PathBuf
);
2497 macro_rules
! impl_cmp_os_str
{
2498 ($lhs
:ty
, $rhs
: ty
) => {
2499 #[stable(feature = "cmp_path", since = "1.8.0")]
2500 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
2502 fn eq(&self, other
: &$rhs
) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2505 #[stable(feature = "cmp_path", since = "1.8.0")]
2506 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
2508 fn eq(&self, other
: &$lhs
) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2511 #[stable(feature = "cmp_path", since = "1.8.0")]
2512 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
2514 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
2515 <Path
as PartialOrd
>::partial_cmp(self, other
.as_ref())
2519 #[stable(feature = "cmp_path", since = "1.8.0")]
2520 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
2522 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
2523 <Path
as PartialOrd
>::partial_cmp(self.as_ref(), other
)
2529 impl_cmp_os_str
!(PathBuf
, OsStr
);
2530 impl_cmp_os_str
!(PathBuf
, &'a OsStr
);
2531 impl_cmp_os_str
!(PathBuf
, Cow
<'a
, OsStr
>);
2532 impl_cmp_os_str
!(PathBuf
, OsString
);
2533 impl_cmp_os_str
!(Path
, OsStr
);
2534 impl_cmp_os_str
!(Path
, &'a OsStr
);
2535 impl_cmp_os_str
!(Path
, Cow
<'a
, OsStr
>);
2536 impl_cmp_os_str
!(Path
, OsString
);
2537 impl_cmp_os_str
!(&'a Path
, OsStr
);
2538 impl_cmp_os_str
!(&'a Path
, Cow
<'b
, OsStr
>);
2539 impl_cmp_os_str
!(&'a Path
, OsString
);
2540 impl_cmp_os_str
!(Cow
<'a
, Path
>, OsStr
);
2541 impl_cmp_os_str
!(Cow
<'a
, Path
>, &'b OsStr
);
2542 impl_cmp_os_str
!(Cow
<'a
, Path
>, OsString
);
2544 #[stable(since = "1.7.0", feature = "strip_prefix")]
2545 impl fmt
::Display
for StripPrefixError
{
2546 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2547 self.description().fmt(f
)
2551 #[stable(since = "1.7.0", feature = "strip_prefix")]
2552 impl Error
for StripPrefixError
{
2553 fn description(&self) -> &str { "prefix not found" }
2561 ($path
:expr
, iter
: $iter
:expr
) => (
2563 let path
= Path
::new($path
);
2565 // Forward iteration
2566 let comps
= path
.iter()
2567 .map(|p
| p
.to_string_lossy().into_owned())
2568 .collect
::<Vec
<String
>>();
2569 let exp
: &[&str] = &$iter
;
2570 let exps
= exp
.iter().map(|s
| s
.to_string()).collect
::<Vec
<String
>>();
2571 assert
!(comps
== exps
, "iter: Expected {:?}, found {:?}",
2574 // Reverse iteration
2575 let comps
= Path
::new($path
).iter().rev()
2576 .map(|p
| p
.to_string_lossy().into_owned())
2577 .collect
::<Vec
<String
>>();
2578 let exps
= exps
.into_iter().rev().collect
::<Vec
<String
>>();
2579 assert
!(comps
== exps
, "iter().rev(): Expected {:?}, found {:?}",
2584 ($path
:expr
, has_root
: $has_root
:expr
, is_absolute
: $is_absolute
:expr
) => (
2586 let path
= Path
::new($path
);
2588 let act_root
= path
.has_root();
2589 assert
!(act_root
== $has_root
, "has_root: Expected {:?}, found {:?}",
2590 $has_root
, act_root
);
2592 let act_abs
= path
.is_absolute();
2593 assert
!(act_abs
== $is_absolute
, "is_absolute: Expected {:?}, found {:?}",
2594 $is_absolute
, act_abs
);
2598 ($path
:expr
, parent
: $parent
:expr
, file_name
: $file
:expr
) => (
2600 let path
= Path
::new($path
);
2602 let parent
= path
.parent().map(|p
| p
.to_str().unwrap());
2603 let exp_parent
: Option
<&str> = $parent
;
2604 assert
!(parent
== exp_parent
, "parent: Expected {:?}, found {:?}",
2605 exp_parent
, parent
);
2607 let file
= path
.file_name().map(|p
| p
.to_str().unwrap());
2608 let exp_file
: Option
<&str> = $file
;
2609 assert
!(file
== exp_file
, "file_name: Expected {:?}, found {:?}",
2614 ($path
:expr
, file_stem
: $file_stem
:expr
, extension
: $extension
:expr
) => (
2616 let path
= Path
::new($path
);
2618 let stem
= path
.file_stem().map(|p
| p
.to_str().unwrap());
2619 let exp_stem
: Option
<&str> = $file_stem
;
2620 assert
!(stem
== exp_stem
, "file_stem: Expected {:?}, found {:?}",
2623 let ext
= path
.extension().map(|p
| p
.to_str().unwrap());
2624 let exp_ext
: Option
<&str> = $extension
;
2625 assert
!(ext
== exp_ext
, "extension: Expected {:?}, found {:?}",
2630 ($path
:expr
, iter
: $iter
:expr
,
2631 has_root
: $has_root
:expr
, is_absolute
: $is_absolute
:expr
,
2632 parent
: $parent
:expr
, file_name
: $file
:expr
,
2633 file_stem
: $file_stem
:expr
, extension
: $extension
:expr
) => (
2635 t
!($path
, iter
: $iter
);
2636 t
!($path
, has_root
: $has_root
, is_absolute
: $is_absolute
);
2637 t
!($path
, parent
: $parent
, file_name
: $file
);
2638 t
!($path
, file_stem
: $file_stem
, extension
: $extension
);
2647 let static_path
= Path
::new("/home/foo");
2648 let static_cow_path
: Cow
<'
static, Path
> = static_path
.into();
2649 let pathbuf
= PathBuf
::from("/home/foo");
2652 let path
: &Path
= &pathbuf
;
2653 let borrowed_cow_path
: Cow
<Path
> = path
.into();
2655 assert_eq
!(static_cow_path
, borrowed_cow_path
);
2658 let owned_cow_path
: Cow
<'
static, Path
> = pathbuf
.into();
2660 assert_eq
!(static_cow_path
, owned_cow_path
);
2665 pub fn test_decompositions_unix() {
2681 file_name
: Some("foo"),
2682 file_stem
: Some("foo"),
2701 file_name
: Some("foo"),
2702 file_stem
: Some("foo"),
2711 file_name
: Some("foo"),
2712 file_stem
: Some("foo"),
2721 file_name
: Some("foo"),
2722 file_stem
: Some("foo"),
2727 iter
: ["foo", "bar"],
2730 parent
: Some("foo"),
2731 file_name
: Some("bar"),
2732 file_stem
: Some("bar"),
2737 iter
: ["/", "foo", "bar"],
2740 parent
: Some("/foo"),
2741 file_name
: Some("bar"),
2742 file_stem
: Some("bar"),
2751 file_name
: Some("foo"),
2752 file_stem
: Some("foo"),
2757 iter
: ["/", "foo", "bar"],
2760 parent
: Some("///foo"),
2761 file_name
: Some("bar"),
2762 file_stem
: Some("bar"),
2801 file_name
: Some("foo"),
2802 file_stem
: Some("foo"),
2807 iter
: ["foo", ".."],
2810 parent
: Some("foo"),
2821 file_name
: Some("foo"),
2822 file_stem
: Some("foo"),
2827 iter
: ["foo", "bar"],
2830 parent
: Some("foo"),
2831 file_name
: Some("bar"),
2832 file_stem
: Some("bar"),
2837 iter
: ["foo", ".."],
2840 parent
: Some("foo"),
2847 iter
: ["foo", "..", "bar"],
2850 parent
: Some("foo/.."),
2851 file_name
: Some("bar"),
2852 file_stem
: Some("bar"),
2861 file_name
: Some("a"),
2862 file_stem
: Some("a"),
2891 file_name
: Some("b"),
2892 file_stem
: Some("b"),
2901 file_name
: Some("b"),
2902 file_stem
: Some("b"),
2911 file_name
: Some("b"),
2912 file_stem
: Some("b"),
2917 iter
: ["a", "b", "c"],
2920 parent
: Some("a/b"),
2921 file_name
: Some("c"),
2922 file_stem
: Some("c"),
2931 file_name
: Some(".foo"),
2932 file_stem
: Some(".foo"),
2939 pub fn test_decompositions_windows() {
2955 file_name
: Some("foo"),
2956 file_stem
: Some("foo"),
3011 iter
: ["\\", "foo"],
3015 file_name
: Some("foo"),
3016 file_stem
: Some("foo"),
3025 file_name
: Some("foo"),
3026 file_stem
: Some("foo"),
3031 iter
: ["\\", "foo"],
3035 file_name
: Some("foo"),
3036 file_stem
: Some("foo"),
3041 iter
: ["foo", "bar"],
3044 parent
: Some("foo"),
3045 file_name
: Some("bar"),
3046 file_stem
: Some("bar"),
3051 iter
: ["\\", "foo", "bar"],
3054 parent
: Some("/foo"),
3055 file_name
: Some("bar"),
3056 file_stem
: Some("bar"),
3061 iter
: ["\\", "foo"],
3065 file_name
: Some("foo"),
3066 file_stem
: Some("foo"),
3071 iter
: ["\\", "foo", "bar"],
3074 parent
: Some("///foo"),
3075 file_name
: Some("bar"),
3076 file_stem
: Some("bar"),
3115 file_name
: Some("foo"),
3116 file_stem
: Some("foo"),
3121 iter
: ["foo", ".."],
3124 parent
: Some("foo"),
3135 file_name
: Some("foo"),
3136 file_stem
: Some("foo"),
3141 iter
: ["foo", "bar"],
3144 parent
: Some("foo"),
3145 file_name
: Some("bar"),
3146 file_stem
: Some("bar"),
3151 iter
: ["foo", ".."],
3154 parent
: Some("foo"),
3161 iter
: ["foo", "..", "bar"],
3164 parent
: Some("foo/.."),
3165 file_name
: Some("bar"),
3166 file_stem
: Some("bar"),
3175 file_name
: Some("a"),
3176 file_stem
: Some("a"),
3205 file_name
: Some("b"),
3206 file_stem
: Some("b"),
3215 file_name
: Some("b"),
3216 file_stem
: Some("b"),
3225 file_name
: Some("b"),
3226 file_stem
: Some("b"),
3231 iter
: ["a", "b", "c"],
3234 parent
: Some("a/b"),
3235 file_name
: Some("c"),
3236 file_stem
: Some("c"),
3240 iter
: ["a", "b", "c"],
3243 parent
: Some("a\\b"),
3244 file_name
: Some("c"),
3245 file_stem
: Some("c"),
3254 file_name
: Some("a"),
3255 file_stem
: Some("a"),
3260 iter
: ["c:", "\\", "foo.txt"],
3263 parent
: Some("c:\\"),
3264 file_name
: Some("foo.txt"),
3265 file_stem
: Some("foo"),
3266 extension
: Some("txt")
3269 t
!("\\\\server\\share\\foo.txt",
3270 iter
: ["\\\\server\\share", "\\", "foo.txt"],
3273 parent
: Some("\\\\server\\share\\"),
3274 file_name
: Some("foo.txt"),
3275 file_stem
: Some("foo"),
3276 extension
: Some("txt")
3279 t
!("\\\\server\\share",
3280 iter
: ["\\\\server\\share", "\\"],
3290 iter
: ["\\", "server"],
3294 file_name
: Some("server"),
3295 file_stem
: Some("server"),
3299 t
!("\\\\?\\bar\\foo.txt",
3300 iter
: ["\\\\?\\bar", "\\", "foo.txt"],
3303 parent
: Some("\\\\?\\bar\\"),
3304 file_name
: Some("foo.txt"),
3305 file_stem
: Some("foo"),
3306 extension
: Some("txt")
3310 iter
: ["\\\\?\\bar"],
3329 t
!("\\\\?\\UNC\\server\\share\\foo.txt",
3330 iter
: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3333 parent
: Some("\\\\?\\UNC\\server\\share\\"),
3334 file_name
: Some("foo.txt"),
3335 file_stem
: Some("foo"),
3336 extension
: Some("txt")
3339 t
!("\\\\?\\UNC\\server",
3340 iter
: ["\\\\?\\UNC\\server"],
3350 iter
: ["\\\\?\\UNC\\"],
3359 t
!("\\\\?\\C:\\foo.txt",
3360 iter
: ["\\\\?\\C:", "\\", "foo.txt"],
3363 parent
: Some("\\\\?\\C:\\"),
3364 file_name
: Some("foo.txt"),
3365 file_stem
: Some("foo"),
3366 extension
: Some("txt")
3371 iter
: ["\\\\?\\C:", "\\"],
3382 iter
: ["\\\\?\\C:"],
3392 t
!("\\\\?\\foo/bar",
3393 iter
: ["\\\\?\\foo/bar"],
3404 iter
: ["\\\\?\\C:/foo"],
3414 t
!("\\\\.\\foo\\bar",
3415 iter
: ["\\\\.\\foo", "\\", "bar"],
3418 parent
: Some("\\\\.\\foo\\"),
3419 file_name
: Some("bar"),
3420 file_stem
: Some("bar"),
3426 iter
: ["\\\\.\\foo", "\\"],
3436 t
!("\\\\.\\foo/bar",
3437 iter
: ["\\\\.\\foo/bar", "\\"],
3447 t
!("\\\\.\\foo\\bar/baz",
3448 iter
: ["\\\\.\\foo", "\\", "bar", "baz"],
3451 parent
: Some("\\\\.\\foo\\bar"),
3452 file_name
: Some("baz"),
3453 file_stem
: Some("baz"),
3459 iter
: ["\\\\.\\", "\\"],
3469 iter
: ["\\\\?\\a", "\\", "b"],
3472 parent
: Some("\\\\?\\a\\"),
3473 file_name
: Some("b"),
3474 file_stem
: Some("b"),
3480 pub fn test_stem_ext() {
3482 file_stem
: Some("foo"),
3487 file_stem
: Some("foo"),
3492 file_stem
: Some(".foo"),
3497 file_stem
: Some("foo"),
3498 extension
: Some("txt")
3502 file_stem
: Some("foo.bar"),
3503 extension
: Some("txt")
3507 file_stem
: Some("foo.bar"),
3528 pub fn test_push() {
3530 ($path
:expr
, $push
:expr
, $expected
:expr
) => ( {
3531 let mut actual
= PathBuf
::from($path
);
3533 assert
!(actual
.to_str() == Some($expected
),
3534 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3535 $push
, $path
, $expected
, actual
.to_str().unwrap());
3540 tp
!("", "foo", "foo");
3541 tp
!("foo", "bar", "foo/bar");
3542 tp
!("foo/", "bar", "foo/bar");
3543 tp
!("foo//", "bar", "foo//bar");
3544 tp
!("foo/.", "bar", "foo/./bar");
3545 tp
!("foo./.", "bar", "foo././bar");
3546 tp
!("foo", "", "foo/");
3547 tp
!("foo", ".", "foo/.");
3548 tp
!("foo", "..", "foo/..");
3549 tp
!("foo", "/", "/");
3550 tp
!("/foo/bar", "/", "/");
3551 tp
!("/foo/bar", "/baz", "/baz");
3552 tp
!("/foo/bar", "./baz", "/foo/bar/./baz");
3554 tp
!("", "foo", "foo");
3555 tp
!("foo", "bar", r
"foo\bar");
3556 tp
!("foo/", "bar", r
"foo/bar");
3557 tp
!(r
"foo\", "bar", r
"foo\bar");
3558 tp
!("foo//", "bar", r
"foo//bar");
3559 tp
!(r
"foo\\", "bar", r
"foo\\bar");
3560 tp
!("foo/.", "bar", r
"foo/.\bar");
3561 tp
!("foo./.", "bar", r
"foo./.\bar");
3562 tp
!(r
"foo\.", "bar", r
"foo\.\bar");
3563 tp
!(r
"foo.\.", "bar", r
"foo.\.\bar");
3564 tp
!("foo", "", "foo\\");
3565 tp
!("foo", ".", r
"foo\.");
3566 tp
!("foo", "..", r
"foo\..");
3567 tp
!("foo", "/", "/");
3568 tp
!("foo", r
"\", r
"\");
3569 tp
!("/foo/bar", "/", "/");
3570 tp
!(r
"\foo\bar", r
"\", r
"\");
3571 tp
!("/foo/bar", "/baz", "/baz");
3572 tp
!("/foo/bar", r
"\baz", r
"\baz");
3573 tp
!("/foo/bar", "./baz", r
"/foo/bar\./baz");
3574 tp
!("/foo/bar", r
".\baz", r
"/foo/bar\.\baz");
3576 tp
!("c:\\", "windows", "c:\\windows");
3577 tp
!("c:", "windows", "c:windows");
3579 tp
!("a\\b\\c", "d", "a\\b\\c\\d");
3580 tp
!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3581 tp
!("a\\b", "c\\d", "a\\b\\c\\d");
3582 tp
!("a\\b", "\\c\\d", "\\c\\d");
3583 tp
!("a\\b", ".", "a\\b\\.");
3584 tp
!("a\\b", "..\\c", "a\\b\\..\\c");
3585 tp
!("a\\b", "C:a.txt", "C:a.txt");
3586 tp
!("a\\b", "C:\\a.txt", "C:\\a.txt");
3587 tp
!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3588 tp
!("C:\\a\\b\\c", "C:d", "C:d");
3589 tp
!("C:a\\b\\c", "C:d", "C:d");
3590 tp
!("C:", r
"a\b\c", r
"C:a\b\c");
3591 tp
!("C:", r
"..\a", r
"C:..\a");
3592 tp
!("\\\\server\\share\\foo",
3594 "\\\\server\\share\\foo\\bar");
3595 tp
!("\\\\server\\share\\foo", "C:baz", "C:baz");
3596 tp
!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3597 tp
!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3598 tp
!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3599 tp
!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3600 tp
!("\\\\?\\UNC\\server\\share\\foo",
3602 "\\\\?\\UNC\\server\\share\\foo\\bar");
3603 tp
!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3604 tp
!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3606 // Note: modified from old path API
3607 tp
!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3610 "\\\\?\\UNC\\server\\share",
3611 "\\\\?\\UNC\\server\\share");
3612 tp
!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3613 tp
!("\\\\.\\foo\\bar", "C:a", "C:a");
3614 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3615 tp
!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3617 tp
!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3624 ($path
:expr
, $expected
:expr
, $output
:expr
) => ( {
3625 let mut actual
= PathBuf
::from($path
);
3626 let output
= actual
.pop();
3627 assert
!(actual
.to_str() == Some($expected
) && output
== $output
,
3628 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3629 $path
, $expected
, $output
,
3630 actual
.to_str().unwrap(), output
);
3635 tp
!("/", "/", false);
3636 tp
!("foo", "", true);
3638 tp
!("/foo", "/", true);
3639 tp
!("/foo/bar", "/foo", true);
3640 tp
!("foo/bar", "foo", true);
3641 tp
!("foo/.", "", true);
3642 tp
!("foo//bar", "foo", true);
3645 tp
!("a\\b\\c", "a\\b", true);
3646 tp
!("\\a", "\\", true);
3647 tp
!("\\", "\\", false);
3649 tp
!("C:\\a\\b", "C:\\a", true);
3650 tp
!("C:\\a", "C:\\", true);
3651 tp
!("C:\\", "C:\\", false);
3652 tp
!("C:a\\b", "C:a", true);
3653 tp
!("C:a", "C:", true);
3654 tp
!("C:", "C:", false);
3655 tp
!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3656 tp
!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3657 tp
!("\\\\server\\share", "\\\\server\\share", false);
3658 tp
!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3659 tp
!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3660 tp
!("\\\\?\\a", "\\\\?\\a", false);
3661 tp
!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3662 tp
!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3663 tp
!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3664 tp
!("\\\\?\\UNC\\server\\share\\a\\b",
3665 "\\\\?\\UNC\\server\\share\\a",
3667 tp
!("\\\\?\\UNC\\server\\share\\a",
3668 "\\\\?\\UNC\\server\\share\\",
3670 tp
!("\\\\?\\UNC\\server\\share",
3671 "\\\\?\\UNC\\server\\share",
3673 tp
!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3674 tp
!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3675 tp
!("\\\\.\\a", "\\\\.\\a", false);
3677 tp
!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3682 pub fn test_set_file_name() {
3684 ($path
:expr
, $file
:expr
, $expected
:expr
) => ( {
3685 let mut p
= PathBuf
::from($path
);
3686 p
.set_file_name($file
);
3687 assert
!(p
.to_str() == Some($expected
),
3688 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3689 $path
, $file
, $expected
,
3690 p
.to_str().unwrap());
3694 tfn
!("foo", "foo", "foo");
3695 tfn
!("foo", "bar", "bar");
3696 tfn
!("foo", "", "");
3697 tfn
!("", "foo", "foo");
3699 tfn
!(".", "foo", "./foo");
3700 tfn
!("foo/", "bar", "bar");
3701 tfn
!("foo/.", "bar", "bar");
3702 tfn
!("..", "foo", "../foo");
3703 tfn
!("foo/..", "bar", "foo/../bar");
3704 tfn
!("/", "foo", "/foo");
3706 tfn
!(".", "foo", r
".\foo");
3707 tfn
!(r
"foo\", "bar", r
"bar");
3708 tfn
!(r
"foo\.", "bar", r
"bar");
3709 tfn
!("..", "foo", r
"..\foo");
3710 tfn
!(r
"foo\..", "bar", r
"foo\..\bar");
3711 tfn
!(r
"\", "foo", r
"\foo");
3716 pub fn test_set_extension() {
3718 ($path
:expr
, $ext
:expr
, $expected
:expr
, $output
:expr
) => ( {
3719 let mut p
= PathBuf
::from($path
);
3720 let output
= p
.set_extension($ext
);
3721 assert
!(p
.to_str() == Some($expected
) && output
== $output
,
3722 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3723 $path
, $ext
, $expected
, $output
,
3724 p
.to_str().unwrap(), output
);
3728 tfe
!("foo", "txt", "foo.txt", true);
3729 tfe
!("foo.bar", "txt", "foo.txt", true);
3730 tfe
!("foo.bar.baz", "txt", "foo.bar.txt", true);
3731 tfe
!(".test", "txt", ".test.txt", true);
3732 tfe
!("foo.txt", "", "foo", true);
3733 tfe
!("foo", "", "foo", true);
3734 tfe
!("", "foo", "", false);
3735 tfe
!(".", "foo", ".", false);
3736 tfe
!("foo/", "bar", "foo.bar", true);
3737 tfe
!("foo/.", "bar", "foo.bar", true);
3738 tfe
!("..", "foo", "..", false);
3739 tfe
!("foo/..", "bar", "foo/..", false);
3740 tfe
!("/", "foo", "/", false);
3744 fn test_eq_recievers() {
3747 let borrowed
: &Path
= Path
::new("foo/bar");
3748 let mut owned
: PathBuf
= PathBuf
::new();
3751 let borrowed_cow
: Cow
<Path
> = borrowed
.into();
3752 let owned_cow
: Cow
<Path
> = owned
.clone().into();
3755 ($
($current
:expr
),+) => {
3757 assert_eq
!($current
, borrowed
);
3758 assert_eq
!($current
, owned
);
3759 assert_eq
!($current
, borrowed_cow
);
3760 assert_eq
!($current
, owned_cow
);
3765 t
!(borrowed
, owned
, borrowed_cow
, owned_cow
);
3769 pub fn test_compare() {
3770 use hash
::{Hash, Hasher}
;
3771 use collections
::hash_map
::DefaultHasher
;
3773 fn hash
<T
: Hash
>(t
: T
) -> u64 {
3774 let mut s
= DefaultHasher
::new();
3780 ($path1
:expr
, $path2
:expr
, eq
: $eq
:expr
,
3781 starts_with
: $starts_with
:expr
, ends_with
: $ends_with
:expr
,
3782 relative_from
: $relative_from
:expr
) => ({
3783 let path1
= Path
::new($path1
);
3784 let path2
= Path
::new($path2
);
3786 let eq
= path1
== path2
;
3787 assert
!(eq
== $eq
, "{:?} == {:?}, expected {:?}, got {:?}",
3788 $path1
, $path2
, $eq
, eq
);
3789 assert
!($eq
== (hash(path1
) == hash(path2
)),
3790 "{:?} == {:?}, expected {:?}, got {} and {}",
3791 $path1
, $path2
, $eq
, hash(path1
), hash(path2
));
3793 let starts_with
= path1
.starts_with(path2
);
3794 assert
!(starts_with
== $starts_with
,
3795 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1
, $path2
,
3796 $starts_with
, starts_with
);
3798 let ends_with
= path1
.ends_with(path2
);
3799 assert
!(ends_with
== $ends_with
,
3800 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1
, $path2
,
3801 $ends_with
, ends_with
);
3803 let relative_from
= path1
.strip_prefix(path2
)
3804 .map(|p
| p
.to_str().unwrap())
3806 let exp
: Option
<&str> = $relative_from
;
3807 assert
!(relative_from
== exp
,
3808 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3809 $path1
, $path2
, exp
, relative_from
);
3817 relative_from
: Some("")
3824 relative_from
: Some("foo")
3838 relative_from
: Some("")
3845 relative_from
: Some("")
3848 tc
!("foo/bar", "foo",
3852 relative_from
: Some("bar")
3855 tc
!("foo/bar/baz", "foo/bar",
3859 relative_from
: Some("baz")
3862 tc
!("foo/bar", "foo/bar/baz",
3869 tc
!("./foo/bar/", ".",
3873 relative_from
: Some("foo/bar")
3877 tc
!(r
"C:\src\rust\cargo-test\test\Cargo.toml",
3878 r
"c:\src\rust\cargo-test\test",
3882 relative_from
: Some("Cargo.toml")
3885 tc
!(r
"c:\foo", r
"C:\foo",
3889 relative_from
: Some("")
3895 fn test_components_debug() {
3896 let path
= Path
::new("/tmp");
3898 let mut components
= path
.components();
3900 let expected
= "Components([RootDir, Normal(\"tmp\")])";
3901 let actual
= format
!("{:?}", components
);
3902 assert_eq
!(expected
, actual
);
3904 let _
= components
.next().unwrap();
3905 let expected
= "Components([Normal(\"tmp\")])";
3906 let actual
= format
!("{:?}", components
);
3907 assert_eq
!(expected
, actual
);
3909 let _
= components
.next().unwrap();
3910 let expected
= "Components([])";
3911 let actual
= format
!("{:?}", components
);
3912 assert_eq
!(expected
, actual
);
3917 fn test_iter_debug() {
3918 let path
= Path
::new("/tmp");
3920 let mut iter
= path
.iter();
3922 let expected
= "Iter([\"/\", \"tmp\"])";
3923 let actual
= format
!("{:?}", iter
);
3924 assert_eq
!(expected
, actual
);
3926 let _
= iter
.next().unwrap();
3927 let expected
= "Iter([\"tmp\"])";
3928 let actual
= format
!("{:?}", iter
);
3929 assert_eq
!(expected
, actual
);
3931 let _
= iter
.next().unwrap();
3932 let expected
= "Iter([])";
3933 let actual
= format
!("{:?}", iter
);
3934 assert_eq
!(expected
, actual
);
3939 let orig
: &str = "some/sort/of/path";
3940 let path
= Path
::new(orig
);
3941 let boxed
: Box
<Path
> = Box
::from(path
);
3942 let path_buf
= path
.to_owned().into_boxed_path().into_path_buf();
3943 assert_eq
!(path
, &*boxed
);
3944 assert_eq
!(&*boxed
, &*path_buf
);
3945 assert_eq
!(&*path_buf
, path
);
3949 fn test_clone_into() {
3950 let mut path_buf
= PathBuf
::from("supercalifragilisticexpialidocious");
3951 let path
= Path
::new("short");
3952 path
.clone_into(&mut path_buf
);
3953 assert_eq
!(path
, path_buf
);
3954 assert
!(path_buf
.into_os_string().capacity() >= 15);
3958 fn display_format_flags() {
3959 assert_eq
!(format
!("a{:#<5}b", Path
::new("").display()), "a#####b");
3960 assert_eq
!(format
!("a{:#<5}b", Path
::new("a").display()), "aa####b");