path.rs 123.9 KB
Newer Older
A
Aaron Turon 已提交
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Cross-platform path manipulation.
//!
G
Guillaume Gomez 已提交
13
//! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
14 15
//! and [`str`]), for working with paths abstractly. These types are thin wrappers
//! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
A
Aaron Turon 已提交
16 17
//! on strings according to the local platform's path syntax.
//!
18 19 20 21 22 23 24
//! Paths can be parsed into [`Component`]s by iterating over the structure
//! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
//! correspond to the substrings between path separators (`/` or `\`). You can
//! reconstruct an equivalent path from components with the [`push`] method on
//! [`PathBuf`]; note that the paths may differ syntactically by the
//! normalization described in the documentation for the [`components`] method.
//!
A
Aaron Turon 已提交
25 26
//! ## Simple usage
//!
A
Aaron Turon 已提交
27
//! Path manipulation includes both parsing components from slices and building
A
Aaron Turon 已提交
28 29
//! new owned paths.
//!
30
//! To parse a path, you can create a [`Path`] slice from a [`str`]
A
Aaron Turon 已提交
31 32
//! slice and start asking questions:
//!
33
//! ```
A
Aaron Turon 已提交
34
//! use std::path::Path;
35
//! use std::ffi::OsStr;
A
Aaron Turon 已提交
36 37
//!
//! let path = Path::new("/tmp/foo/bar.txt");
38 39 40 41 42 43 44
//!
//! let parent = path.parent();
//! assert_eq!(parent, Some(Path::new("/tmp/foo")));
//!
//! let file_stem = path.file_stem();
//! assert_eq!(file_stem, Some(OsStr::new("bar")));
//!
A
Aaron Turon 已提交
45
//! let extension = path.extension();
46
//! assert_eq!(extension, Some(OsStr::new("txt")));
A
Aaron Turon 已提交
47 48
//! ```
//!
49
//! To build or modify paths, use [`PathBuf`]:
A
Aaron Turon 已提交
50
//!
51
//! ```
A
Aaron Turon 已提交
52 53
//! use std::path::PathBuf;
//!
54
//! // This way works...
55
//! let mut path = PathBuf::from("c:\\");
56
//!
A
Aaron Turon 已提交
57 58
//! path.push("windows");
//! path.push("system32");
59
//!
A
Aaron Turon 已提交
60
//! path.set_extension("dll");
61 62 63 64
//!
//! // ... but push is best used if you don't know everything up
//! // front. If you do, this way is better:
//! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
A
Aaron Turon 已提交
65 66
//! ```
//!
67 68
//! [`Component`]: ../../std/path/enum.Component.html
//! [`components`]: ../../std/path/struct.Path.html#method.components
69 70
//! [`PathBuf`]: ../../std/path/struct.PathBuf.html
//! [`Path`]: ../../std/path/struct.Path.html
71
//! [`push`]: ../../std/path/struct.PathBuf.html#method.push
72
//! [`String`]: ../../std/string/struct.String.html
73
//!
74 75 76
//! [`str`]: ../../std/primitive.str.html
//! [`OsString`]: ../../std/ffi/struct.OsString.html
//! [`OsStr`]: ../../std/ffi/struct.OsStr.html
A
Aaron Turon 已提交
77

A
Aaron Turon 已提交
78
#![stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
79

80
use borrow::{Borrow, Cow};
A
Aaron Turon 已提交
81
use cmp;
82
use error::Error;
83 84
use fmt;
use fs;
85
use hash::{Hash, Hasher};
86
use io;
S
Steven Allen 已提交
87
use iter::{self, FusedIterator};
A
Aaron Turon 已提交
88
use ops::{self, Deref};
89
use rc::Rc;
S
Simon Sapin 已提交
90 91
use str::FromStr;
use string::ParseError;
92
use sync::Arc;
A
Aaron Turon 已提交
93

94
use ffi::{OsStr, OsString};
A
Aaron Turon 已提交
95

96
use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
A
Aaron Turon 已提交
97 98 99 100 101 102 103 104 105 106 107

////////////////////////////////////////////////////////////////////////////////
// GENERAL NOTES
////////////////////////////////////////////////////////////////////////////////
//
// Parsing in this module is done by directly transmuting OsStr to [u8] slices,
// taking advantage of the fact that OsStr always encodes ASCII characters
// as-is.  Eventually, this transmutation should be replaced by direct uses of
// OsStr APIs for parsing, but it will take a while for those to become
// available.

A
Aaron Turon 已提交
108 109 110
////////////////////////////////////////////////////////////////////////////////
// Windows Prefixes
////////////////////////////////////////////////////////////////////////////////
A
Aaron Turon 已提交
111

112
/// Windows path prefixes, e.g. `C:` or `\\server\share`.
A
Aaron Turon 已提交
113
///
114 115 116
/// Windows uses a variety of path prefix styles, including references to drive
/// volumes (like `C:`), network shared folders (like `\\server\share`), and
/// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
L
lukaramu 已提交
117 118
/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
/// no normalization is performed.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
///
/// # Examples
///
/// ```
/// use std::path::{Component, Path, Prefix};
/// use std::path::Prefix::*;
/// use std::ffi::OsStr;
///
/// fn get_path_prefix(s: &str) -> Prefix {
///     let path = Path::new(s);
///     match path.components().next().unwrap() {
///         Component::Prefix(prefix_component) => prefix_component.kind(),
///         _ => panic!(),
///     }
/// }
///
/// # if cfg!(windows) {
/// assert_eq!(Verbatim(OsStr::new("pictures")),
///            get_path_prefix(r"\\?\pictures\kittens"));
/// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
///            get_path_prefix(r"\\?\UNC\server\share"));
140
/// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
141 142 143 144
/// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
///            get_path_prefix(r"\\.\BrainInterface"));
/// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
///            get_path_prefix(r"\\server\share"));
145
/// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
146 147
/// # }
/// ```
A
Aaron Turon 已提交
148
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
A
Aaron Turon 已提交
149
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
150
pub enum Prefix<'a> {
151 152 153 154
    /// Verbatim prefix, e.g. `\\?\cat_pics`.
    ///
    /// Verbatim prefixes consist of `\\?\` immediately followed by the given
    /// component.
A
Aaron Turon 已提交
155
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
156
    Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
A
Aaron Turon 已提交
157

158 159 160 161 162
    /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
    /// e.g. `\\?\UNC\server\share`.
    ///
    /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
    /// server's hostname and a share name.
A
Aaron Turon 已提交
163
    #[stable(feature = "rust1", since = "1.0.0")]
164
    VerbatimUNC(
A
Aaron Turon 已提交
165 166
        #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
        #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
167
    ),
A
Aaron Turon 已提交
168

169 170 171 172
    /// Verbatim disk prefix, e.g. `\\?\C:\`.
    ///
    /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
    /// drive letter and `:\`.
A
Aaron Turon 已提交
173
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
174
    VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
A
Aaron Turon 已提交
175

176 177 178 179
    /// Device namespace prefix, e.g. `\\.\COM42`.
    ///
    /// Device namespace prefixes consist of `\\.\` immediately followed by the
    /// device name.
A
Aaron Turon 已提交
180
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
181
    DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
A
Aaron Turon 已提交
182

183 184 185 186
    /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
    /// `\\server\share`.
    ///
    /// UNC prefixes consist of the server's hostname and a share name.
A
Aaron Turon 已提交
187
    #[stable(feature = "rust1", since = "1.0.0")]
188
    UNC(
A
Aaron Turon 已提交
189 190
        #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
        #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
191
    ),
A
Aaron Turon 已提交
192 193

    /// Prefix `C:` for the given disk drive.
A
Aaron Turon 已提交
194
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
195
    Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
A
Aaron Turon 已提交
196
}
A
Aaron Turon 已提交
197

A
Aaron Turon 已提交
198 199 200 201 202 203
impl<'a> Prefix<'a> {
    #[inline]
    fn len(&self) -> usize {
        use self::Prefix::*;
        fn os_str_len(s: &OsStr) -> usize {
            os_str_as_u8_slice(s).len()
A
Aaron Turon 已提交
204
        }
A
Aaron Turon 已提交
205 206
        match *self {
            Verbatim(x) => 4 + os_str_len(x),
T
Tshepang Lekhonkhobe 已提交
207 208 209 210 211 212 213 214
            VerbatimUNC(x, y) => {
                8 + os_str_len(x) +
                if os_str_len(y) > 0 {
                    1 + os_str_len(y)
                } else {
                    0
                }
            },
A
Aaron Turon 已提交
215
            VerbatimDisk(_) => 6,
T
Tshepang Lekhonkhobe 已提交
216 217 218 219 220 221 222 223
            UNC(x, y) => {
                2 + os_str_len(x) +
                if os_str_len(y) > 0 {
                    1 + os_str_len(y)
                } else {
                    0
                }
            },
A
Aaron Turon 已提交
224
            DeviceNS(x) => 4 + os_str_len(x),
T
Tshepang Lekhonkhobe 已提交
225
            Disk(_) => 2,
A
Aaron Turon 已提交
226 227
        }

A
Aaron Turon 已提交
228 229
    }

T
Tshepang Lekhonkhobe 已提交
230
    /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
231 232 233 234 235 236 237 238 239
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Prefix::*;
    /// use std::ffi::OsStr;
    ///
    /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
    /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
240
    /// assert!(VerbatimDisk(b'C').is_verbatim());
241 242
    /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
    /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
243
    /// assert!(!Disk(b'C').is_verbatim());
244
    /// ```
A
Aaron Turon 已提交
245
    #[inline]
A
Aaron Turon 已提交
246
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
247 248 249
    pub fn is_verbatim(&self) -> bool {
        use self::Prefix::*;
        match *self {
V
Vadim Petrochenkov 已提交
250
            Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
251
            _ => false,
A
Aaron Turon 已提交
252 253 254
        }
    }

A
Aaron Turon 已提交
255 256 257 258 259
    #[inline]
    fn is_drive(&self) -> bool {
        match *self {
            Prefix::Disk(_) => true,
            _ => false,
A
Aaron Turon 已提交
260 261 262
        }
    }

A
Aaron Turon 已提交
263 264 265 266
    #[inline]
    fn has_implicit_root(&self) -> bool {
        !self.is_drive()
    }
A
Aaron Turon 已提交
267 268
}

A
Aaron Turon 已提交
269 270 271 272
////////////////////////////////////////////////////////////////////////////////
// Exposed parsing helpers
////////////////////////////////////////////////////////////////////////////////

273
/// Determines whether the character is one of the permitted path
A
Aaron Turon 已提交
274
/// separators for the current platform.
275 276 277 278 279 280
///
/// # Examples
///
/// ```
/// use std::path;
///
281
/// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
282 283
/// assert!(!path::is_separator('❤'));
/// ```
A
Aaron Turon 已提交
284
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
285 286
pub fn is_separator(c: char) -> bool {
    c.is_ascii() && is_sep_byte(c as u8)
A
Aaron Turon 已提交
287 288
}

289 290 291
/// The primary separator of path components for the current platform.
///
/// For example, `/` on Unix and `\` on Windows.
A
Aaron Turon 已提交
292
#[stable(feature = "rust1", since = "1.0.0")]
293
pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
A
Aaron Turon 已提交
294

A
Aaron Turon 已提交
295 296 297 298 299 300 301
////////////////////////////////////////////////////////////////////////////////
// Misc helpers
////////////////////////////////////////////////////////////////////////////////

// Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
// is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
// `iter` after having exhausted `prefix`.
302 303 304
fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
    where I: Iterator<Item = Component<'a>> + Clone,
          J: Iterator<Item = Component<'b>>,
A
Aaron Turon 已提交
305 306 307 308
{
    loop {
        let mut iter_next = iter.clone();
        match (iter_next.next(), prefix.next()) {
309 310
            (Some(ref x), Some(ref y)) if x == y => (),
            (Some(_), Some(_)) => return None,
A
Aaron Turon 已提交
311 312 313 314 315 316 317 318 319 320
            (Some(_), None) => return Some(iter),
            (None, None) => return Some(iter),
            (None, Some(_)) => return None,
        }
        iter = iter_next;
    }
}

// See note at the top of this module to understand why these are used:
fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
321
    unsafe { &*(s as *const OsStr as *const [u8]) }
A
Aaron Turon 已提交
322 323
}
unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
324
    &*(s as *const [u8] as *const OsStr)
A
Aaron Turon 已提交
325 326
}

I
Ian Douglas Scott 已提交
327
// Detect scheme on Redox
328
fn has_redox_scheme(s: &[u8]) -> bool {
I
Ian Douglas Scott 已提交
329
    cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
I
Ian Douglas Scott 已提交
330 331
}

A
Aaron Turon 已提交
332
////////////////////////////////////////////////////////////////////////////////
A
Aaron Turon 已提交
333
// Cross-platform, iterator-independent parsing
A
Aaron Turon 已提交
334 335 336 337
////////////////////////////////////////////////////////////////////////////////

/// Says whether the first byte after the prefix is a separator.
fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
T
Tshepang Lekhonkhobe 已提交
338 339 340 341 342
    let path = if let Some(p) = prefix {
        &s[p.len()..]
    } else {
        s
    };
343
    !path.is_empty() && is_sep_byte(path[0])
A
Aaron Turon 已提交
344 345 346 347 348
}

// basic workhorse for splitting stem and extension
fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
    unsafe {
T
Tshepang Lekhonkhobe 已提交
349 350 351
        if os_str_as_u8_slice(file) == b".." {
            return (Some(file), None);
        }
A
Aaron Turon 已提交
352 353 354 355 356 357

        // The unsafety here stems from converting between &OsStr and &[u8]
        // and back. This is safe to do because (1) we only look at ASCII
        // contents of the encoding and (2) new &OsStr values are produced
        // only from ASCII-bounded slices of existing &OsStr values.

358
        let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
A
Aaron Turon 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
        let after = iter.next();
        let before = iter.next();
        if before == Some(b"") {
            (Some(file), None)
        } else {
            (before.map(|s| u8_slice_as_os_str(s)),
             after.map(|s| u8_slice_as_os_str(s)))
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// The core iterators
////////////////////////////////////////////////////////////////////////////////

/// Component parsing works by a double-ended state machine; the cursors at the
/// front and back of the path each keep track of what parts of the path have
/// been consumed so far.
///
A
Aaron Turon 已提交
378 379
/// Going front to back, a path is made up of a prefix, a starting
/// directory component, and a body (of normal components)
A
Alex Crichton 已提交
380
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
A
Aaron Turon 已提交
381 382
enum State {
    Prefix = 0,         // c:
A
Aaron Turon 已提交
383
    StartDir = 1,       // / or . or nothing
A
Aaron Turon 已提交
384
    Body = 2,           // foo/bar/baz
A
Aaron Turon 已提交
385 386 387
    Done = 3,
}

388 389
/// A structure wrapping a Windows path prefix as well as its unparsed string
/// representation.
A
Aaron Turon 已提交
390
///
391 392 393 394 395 396 397
/// In addition to the parsed [`Prefix`] information returned by [`kind`],
/// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
/// returned by [`as_os_str`].
///
/// Instances of this `struct` can be obtained by matching against the
/// [`Prefix` variant] on [`Component`].
///
A
Aaron Turon 已提交
398
/// Does not occur on Unix.
399 400 401 402 403 404 405 406 407 408 409
///
/// # Examples
///
/// ```
/// # if cfg!(windows) {
/// use std::path::{Component, Path, Prefix};
/// use std::ffi::OsStr;
///
/// let path = Path::new(r"c:\you\later\");
/// match path.components().next().unwrap() {
///     Component::Prefix(prefix_component) => {
410
///         assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
411 412 413 414 415 416 417 418 419 420 421 422 423
///         assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
///     }
///     _ => unreachable!(),
/// }
/// # }
/// ```
///
/// [`as_os_str`]: #method.as_os_str
/// [`Component`]: enum.Component.html
/// [`kind`]: #method.kind
/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
/// [`Prefix` variant]: enum.Component.html#variant.Prefix
/// [`Prefix`]: enum.Prefix.html
A
Aaron Turon 已提交
424
#[stable(feature = "rust1", since = "1.0.0")]
425
#[derive(Copy, Clone, Eq, Debug)]
A
Aaron Turon 已提交
426 427 428 429 430 431 432 433 434
pub struct PrefixComponent<'a> {
    /// The prefix as an unparsed `OsStr` slice.
    raw: &'a OsStr,

    /// The parsed prefix data.
    parsed: Prefix<'a>,
}

impl<'a> PrefixComponent<'a> {
435
    /// Returns the parsed prefix data.
436 437 438 439 440
    ///
    /// See [`Prefix`]'s documentation for more information on the different
    /// kinds of prefixes.
    ///
    /// [`Prefix`]: enum.Prefix.html
A
Aaron Turon 已提交
441
    #[stable(feature = "rust1", since = "1.0.0")]
M
Mazdak Farrokhzad 已提交
442
    pub const fn kind(&self) -> Prefix<'a> {
A
Aaron Turon 已提交
443 444 445
        self.parsed
    }

446 447 448
    /// Returns the raw [`OsStr`] slice for this prefix.
    ///
    /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
A
Aaron Turon 已提交
449
    #[stable(feature = "rust1", since = "1.0.0")]
M
Mazdak Farrokhzad 已提交
450
    pub const fn as_os_str(&self) -> &'a OsStr {
A
Aaron Turon 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        self.raw
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> cmp::PartialEq for PrefixComponent<'a> {
    fn eq(&self, other: &PrefixComponent<'a>) -> bool {
        cmp::PartialEq::eq(&self.parsed, &other.parsed)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
    fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
        cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> cmp::Ord for PrefixComponent<'a> {
    fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
        cmp::Ord::cmp(&self.parsed, &other.parsed)
    }
A
Aaron Turon 已提交
474 475
}

476 477 478 479 480 481 482
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Hash for PrefixComponent<'a> {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.parsed.hash(h);
    }
}

A
Aaron Turon 已提交
483 484
/// A single component of a path.
///
B
Bruce Mitchener 已提交
485
/// A `Component` roughly corresponds to a substring between path separators
486
/// (`/` or `\`).
487
///
488 489
/// This `enum` is created by iterating over [`Components`], which in turn is
/// created by the [`components`][`Path::components`] method on [`Path`].
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
///
/// # Examples
///
/// ```rust
/// use std::path::{Component, Path};
///
/// let path = Path::new("/tmp/foo/bar.txt");
/// let components = path.components().collect::<Vec<_>>();
/// assert_eq!(&components, &[
///     Component::RootDir,
///     Component::Normal("tmp".as_ref()),
///     Component::Normal("foo".as_ref()),
///     Component::Normal("bar.txt".as_ref()),
/// ]);
/// ```
///
506 507 508
/// [`Components`]: struct.Components.html
/// [`Path`]: struct.Path.html
/// [`Path::components`]: struct.Path.html#method.components
A
Alex Crichton 已提交
509
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
A
Aaron Turon 已提交
510
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
511
pub enum Component<'a> {
512
    /// A Windows path prefix, e.g. `C:` or `\\server\share`.
A
Aaron Turon 已提交
513
    ///
514 515 516
    /// There is a large variety of prefix types, see [`Prefix`]'s documentation
    /// for more.
    ///
A
Aaron Turon 已提交
517
    /// Does not occur on Unix.
518 519
    ///
    /// [`Prefix`]: enum.Prefix.html
A
Aaron Turon 已提交
520
    #[stable(feature = "rust1", since = "1.0.0")]
521
    Prefix(
A
Aaron Turon 已提交
522
        #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
523
    ),
A
Aaron Turon 已提交
524

525
    /// The root directory component, appears after any prefix and before anything else.
526
    ///
L
lukaramu 已提交
527
    /// It represents a separator that designates that a path starts from root.
A
Aaron Turon 已提交
528
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
529 530
    RootDir,

531
    /// A reference to the current directory, i.e. `.`.
A
Aaron Turon 已提交
532
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
533 534
    CurDir,

535
    /// A reference to the parent directory, i.e. `..`.
A
Aaron Turon 已提交
536
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
537 538
    ParentDir,

539
    /// A normal component, e.g. `a` and `b` in `a/b`.
540 541 542
    ///
    /// This variant is the most common one, it represents references to files
    /// or directories.
A
Aaron Turon 已提交
543
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
544
    Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
A
Aaron Turon 已提交
545 546 547
}

impl<'a> Component<'a> {
548
    /// Extracts the underlying [`OsStr`] slice.
G
Guillaume Gomez 已提交
549 550 551 552 553 554 555 556 557 558
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let path = Path::new("./tmp/foo/bar.txt");
    /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
    /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
    /// ```
559 560
    ///
    /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
A
Aaron Turon 已提交
561
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
562 563
    pub fn as_os_str(self) -> &'a OsStr {
        match self {
A
Aaron Turon 已提交
564
            Component::Prefix(p) => p.as_os_str(),
565 566 567
            Component::RootDir => OsStr::new(MAIN_SEP_STR),
            Component::CurDir => OsStr::new("."),
            Component::ParentDir => OsStr::new(".."),
A
Aaron Turon 已提交
568 569 570 571 572
            Component::Normal(path) => path,
        }
    }
}

A
Aaron Turon 已提交
573 574 575 576 577 578 579
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> AsRef<OsStr> for Component<'a> {
    fn as_ref(&self) -> &OsStr {
        self.as_os_str()
    }
}

580
#[stable(feature = "path_component_asref", since = "1.25.0")]
581 582 583 584 585 586
impl<'a> AsRef<Path> for Component<'a> {
    fn as_ref(&self) -> &Path {
        self.as_os_str().as_ref()
    }
}

B
Bruce Mitchener 已提交
587
/// An iterator over the [`Component`]s of a [`Path`].
A
Aaron Turon 已提交
588
///
589 590
/// This `struct` is created by the [`components`] method on [`Path`].
/// See its documentation for more.
591
///
592 593 594 595 596 597 598 599 600 601 602
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// let path = Path::new("/tmp/foo/bar.txt");
///
/// for component in path.components() {
///     println!("{:?}", component);
/// }
/// ```
603
///
604 605 606
/// [`Component`]: enum.Component.html
/// [`components`]: struct.Path.html#method.components
/// [`Path`]: struct.Path.html
A
Aaron Turon 已提交
607
#[derive(Clone)]
A
Aaron Turon 已提交
608
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
pub struct Components<'a> {
    // The path left to parse components from
    path: &'a [u8],

    // The prefix as it was originally parsed, if any
    prefix: Option<Prefix<'a>>,

    // true if path *physically* has a root separator; for most Windows
    // prefixes, it may have a "logical" rootseparator for the purposes of
    // normalization, e.g.  \\server\share == \\server\share\.
    has_physical_root: bool,

    // The iterator is double-ended, and these two states keep track of what has
    // been produced from either end
    front: State,
    back: State,
}

627
/// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
628
///
629 630 631 632 633
/// This `struct` is created by the [`iter`] method on [`Path`].
/// See its documentation for more.
///
/// [`Component`]: enum.Component.html
/// [`iter`]: struct.Path.html#method.iter
634
/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
635
/// [`Path`]: struct.Path.html
A
Aaron Turon 已提交
636
#[derive(Clone)]
A
Aaron Turon 已提交
637
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
638
pub struct Iter<'a> {
T
Tshepang Lekhonkhobe 已提交
639
    inner: Components<'a>,
A
Aaron Turon 已提交
640 641
}

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
#[stable(feature = "path_components_debug", since = "1.13.0")]
impl<'a> fmt::Debug for Components<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        struct DebugHelper<'a>(&'a Path);

        impl<'a> fmt::Debug for DebugHelper<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.debug_list()
                    .entries(self.0.components())
                    .finish()
            }
        }

        f.debug_tuple("Components")
            .field(&DebugHelper(self.as_path()))
            .finish()
    }
}

A
Aaron Turon 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
impl<'a> Components<'a> {
    // how long is the prefix, if any?
    #[inline]
    fn prefix_len(&self) -> usize {
        self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
    }

    #[inline]
    fn prefix_verbatim(&self) -> bool {
        self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
    }

    /// how much of the prefix is left from the point of view of iteration?
    #[inline]
    fn prefix_remaining(&self) -> usize {
676 677 678 679 680
        if self.front == State::Prefix {
            self.prefix_len()
        } else {
            0
        }
A
Aaron Turon 已提交
681 682
    }

A
Aaron Turon 已提交
683 684 685
    // Given the iteration so far, how much of the pre-State::Body path is left?
    #[inline]
    fn len_before_body(&self) -> usize {
T
Tshepang Lekhonkhobe 已提交
686 687 688 689 690 691 692 693 694 695
        let root = if self.front <= State::StartDir && self.has_physical_root {
            1
        } else {
            0
        };
        let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
            1
        } else {
            0
        };
A
Aaron Turon 已提交
696
        self.prefix_remaining() + root + cur_dir
A
Aaron Turon 已提交
697 698 699 700 701 702 703 704 705
    }

    // is the iteration complete?
    #[inline]
    fn finished(&self) -> bool {
        self.front == State::Done || self.back == State::Done || self.front > self.back
    }

    #[inline]
A
Aaron Turon 已提交
706
    fn is_sep_byte(&self, b: u8) -> bool {
A
Aaron Turon 已提交
707 708 709
        if self.prefix_verbatim() {
            is_verbatim_sep(b)
        } else {
A
Aaron Turon 已提交
710
            is_sep_byte(b)
A
Aaron Turon 已提交
711 712 713
        }
    }

714
    /// Extracts a slice corresponding to the portion of the path remaining for iteration.
715 716 717 718 719 720
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
721 722 723
    /// let mut components = Path::new("/tmp/foo/bar.txt").components();
    /// components.next();
    /// components.next();
724
    ///
725
    /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
726
    /// ```
A
Aaron Turon 已提交
727
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
728 729
    pub fn as_path(&self) -> &'a Path {
        let mut comps = self.clone();
T
Tshepang Lekhonkhobe 已提交
730 731 732 733 734 735
        if comps.front == State::Body {
            comps.trim_left();
        }
        if comps.back == State::Body {
            comps.trim_right();
        }
A
Aaron Turon 已提交
736
        unsafe { Path::from_u8_slice(comps.path) }
A
Aaron Turon 已提交
737 738 739 740
    }

    /// Is the *original* path rooted?
    fn has_root(&self) -> bool {
T
Tshepang Lekhonkhobe 已提交
741 742 743
        if self.has_physical_root {
            return true;
        }
A
Aaron Turon 已提交
744
        if let Some(p) = self.prefix {
T
Tshepang Lekhonkhobe 已提交
745 746 747
            if p.has_implicit_root() {
                return true;
            }
A
Aaron Turon 已提交
748 749 750 751
        }
        false
    }

A
Aaron Turon 已提交
752 753
    /// Should the normalized path include a leading . ?
    fn include_cur_dir(&self) -> bool {
T
Tshepang Lekhonkhobe 已提交
754 755 756
        if self.has_root() {
            return false;
        }
A
Aaron Turon 已提交
757 758 759 760
        let mut iter = self.path[self.prefix_len()..].iter();
        match (iter.next(), iter.next()) {
            (Some(&b'.'), None) => true,
            (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
T
Tshepang Lekhonkhobe 已提交
761
            _ => false,
A
Aaron Turon 已提交
762 763 764 765 766 767 768 769 770 771 772 773
        }
    }

    // parse a given byte sequence into the corresponding path component
    fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
        match comp {
            b"." if self.prefix_verbatim() => Some(Component::CurDir),
            b"." => None, // . components are normalized away, except at
                          // the beginning of a path, which is treated
                          // separately via `include_cur_dir`
            b".." => Some(Component::ParentDir),
            b"" => None,
T
Tshepang Lekhonkhobe 已提交
774
            _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
A
Aaron Turon 已提交
775 776 777
        }
    }

A
Aaron Turon 已提交
778 779 780 781
    // parse a component from the left, saying how many bytes to consume to
    // remove the component
    fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
        debug_assert!(self.front == State::Body);
A
Aaron Turon 已提交
782
        let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
A
Aaron Turon 已提交
783
            None => (0, self.path),
T
Tshepang Lekhonkhobe 已提交
784
            Some(i) => (1, &self.path[..i]),
A
Aaron Turon 已提交
785
        };
A
Aaron Turon 已提交
786
        (comp.len() + extra, self.parse_single_component(comp))
A
Aaron Turon 已提交
787 788 789 790 791 792
    }

    // parse a component from the right, saying how many bytes to consume to
    // remove the component
    fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
        debug_assert!(self.back == State::Body);
A
Aaron Turon 已提交
793
        let start = self.len_before_body();
A
Aaron Turon 已提交
794
        let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
T
Tshepang Lekhonkhobe 已提交
795 796
            None => (0, &self.path[start..]),
            Some(i) => (1, &self.path[start + i + 1..]),
A
Aaron Turon 已提交
797
        };
A
Aaron Turon 已提交
798
        (comp.len() + extra, self.parse_single_component(comp))
A
Aaron Turon 已提交
799 800
    }

C
Corey Farwell 已提交
801
    // trim away repeated separators (i.e. empty components) on the left
A
Aaron Turon 已提交
802 803 804 805 806 807
    fn trim_left(&mut self) {
        while !self.path.is_empty() {
            let (size, comp) = self.parse_next_component();
            if comp.is_some() {
                return;
            } else {
T
Tshepang Lekhonkhobe 已提交
808
                self.path = &self.path[size..];
A
Aaron Turon 已提交
809 810 811 812
            }
        }
    }

C
Corey Farwell 已提交
813
    // trim away repeated separators (i.e. empty components) on the right
A
Aaron Turon 已提交
814
    fn trim_right(&mut self) {
A
Aaron Turon 已提交
815
        while self.path.len() > self.len_before_body() {
A
Aaron Turon 已提交
816 817 818 819
            let (size, comp) = self.parse_next_component_back();
            if comp.is_some() {
                return;
            } else {
T
Tshepang Lekhonkhobe 已提交
820
                self.path = &self.path[..self.path.len() - size];
A
Aaron Turon 已提交
821 822 823 824 825
            }
        }
    }
}

A
Aaron Turon 已提交
826 827 828 829 830 831 832 833 834 835 836 837 838 839
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> AsRef<Path> for Components<'a> {
    fn as_ref(&self) -> &Path {
        self.as_path()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> AsRef<OsStr> for Components<'a> {
    fn as_ref(&self) -> &OsStr {
        self.as_path().as_os_str()
    }
}

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
#[stable(feature = "path_iter_debug", since = "1.13.0")]
impl<'a> fmt::Debug for Iter<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        struct DebugHelper<'a>(&'a Path);

        impl<'a> fmt::Debug for DebugHelper<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.debug_list()
                    .entries(self.0.iter())
                    .finish()
            }
        }

        f.debug_tuple("Iter")
            .field(&DebugHelper(self.as_path()))
            .finish()
    }
}

A
Aaron Turon 已提交
859
impl<'a> Iter<'a> {
860
    /// Extracts a slice corresponding to the portion of the path remaining for iteration.
861 862 863 864 865 866 867 868 869 870 871 872
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
    /// iter.next();
    /// iter.next();
    ///
    /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
    /// ```
A
Aaron Turon 已提交
873
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
874 875 876 877 878
    pub fn as_path(&self) -> &'a Path {
        self.inner.as_path()
    }
}

A
Aaron Turon 已提交
879 880 881 882 883 884 885 886 887 888 889 890 891 892
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> AsRef<Path> for Iter<'a> {
    fn as_ref(&self) -> &Path {
        self.as_path()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> AsRef<OsStr> for Iter<'a> {
    fn as_ref(&self) -> &OsStr {
        self.as_path().as_os_str()
    }
}

A
Aaron Turon 已提交
893
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
894 895 896 897 898 899 900 901
impl<'a> Iterator for Iter<'a> {
    type Item = &'a OsStr;

    fn next(&mut self) -> Option<&'a OsStr> {
        self.inner.next().map(Component::as_os_str)
    }
}

A
Aaron Turon 已提交
902
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
903 904 905 906 907 908
impl<'a> DoubleEndedIterator for Iter<'a> {
    fn next_back(&mut self) -> Option<&'a OsStr> {
        self.inner.next_back().map(Component::as_os_str)
    }
}

909
#[stable(feature = "fused", since = "1.26.0")]
S
Steven Allen 已提交
910 911
impl<'a> FusedIterator for Iter<'a> {}

A
Aaron Turon 已提交
912
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
913 914 915 916 917 918 919
impl<'a> Iterator for Components<'a> {
    type Item = Component<'a>;

    fn next(&mut self) -> Option<Component<'a>> {
        while !self.finished() {
            match self.front {
                State::Prefix if self.prefix_len() > 0 => {
A
Aaron Turon 已提交
920
                    self.front = State::StartDir;
A
Aaron Turon 已提交
921
                    debug_assert!(self.prefix_len() <= self.path.len());
T
Tshepang Lekhonkhobe 已提交
922 923
                    let raw = &self.path[..self.prefix_len()];
                    self.path = &self.path[self.prefix_len()..];
A
Aaron Turon 已提交
924
                    return Some(Component::Prefix(PrefixComponent {
A
Aaron Turon 已提交
925
                        raw: unsafe { u8_slice_as_os_str(raw) },
T
Tshepang Lekhonkhobe 已提交
926 927
                        parsed: self.prefix.unwrap(),
                    }));
A
Aaron Turon 已提交
928 929
                }
                State::Prefix => {
A
Aaron Turon 已提交
930
                    self.front = State::StartDir;
A
Aaron Turon 已提交
931
                }
A
Aaron Turon 已提交
932
                State::StartDir => {
A
Aaron Turon 已提交
933 934
                    self.front = State::Body;
                    if self.has_physical_root {
935
                        debug_assert!(!self.path.is_empty());
A
Aaron Turon 已提交
936
                        self.path = &self.path[1..];
T
Tshepang Lekhonkhobe 已提交
937
                        return Some(Component::RootDir);
A
Aaron Turon 已提交
938 939
                    } else if let Some(p) = self.prefix {
                        if p.has_implicit_root() && !p.is_verbatim() {
T
Tshepang Lekhonkhobe 已提交
940
                            return Some(Component::RootDir);
A
Aaron Turon 已提交
941
                        }
A
Aaron Turon 已提交
942
                    } else if self.include_cur_dir() {
943
                        debug_assert!(!self.path.is_empty());
A
Aaron Turon 已提交
944
                        self.path = &self.path[1..];
T
Tshepang Lekhonkhobe 已提交
945
                        return Some(Component::CurDir);
A
Aaron Turon 已提交
946 947 948 949
                    }
                }
                State::Body if !self.path.is_empty() => {
                    let (size, comp) = self.parse_next_component();
T
Tshepang Lekhonkhobe 已提交
950 951 952 953
                    self.path = &self.path[size..];
                    if comp.is_some() {
                        return comp;
                    }
A
Aaron Turon 已提交
954 955 956 957
                }
                State::Body => {
                    self.front = State::Done;
                }
T
Tshepang Lekhonkhobe 已提交
958
                State::Done => unreachable!(),
A
Aaron Turon 已提交
959 960 961 962 963 964
            }
        }
        None
    }
}

A
Aaron Turon 已提交
965
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
966 967 968 969
impl<'a> DoubleEndedIterator for Components<'a> {
    fn next_back(&mut self) -> Option<Component<'a>> {
        while !self.finished() {
            match self.back {
A
Aaron Turon 已提交
970
                State::Body if self.path.len() > self.len_before_body() => {
A
Aaron Turon 已提交
971
                    let (size, comp) = self.parse_next_component_back();
T
Tshepang Lekhonkhobe 已提交
972 973 974 975
                    self.path = &self.path[..self.path.len() - size];
                    if comp.is_some() {
                        return comp;
                    }
A
Aaron Turon 已提交
976 977
                }
                State::Body => {
A
Aaron Turon 已提交
978
                    self.back = State::StartDir;
A
Aaron Turon 已提交
979
                }
A
Aaron Turon 已提交
980
                State::StartDir => {
A
Aaron Turon 已提交
981 982
                    self.back = State::Prefix;
                    if self.has_physical_root {
T
Tshepang Lekhonkhobe 已提交
983 984
                        self.path = &self.path[..self.path.len() - 1];
                        return Some(Component::RootDir);
A
Aaron Turon 已提交
985 986
                    } else if let Some(p) = self.prefix {
                        if p.has_implicit_root() && !p.is_verbatim() {
T
Tshepang Lekhonkhobe 已提交
987
                            return Some(Component::RootDir);
A
Aaron Turon 已提交
988
                        }
A
Aaron Turon 已提交
989
                    } else if self.include_cur_dir() {
T
Tshepang Lekhonkhobe 已提交
990 991
                        self.path = &self.path[..self.path.len() - 1];
                        return Some(Component::CurDir);
A
Aaron Turon 已提交
992 993 994 995
                    }
                }
                State::Prefix if self.prefix_len() > 0 => {
                    self.back = State::Done;
A
Aaron Turon 已提交
996
                    return Some(Component::Prefix(PrefixComponent {
A
Aaron Turon 已提交
997
                        raw: unsafe { u8_slice_as_os_str(self.path) },
T
Tshepang Lekhonkhobe 已提交
998 999
                        parsed: self.prefix.unwrap(),
                    }));
A
Aaron Turon 已提交
1000 1001 1002
                }
                State::Prefix => {
                    self.back = State::Done;
T
Tshepang Lekhonkhobe 已提交
1003
                    return None;
A
Aaron Turon 已提交
1004
                }
T
Tshepang Lekhonkhobe 已提交
1005
                State::Done => unreachable!(),
A
Aaron Turon 已提交
1006 1007 1008 1009 1010 1011
            }
        }
        None
    }
}

1012
#[stable(feature = "fused", since = "1.26.0")]
S
Steven Allen 已提交
1013 1014
impl<'a> FusedIterator for Components<'a> {}

A
Aaron Turon 已提交
1015
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1016 1017
impl<'a> cmp::PartialEq for Components<'a> {
    fn eq(&self, other: &Components<'a>) -> bool {
1018
        Iterator::eq(self.clone(), other.clone())
A
Aaron Turon 已提交
1019 1020 1021
    }
}

A
Aaron Turon 已提交
1022
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1023 1024
impl<'a> cmp::Eq for Components<'a> {}

A
Aaron Turon 已提交
1025
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1026 1027
impl<'a> cmp::PartialOrd for Components<'a> {
    fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1028
        Iterator::partial_cmp(self.clone(), other.clone())
A
Aaron Turon 已提交
1029 1030 1031
    }
}

A
Aaron Turon 已提交
1032
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1033 1034
impl<'a> cmp::Ord for Components<'a> {
    fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1035
        Iterator::cmp(self.clone(), other.clone())
A
Aaron Turon 已提交
1036 1037 1038
    }
}

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
/// An iterator over [`Path`] and its ancestors.
///
/// This `struct` is created by the [`ancestors`] method on [`Path`].
/// See its documentation for more.
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// let path = Path::new("/foo/bar");
///
/// for ancestor in path.ancestors() {
///     println!("{}", ancestor.display());
/// }
/// ```
///
/// [`ancestors`]: struct.Path.html#method.ancestors
/// [`Path`]: struct.Path.html
#[derive(Copy, Clone, Debug)]
1059
#[stable(feature = "path_ancestors", since = "1.28.0")]
1060 1061 1062 1063
pub struct Ancestors<'a> {
    next: Option<&'a Path>,
}

1064
#[stable(feature = "path_ancestors", since = "1.28.0")]
1065 1066 1067 1068 1069
impl<'a> Iterator for Ancestors<'a> {
    type Item = &'a Path;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next;
1070
        self.next = next.and_then(Path::parent);
1071 1072 1073 1074
        next
    }
}

1075
#[stable(feature = "path_ancestors", since = "1.28.0")]
1076 1077
impl<'a> FusedIterator for Ancestors<'a> {}

A
Aaron Turon 已提交
1078 1079 1080 1081
////////////////////////////////////////////////////////////////////////////////
// Basic types and traits
////////////////////////////////////////////////////////////////////////////////

G
Guillaume Gomez 已提交
1082
/// An owned, mutable path (akin to [`String`]).
A
Aaron Turon 已提交
1083
///
G
Guillaume Gomez 已提交
1084 1085 1086 1087 1088 1089 1090 1091
/// This type provides methods like [`push`] and [`set_extension`] that mutate
/// the path in place. It also implements [`Deref`] to [`Path`], meaning that
/// all methods on [`Path`] slices are available on `PathBuf` values as well.
///
/// [`String`]: ../string/struct.String.html
/// [`Path`]: struct.Path.html
/// [`push`]: struct.PathBuf.html#method.push
/// [`set_extension`]: struct.PathBuf.html#method.set_extension
O
Oliver Middleton 已提交
1092
/// [`Deref`]: ../ops/trait.Deref.html
A
Aaron Turon 已提交
1093 1094
///
/// More details about the overall approach can be found in
1095
/// the [module documentation](index.html).
A
Aaron Turon 已提交
1096
///
S
Steve Klabnik 已提交
1097
/// # Examples
A
Aaron Turon 已提交
1098
///
1099 1100 1101
/// You can use [`push`] to build up a `PathBuf` from
/// components:
///
1102
/// ```
A
Aaron Turon 已提交
1103 1104
/// use std::path::PathBuf;
///
1105 1106 1107
/// let mut path = PathBuf::new();
///
/// path.push(r"C:\");
A
Aaron Turon 已提交
1108 1109
/// path.push("windows");
/// path.push("system32");
1110
///
A
Aaron Turon 已提交
1111 1112
/// path.set_extension("dll");
/// ```
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
///
/// However, [`push`] is best used for dynamic situations. This is a better way
/// to do this when you know all of the components ahead of time:
///
/// ```
/// use std::path::PathBuf;
///
/// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
/// ```
///
/// We can still do better than this! Since these are all strings, we can use
/// `From::from`:
///
/// ```
/// use std::path::PathBuf;
///
/// let path = PathBuf::from(r"C:\windows\system32.dll");
/// ```
///
/// Which method works best depends on what kind of situation you're in.
1133
#[derive(Clone)]
A
Aaron Turon 已提交
1134
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1135
pub struct PathBuf {
T
Tshepang Lekhonkhobe 已提交
1136
    inner: OsString,
A
Aaron Turon 已提交
1137 1138 1139 1140
}

impl PathBuf {
    fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1141
        unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
A
Aaron Turon 已提交
1142 1143
    }

1144
    /// Allocates an empty `PathBuf`.
G
Guillaume Gomez 已提交
1145 1146 1147 1148 1149 1150 1151 1152
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// let path = PathBuf::new();
    /// ```
A
Aaron Turon 已提交
1153
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1154 1155
    pub fn new() -> PathBuf {
        PathBuf { inner: OsString::new() }
A
Aaron Turon 已提交
1156 1157
    }

G
Guillaume Gomez 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    /// Coerces to a [`Path`] slice.
    ///
    /// [`Path`]: struct.Path.html
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::{Path, PathBuf};
    ///
    /// let p = PathBuf::from("/test");
    /// assert_eq!(Path::new("/test"), p.as_path());
    /// ```
1170 1171 1172 1173 1174
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn as_path(&self) -> &Path {
        self
    }

1175
    /// Extends `self` with `path`.
A
Aaron Turon 已提交
1176 1177 1178 1179 1180 1181 1182
    ///
    /// If `path` is absolute, it replaces the current path.
    ///
    /// On Windows:
    ///
    /// * if `path` has a root but no prefix (e.g. `\windows`), it
    ///   replaces everything except for the prefix (if any) of `self`.
T
Tshepang Lekhonkhobe 已提交
1183
    /// * if `path` has a prefix but no root, it replaces `self`.
1184 1185 1186
    ///
    /// # Examples
    ///
1187 1188
    /// Pushing a relative path extends the existing path:
    ///
1189 1190 1191
    /// ```
    /// use std::path::PathBuf;
    ///
1192
    /// let mut path = PathBuf::from("/tmp");
1193 1194
    /// path.push("file.bk");
    /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1195 1196 1197 1198 1199 1200
    /// ```
    ///
    /// Pushing an absolute path replaces the existing path:
    ///
    /// ```
    /// use std::path::PathBuf;
1201
    ///
1202 1203 1204
    /// let mut path = PathBuf::from("/tmp");
    /// path.push("/etc");
    /// assert_eq!(path, PathBuf::from("/etc"));
1205
    /// ```
A
Aaron Turon 已提交
1206
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1207
    pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1208 1209
        self._push(path.as_ref())
    }
A
Aaron Turon 已提交
1210

1211
    fn _push(&mut self, path: &Path) {
A
Aaron Turon 已提交
1212
        // in general, a separator is needed if the rightmost byte is not a separator
A
Aaron Turon 已提交
1213
        let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
A
Aaron Turon 已提交
1214 1215 1216 1217

        // in the special case of `C:` on Windows, do *not* add a separator
        {
            let comps = self.components();
T
Tshepang Lekhonkhobe 已提交
1218 1219
            if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
               comps.prefix.unwrap().is_drive() {
A
Aaron Turon 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
                need_sep = false
            }
        }

        // absolute `path` replaces `self`
        if path.is_absolute() || path.prefix().is_some() {
            self.as_mut_vec().truncate(0);

        // `path` has a root but no prefix, e.g. `\windows` (Windows only)
        } else if path.has_root() {
            let prefix_len = self.components().prefix_remaining();
            self.as_mut_vec().truncate(prefix_len);

        // `path` is a pure relative path
        } else if need_sep {
A
Alex Crichton 已提交
1235
            self.inner.push(MAIN_SEP_STR);
A
Aaron Turon 已提交
1236 1237
        }

A
Alex Crichton 已提交
1238
        self.inner.push(path);
A
Aaron Turon 已提交
1239 1240
    }

1241
    /// Truncates `self` to [`self.parent`].
A
Aaron Turon 已提交
1242
    ///
1243
    /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
B
Ben S 已提交
1244
    /// Otherwise, returns `true`.
G
Guillaume Gomez 已提交
1245
    ///
1246
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
1247 1248
    /// [`self.parent`]: struct.PathBuf.html#method.parent
    /// [`self.file_name`]: struct.PathBuf.html#method.file_name
G
Guillaume Gomez 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::{Path, PathBuf};
    ///
    /// let mut p = PathBuf::from("/test/test.rs");
    ///
    /// p.pop();
1258
    /// assert_eq!(Path::new("/test"), p);
G
Guillaume Gomez 已提交
1259
    /// p.pop();
1260
    /// assert_eq!(Path::new("/"), p);
G
Guillaume Gomez 已提交
1261
    /// ```
A
Aaron Turon 已提交
1262
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1263 1264 1265 1266 1267 1268
    pub fn pop(&mut self) -> bool {
        match self.parent().map(|p| p.as_u8_slice().len()) {
            Some(len) => {
                self.as_mut_vec().truncate(len);
                true
            }
T
Tshepang Lekhonkhobe 已提交
1269
            None => false,
A
Aaron Turon 已提交
1270 1271 1272
        }
    }

1273
    /// Updates [`self.file_name`] to `file_name`.
A
Aaron Turon 已提交
1274
    ///
1275
    /// If [`self.file_name`] was [`None`], this is equivalent to pushing
A
Aaron Turon 已提交
1276 1277
    /// `file_name`.
    ///
1278 1279 1280 1281
    /// Otherwise it is equivalent to calling [`pop`] and then pushing
    /// `file_name`. The new path will be a sibling of the original path.
    /// (That is, it will have the same parent.)
    ///
1282
    /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1283
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
1284
    /// [`pop`]: struct.PathBuf.html#method.pop
G
Guillaume Gomez 已提交
1285
    ///
A
Aaron Turon 已提交
1286 1287
    /// # Examples
    ///
1288
    /// ```
A
Aaron Turon 已提交
1289
    /// use std::path::PathBuf;
A
Aaron Turon 已提交
1290
    ///
1291
    /// let mut buf = PathBuf::from("/");
A
Aaron Turon 已提交
1292 1293
    /// assert!(buf.file_name() == None);
    /// buf.set_file_name("bar");
1294
    /// assert!(buf == PathBuf::from("/bar"));
A
Aaron Turon 已提交
1295 1296
    /// assert!(buf.file_name().is_some());
    /// buf.set_file_name("baz.txt");
1297
    /// assert!(buf == PathBuf::from("/baz.txt"));
A
Aaron Turon 已提交
1298
    /// ```
A
Aaron Turon 已提交
1299
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1300
    pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1301 1302 1303 1304
        self._set_file_name(file_name.as_ref())
    }

    fn _set_file_name(&mut self, file_name: &OsStr) {
A
Aaron Turon 已提交
1305 1306 1307
        if self.file_name().is_some() {
            let popped = self.pop();
            debug_assert!(popped);
A
Aaron Turon 已提交
1308
        }
1309
        self.push(file_name);
A
Aaron Turon 已提交
1310 1311
    }

1312
    /// Updates [`self.extension`] to `extension`.
G
Guillaume Gomez 已提交
1313
    ///
1314 1315
    /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
    /// returns `true` and updates the extension otherwise.
G
Guillaume Gomez 已提交
1316
    ///
1317 1318
    /// If [`self.extension`] is [`None`], the extension is added; otherwise
    /// it is replaced.
G
Guillaume Gomez 已提交
1319
    ///
1320 1321
    /// [`self.file_name`]: struct.PathBuf.html#method.file_name
    /// [`self.extension`]: struct.PathBuf.html#method.extension
1322
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
G
Guillaume Gomez 已提交
1323 1324 1325 1326 1327
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::{Path, PathBuf};
A
Aaron Turon 已提交
1328
    ///
G
Guillaume Gomez 已提交
1329
    /// let mut p = PathBuf::from("/feel/the");
A
Aaron Turon 已提交
1330
    ///
G
Guillaume Gomez 已提交
1331 1332 1333 1334 1335 1336
    /// p.set_extension("force");
    /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
    ///
    /// p.set_extension("dark_side");
    /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
    /// ```
A
Aaron Turon 已提交
1337
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1338
    pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1339 1340 1341 1342
        self._set_extension(extension.as_ref())
    }

    fn _set_extension(&mut self, extension: &OsStr) -> bool {
T
Tshepang Lekhonkhobe 已提交
1343 1344 1345
        if self.file_name().is_none() {
            return false;
        }
A
Aaron Turon 已提交
1346 1347 1348

        let mut stem = match self.file_stem() {
            Some(stem) => stem.to_os_string(),
A
Aaron Turon 已提交
1349
            None => OsString::new(),
A
Aaron Turon 已提交
1350 1351
        };

1352
        if !os_str_as_u8_slice(extension).is_empty() {
A
Alex Crichton 已提交
1353 1354
            stem.push(".");
            stem.push(extension);
A
Aaron Turon 已提交
1355 1356 1357 1358 1359
        }
        self.set_file_name(&stem);

        true
    }
A
Aaron Turon 已提交
1360

G
Guillaume Gomez 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
    ///
    /// [`OsString`]: ../ffi/struct.OsString.html
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// let p = PathBuf::from("/the/head");
    /// let os_str = p.into_os_string();
    /// ```
A
Aaron Turon 已提交
1373
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1374 1375 1376
    pub fn into_os_string(self) -> OsString {
        self.inner
    }
1377

1378 1379 1380 1381
    /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
    ///
    /// [`Box`]: ../../std/boxed/struct.Box.html
    /// [`Path`]: struct.Path.html
1382
    #[stable(feature = "into_boxed_path", since = "1.20.0")]
1383
    pub fn into_boxed_path(self) -> Box<Path> {
1384 1385
        let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
        unsafe { Box::from_raw(rw) }
1386 1387 1388 1389 1390 1391
    }
}

#[stable(feature = "box_from_path", since = "1.17.0")]
impl<'a> From<&'a Path> for Box<Path> {
    fn from(path: &'a Path) -> Box<Path> {
1392 1393
        let boxed: Box<OsStr> = path.inner.into();
        let rw = Box::into_raw(boxed) as *mut Path;
1394
        unsafe { Box::from_raw(rw) }
1395 1396 1397
    }
}

1398
#[stable(feature = "path_buf_from_box", since = "1.18.0")]
C
Clar Charr 已提交
1399
impl From<Box<Path>> for PathBuf {
C
Clar Charr 已提交
1400 1401 1402 1403 1404
    fn from(boxed: Box<Path>) -> PathBuf {
        boxed.into_path_buf()
    }
}

1405
#[stable(feature = "box_from_path_buf", since = "1.20.0")]
C
Clar Charr 已提交
1406 1407 1408
impl From<PathBuf> for Box<Path> {
    fn from(p: PathBuf) -> Box<Path> {
        p.into_boxed_path()
C
Clar Charr 已提交
1409 1410 1411
    }
}

1412 1413 1414 1415 1416 1417 1418 1419
#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
impl Clone for Box<Path> {
    #[inline]
    fn clone(&self) -> Self {
        self.to_path_buf().into_boxed_path()
    }
}

A
Aaron Turon 已提交
1420
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1421 1422 1423
impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
    fn from(s: &'a T) -> PathBuf {
        PathBuf::from(s.as_ref().to_os_string())
A
Aaron Turon 已提交
1424 1425 1426 1427
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1428 1429 1430
impl From<OsString> for PathBuf {
    fn from(s: OsString) -> PathBuf {
        PathBuf { inner: s }
A
Aaron Turon 已提交
1431 1432 1433
    }
}

1434 1435 1436 1437 1438 1439 1440
#[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
impl From<PathBuf> for OsString {
    fn from(path_buf : PathBuf) -> OsString {
        path_buf.inner
    }
}

A
Aaron Turon 已提交
1441 1442 1443 1444 1445 1446 1447
#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for PathBuf {
    fn from(s: String) -> PathBuf {
        PathBuf::from(OsString::from(s))
    }
}

S
Simon Sapin 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456
#[stable(feature = "path_from_str", since = "1.26.0")]
impl FromStr for PathBuf {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(PathBuf::from(s))
    }
}

A
Aaron Turon 已提交
1457 1458
#[stable(feature = "rust1", since = "1.0.0")]
impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1459
    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
A
Aaron Turon 已提交
1460
        let mut buf = PathBuf::new();
A
Aaron Turon 已提交
1461 1462 1463 1464 1465
        buf.extend(iter);
        buf
    }
}

A
Aaron Turon 已提交
1466
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1467
impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1468
    fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
A
Aaron Turon 已提交
1469
        for p in iter {
1470
            self.push(p.as_ref())
A
Aaron Turon 已提交
1471 1472 1473 1474
        }
    }
}

A
Aaron Turon 已提交
1475
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1476
impl fmt::Debug for PathBuf {
A
Andre Bogus 已提交
1477
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
A
Aaron Turon 已提交
1478 1479 1480 1481
        fmt::Debug::fmt(&**self, formatter)
    }
}

A
Aaron Turon 已提交
1482
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1483 1484 1485 1486
impl ops::Deref for PathBuf {
    type Target = Path;

    fn deref(&self) -> &Path {
1487
        Path::new(&self.inner)
A
Aaron Turon 已提交
1488 1489 1490
    }
}

A
Aaron Turon 已提交
1491
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1492 1493 1494
impl Borrow<Path> for PathBuf {
    fn borrow(&self) -> &Path {
        self.deref()
A
Aaron Turon 已提交
1495 1496 1497
    }
}

1498
#[stable(feature = "default_for_pathbuf", since = "1.17.0")]
A
Aaron Power 已提交
1499 1500 1501 1502 1503 1504
impl Default for PathBuf {
    fn default() -> Self {
        PathBuf::new()
    }
}

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
#[stable(feature = "cow_from_path", since = "1.6.0")]
impl<'a> From<&'a Path> for Cow<'a, Path> {
    #[inline]
    fn from(s: &'a Path) -> Cow<'a, Path> {
        Cow::Borrowed(s)
    }
}

#[stable(feature = "cow_from_path", since = "1.6.0")]
impl<'a> From<PathBuf> for Cow<'a, Path> {
    #[inline]
    fn from(s: PathBuf) -> Cow<'a, Path> {
        Cow::Owned(s)
    }
}

G
George Burton 已提交
1521
#[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1522 1523 1524 1525 1526 1527 1528
impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
    #[inline]
    fn from(p: &'a PathBuf) -> Cow<'a, Path> {
        Cow::Borrowed(p.as_path())
    }
}

G
George Burton 已提交
1529
#[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
G
George Burton 已提交
1530 1531 1532 1533 1534 1535 1536
impl<'a> From<Cow<'a, Path>> for PathBuf {
    #[inline]
    fn from(p: Cow<'a, Path>) -> Self {
        p.into_owned()
    }
}

1537
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1538 1539 1540 1541 1542 1543 1544 1545
impl From<PathBuf> for Arc<Path> {
    #[inline]
    fn from(s: PathBuf) -> Arc<Path> {
        let arc: Arc<OsStr> = Arc::from(s.into_os_string());
        unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
    }
}

1546
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1547 1548 1549 1550 1551 1552 1553 1554
impl<'a> From<&'a Path> for Arc<Path> {
    #[inline]
    fn from(s: &Path) -> Arc<Path> {
        let arc: Arc<OsStr> = Arc::from(s.as_os_str());
        unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
    }
}

1555
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1556 1557 1558 1559 1560 1561 1562 1563
impl From<PathBuf> for Rc<Path> {
    #[inline]
    fn from(s: PathBuf) -> Rc<Path> {
        let rc: Rc<OsStr> = Rc::from(s.into_os_string());
        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
    }
}

1564
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1565 1566 1567 1568 1569 1570 1571 1572
impl<'a> From<&'a Path> for Rc<Path> {
    #[inline]
    fn from(s: &Path) -> Rc<Path> {
        let rc: Rc<OsStr> = Rc::from(s.as_os_str());
        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
    }
}

A
Aaron Turon 已提交
1573
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1574 1575
impl ToOwned for Path {
    type Owned = PathBuf;
T
Tshepang Lekhonkhobe 已提交
1576 1577 1578
    fn to_owned(&self) -> PathBuf {
        self.to_path_buf()
    }
1579 1580 1581
    fn clone_into(&self, target: &mut PathBuf) {
        self.inner.clone_into(&mut target.inner);
    }
A
Aaron Turon 已提交
1582 1583
}

A
Aaron Turon 已提交
1584
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1585 1586 1587 1588 1589 1590
impl cmp::PartialEq for PathBuf {
    fn eq(&self, other: &PathBuf) -> bool {
        self.components() == other.components()
    }
}

1591 1592 1593 1594 1595 1596 1597
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for PathBuf {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.as_path().hash(h)
    }
}

A
Aaron Turon 已提交
1598
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1599 1600
impl cmp::Eq for PathBuf {}

A
Aaron Turon 已提交
1601
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1602 1603
impl cmp::PartialOrd for PathBuf {
    fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1604
        self.components().partial_cmp(other.components())
A
Aaron Turon 已提交
1605 1606 1607
    }
}

A
Aaron Turon 已提交
1608
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1609 1610
impl cmp::Ord for PathBuf {
    fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1611
        self.components().cmp(other.components())
A
Aaron Turon 已提交
1612 1613 1614
    }
}

A
Aaron Turon 已提交
1615
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1616 1617 1618 1619 1620 1621
impl AsRef<OsStr> for PathBuf {
    fn as_ref(&self) -> &OsStr {
        &self.inner[..]
    }
}

G
Guillaume Gomez 已提交
1622
/// A slice of a path (akin to [`str`]).
A
Aaron Turon 已提交
1623 1624
///
/// This type supports a number of operations for inspecting a path, including
1625 1626 1627
/// breaking the path into its components (separated by `/` on Unix and by either
/// `/` or `\` on Windows), extracting the file name, determining whether the path
/// is absolute, and so on.
A
Aaron Turon 已提交
1628
///
1629
/// This is an *unsized* type, meaning that it must always be used behind a
D
Duncan 已提交
1630 1631
/// pointer like `&` or [`Box`]. For an owned version of this type,
/// see [`PathBuf`].
G
Guillaume Gomez 已提交
1632 1633 1634
///
/// [`str`]: ../primitive.str.html
/// [`Box`]: ../boxed/struct.Box.html
D
Duncan 已提交
1635 1636 1637
/// [`PathBuf`]: struct.PathBuf.html
///
/// More details about the overall approach can be found in
1638
/// the [module documentation](index.html).
A
Aaron Turon 已提交
1639
///
S
Steve Klabnik 已提交
1640
/// # Examples
A
Aaron Turon 已提交
1641
///
1642
/// ```
A
Aaron Turon 已提交
1643
/// use std::path::Path;
1644
/// use std::ffi::OsStr;
A
Aaron Turon 已提交
1645
///
1646 1647
/// // Note: this example does work on Windows
/// let path = Path::new("./foo/bar.txt");
1648 1649
///
/// let parent = path.parent();
1650
/// assert_eq!(parent, Some(Path::new("./foo")));
1651 1652 1653 1654
///
/// let file_stem = path.file_stem();
/// assert_eq!(file_stem, Some(OsStr::new("bar")));
///
A
Aaron Turon 已提交
1655
/// let extension = path.extension();
1656
/// assert_eq!(extension, Some(OsStr::new("txt")));
A
Aaron Turon 已提交
1657
/// ```
A
Aaron Turon 已提交
1658
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1659
pub struct Path {
T
Tshepang Lekhonkhobe 已提交
1660
    inner: OsStr,
A
Aaron Turon 已提交
1661 1662
}

1663 1664 1665 1666 1667
/// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
/// was not found.
///
/// This `struct` is created by the [`strip_prefix`] method on [`Path`].
/// See its documentation for more.
1668
///
1669 1670
/// [`strip_prefix`]: struct.Path.html#method.strip_prefix
/// [`Path`]: struct.Path.html
1671 1672 1673 1674
#[derive(Debug, Clone, PartialEq, Eq)]
#[stable(since = "1.7.0", feature = "strip_prefix")]
pub struct StripPrefixError(());

A
Aaron Turon 已提交
1675 1676 1677 1678
impl Path {
    // The following (private!) function allows construction of a path from a u8
    // slice, which is only safe when it is known to follow the OsStr encoding.
    unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1679
        Path::new(u8_slice_as_os_str(s))
A
Aaron Turon 已提交
1680 1681 1682
    }
    // The following (private!) function reveals the byte encoding used for OsStr.
    fn as_u8_slice(&self) -> &[u8] {
1683
        os_str_as_u8_slice(&self.inner)
A
Aaron Turon 已提交
1684 1685
    }

1686
    /// Directly wraps a string slice as a `Path` slice.
A
Aaron Turon 已提交
1687 1688
    ///
    /// This is a cost-free conversion.
1689 1690 1691 1692 1693 1694 1695 1696
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// Path::new("foo.txt");
    /// ```
N
Nick Hamann 已提交
1697 1698
    ///
    /// You can create `Path`s from `String`s, or even other `Path`s:
N
Nick Hamann 已提交
1699
    ///
N
Nick Hamann 已提交
1700
    /// ```
M
Manish Goregaokar 已提交
1701 1702
    /// use std::path::Path;
    ///
1703 1704 1705 1706
    /// let string = String::from("foo.txt");
    /// let from_string = Path::new(&string);
    /// let from_path = Path::new(&from_string);
    /// assert_eq!(from_string, from_path);
1707
    /// ```
A
Aaron Turon 已提交
1708
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1709
    pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1710
        unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
A
Aaron Turon 已提交
1711 1712
    }

G
Guillaume Gomez 已提交
1713 1714 1715
    /// Yields the underlying [`OsStr`] slice.
    ///
    /// [`OsStr`]: ../ffi/struct.OsStr.html
1716 1717 1718 1719 1720 1721 1722
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let os_str = Path::new("foo.txt").as_os_str();
1723
    /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1724
    /// ```
A
Aaron Turon 已提交
1725 1726 1727
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn as_os_str(&self) -> &OsStr {
        &self.inner
A
Aaron Turon 已提交
1728 1729
    }

G
Guillaume Gomez 已提交
1730
    /// Yields a [`&str`] slice if the `Path` is valid unicode.
A
Aaron Turon 已提交
1731 1732
    ///
    /// This conversion may entail doing a check for UTF-8 validity.
1733
    ///
G
Guillaume Gomez 已提交
1734 1735
    /// [`&str`]: ../primitive.str.html
    ///
1736 1737 1738 1739 1740
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
1741 1742
    /// let path = Path::new("foo.txt");
    /// assert_eq!(path.to_str(), Some("foo.txt"));
1743
    /// ```
A
Aaron Turon 已提交
1744
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1745 1746 1747 1748
    pub fn to_str(&self) -> Option<&str> {
        self.inner.to_str()
    }

G
Guillaume Gomez 已提交
1749
    /// Converts a `Path` to a [`Cow<str>`].
A
Aaron Turon 已提交
1750
    ///
1751 1752
    /// Any non-Unicode sequences are replaced with
    /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1753
    ///
G
Guillaume Gomez 已提交
1754
    /// [`Cow<str>`]: ../borrow/enum.Cow.html
1755
    /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
G
Guillaume Gomez 已提交
1756
    ///
1757 1758
    /// # Examples
    ///
1759 1760
    /// Calling `to_string_lossy` on a `Path` with valid unicode:
    ///
1761 1762 1763
    /// ```
    /// use std::path::Path;
    ///
1764 1765
    /// let path = Path::new("foo.txt");
    /// assert_eq!(path.to_string_lossy(), "foo.txt");
1766
    /// ```
1767
    ///
P
Petr Zemek 已提交
1768
    /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1769
    /// have returned `"fo�.txt"`.
A
Aaron Turon 已提交
1770
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1771
    pub fn to_string_lossy(&self) -> Cow<str> {
A
Aaron Turon 已提交
1772 1773 1774
        self.inner.to_string_lossy()
    }

G
Guillaume Gomez 已提交
1775 1776 1777
    /// Converts a `Path` to an owned [`PathBuf`].
    ///
    /// [`PathBuf`]: struct.PathBuf.html
1778 1779 1780 1781 1782 1783
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
1784 1785
    /// let path_buf = Path::new("foo.txt").to_path_buf();
    /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1786
    /// ```
1787
    #[rustc_conversion_suggestion]
A
Aaron Turon 已提交
1788
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1789
    pub fn to_path_buf(&self) -> PathBuf {
A
Aaron Turon 已提交
1790
        PathBuf::from(self.inner.to_os_string())
A
Aaron Turon 已提交
1791 1792
    }

1793 1794
    /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
    /// the current directory.
A
Aaron Turon 已提交
1795 1796
    ///
    /// * On Unix, a path is absolute if it starts with the root, so
1797
    /// `is_absolute` and [`has_root`] are equivalent.
A
Aaron Turon 已提交
1798 1799
    ///
    /// * On Windows, a path is absolute if it has a prefix and starts with the
1800
    /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1801 1802 1803 1804 1805 1806
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
1807
    /// assert!(!Path::new("foo.txt").is_absolute());
1808
    /// ```
1809 1810
    ///
    /// [`has_root`]: #method.has_root
A
Aaron Turon 已提交
1811
    #[stable(feature = "rust1", since = "1.0.0")]
1812
    #[allow(deprecated)]
A
Aaron Turon 已提交
1813
    pub fn is_absolute(&self) -> bool {
1814
        if cfg!(target_os = "redox") {
1815
            // FIXME: Allow Redox prefixes
1816 1817 1818
            self.has_root() || has_redox_scheme(self.as_u8_slice())
        } else {
            self.has_root() && (cfg!(unix) || self.prefix().is_some())
1819
        }
A
Aaron Turon 已提交
1820 1821
    }

1822
    /// Returns `true` if the `Path` is relative, i.e. not absolute.
1823 1824
    ///
    /// See [`is_absolute`]'s documentation for more details.
1825 1826 1827 1828 1829 1830 1831 1832
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// assert!(Path::new("foo.txt").is_relative());
    /// ```
1833 1834
    ///
    /// [`is_absolute`]: #method.is_absolute
A
Aaron Turon 已提交
1835
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1836 1837 1838 1839
    pub fn is_relative(&self) -> bool {
        !self.is_absolute()
    }

A
Alex Crichton 已提交
1840
    fn prefix(&self) -> Option<Prefix> {
A
Aaron Turon 已提交
1841
        self.components().prefix
A
Aaron Turon 已提交
1842 1843
    }

1844
    /// Returns `true` if the `Path` has a root.
A
Aaron Turon 已提交
1845 1846 1847 1848
    ///
    /// * On Unix, a path has a root if it begins with `/`.
    ///
    /// * On Windows, a path has a root if it:
F
Typo  
Felix Rabe 已提交
1849
    ///     * has no prefix and begins with a separator, e.g. `\windows`
A
Aaron Turon 已提交
1850 1851
    ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
    ///     * has any non-disk prefix, e.g. `\\server\share`
1852 1853 1854 1855 1856 1857 1858 1859
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// assert!(Path::new("/etc/passwd").has_root());
    /// ```
A
Aaron Turon 已提交
1860
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1861
    pub fn has_root(&self) -> bool {
T
Tshepang Lekhonkhobe 已提交
1862
        self.components().has_root()
A
Aaron Turon 已提交
1863 1864
    }

1865
    /// Returns the `Path` without its final component, if there is one.
A
Aaron Turon 已提交
1866
    ///
1867 1868 1869
    /// Returns [`None`] if the path terminates in a root or prefix.
    ///
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
A
Aaron Turon 已提交
1870 1871 1872
    ///
    /// # Examples
    ///
1873
    /// ```
A
Aaron Turon 已提交
1874 1875 1876
    /// use std::path::Path;
    ///
    /// let path = Path::new("/foo/bar");
1877 1878
    /// let parent = path.parent().unwrap();
    /// assert_eq!(parent, Path::new("/foo"));
1879
    ///
1880 1881 1882
    /// let grand_parent = parent.parent().unwrap();
    /// assert_eq!(grand_parent, Path::new("/"));
    /// assert_eq!(grand_parent.parent(), None);
A
Aaron Turon 已提交
1883
    /// ```
A
Aaron Turon 已提交
1884
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1885 1886 1887
    pub fn parent(&self) -> Option<&Path> {
        let mut comps = self.components();
        let comp = comps.next_back();
T
Tshepang Lekhonkhobe 已提交
1888 1889 1890 1891 1892 1893 1894
        comp.and_then(|p| {
            match p {
                Component::Normal(_) |
                Component::CurDir |
                Component::ParentDir => Some(comps.as_path()),
                _ => None,
            }
A
Aaron Turon 已提交
1895
        })
A
Aaron Turon 已提交
1896 1897
    }

1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
    /// Produces an iterator over `Path` and its ancestors.
    ///
    /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
    /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
    /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
    /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
    /// namely `&self`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let mut ancestors = Path::new("/foo/bar").ancestors();
    /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
    /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
    /// assert_eq!(ancestors.next(), Some(Path::new("/")));
    /// assert_eq!(ancestors.next(), None);
    /// ```
    ///
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
    /// [`parent`]: struct.Path.html#method.parent
1920
    #[stable(feature = "path_ancestors", since = "1.28.0")]
M
Mazdak Farrokhzad 已提交
1921
    pub const fn ancestors(&self) -> Ancestors {
1922 1923 1924 1925 1926
        Ancestors {
            next: Some(&self),
        }
    }

1927 1928 1929 1930
    /// Returns the final component of the `Path`, if there is one.
    ///
    /// If the path is a normal file, this is the file name. If it's the path of a directory, this
    /// is the directory name.
A
Aaron Turon 已提交
1931
    ///
1932
    /// Returns [`None`] if the path terminates in `..`.
1933 1934
    ///
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
1935 1936 1937 1938 1939
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
1940
    /// use std::ffi::OsStr;
1941
    ///
1942 1943
    /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
    /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
G
ggomez 已提交
1944 1945 1946
    /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
    /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
    /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1947
    /// assert_eq!(None, Path::new("/").file_name());
G
ggomez 已提交
1948
    /// ```
A
Aaron Turon 已提交
1949
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1950
    pub fn file_name(&self) -> Option<&OsStr> {
T
Tshepang Lekhonkhobe 已提交
1951 1952 1953 1954 1955
        self.components().next_back().and_then(|p| {
            match p {
                Component::Normal(p) => Some(p.as_ref()),
                _ => None,
            }
A
Aaron Turon 已提交
1956 1957 1958
        })
    }

1959 1960
    /// Returns a path that, when joined onto `base`, yields `self`.
    ///
G
Gleb Kozyrev 已提交
1961 1962
    /// # Errors
    ///
1963 1964 1965 1966 1967
    /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
    /// returns `false`), returns [`Err`].
    ///
    /// [`starts_with`]: #method.starts_with
    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
G
Guillaume Gomez 已提交
1968 1969 1970 1971
    ///
    /// # Examples
    ///
    /// ```
1972
    /// use std::path::{Path, PathBuf};
G
Guillaume Gomez 已提交
1973 1974 1975
    ///
    /// let path = Path::new("/test/haha/foo.txt");
    ///
1976
    /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
G
Guillaume Gomez 已提交
1977
    /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1978 1979 1980
    /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
    /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
    /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
G
Guillaume Gomez 已提交
1981 1982
    /// assert_eq!(path.strip_prefix("test").is_ok(), false);
    /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1983 1984 1985
    ///
    /// let prefix = PathBuf::from("/test/");
    /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
G
Guillaume Gomez 已提交
1986
    /// ```
1987
    #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1988 1989
    pub fn strip_prefix<P>(&self, base: P)
                           -> Result<&Path, StripPrefixError>
1990 1991 1992
        where P: AsRef<Path>
    {
        self._strip_prefix(base.as_ref())
1993 1994
    }

1995 1996
    fn _strip_prefix(&self, base: &Path)
                     -> Result<&Path, StripPrefixError> {
1997 1998 1999
        iter_after(self.components(), base.components())
            .map(|c| c.as_path())
            .ok_or(StripPrefixError(()))
A
Aaron Turon 已提交
2000 2001 2002
    }

    /// Determines whether `base` is a prefix of `self`.
2003
    ///
2004 2005
    /// Only considers whole path components to match.
    ///
2006 2007 2008 2009 2010 2011 2012 2013
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let path = Path::new("/etc/passwd");
    ///
    /// assert!(path.starts_with("/etc"));
2014 2015 2016
    /// assert!(path.starts_with("/etc/"));
    /// assert!(path.starts_with("/etc/passwd"));
    /// assert!(path.starts_with("/etc/passwd/"));
2017 2018
    ///
    /// assert!(!path.starts_with("/e"));
2019
    /// ```
A
Aaron Turon 已提交
2020
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2021
    pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2022 2023 2024 2025 2026
        self._starts_with(base.as_ref())
    }

    fn _starts_with(&self, base: &Path) -> bool {
        iter_after(self.components(), base.components()).is_some()
A
Aaron Turon 已提交
2027 2028
    }

2029
    /// Determines whether `child` is a suffix of `self`.
2030
    ///
2031 2032
    /// Only considers whole path components to match.
    ///
2033 2034 2035 2036 2037 2038 2039 2040 2041
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let path = Path::new("/etc/passwd");
    ///
    /// assert!(path.ends_with("passwd"));
    /// ```
A
Aaron Turon 已提交
2042
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2043
    pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2044 2045 2046 2047 2048
        self._ends_with(child.as_ref())
    }

    fn _ends_with(&self, child: &Path) -> bool {
        iter_after(self.components().rev(), child.components().rev()).is_some()
A
Aaron Turon 已提交
2049 2050
    }

2051
    /// Extracts the stem (non-extension) portion of [`self.file_name`].
G
Guillaume Gomez 已提交
2052
    ///
2053
    /// [`self.file_name`]: struct.Path.html#method.file_name
A
Aaron Turon 已提交
2054 2055 2056
    ///
    /// The stem is:
    ///
2057
    /// * [`None`], if there is no file name;
A
Aaron Turon 已提交
2058 2059 2060
    /// * The entire file name if there is no embedded `.`;
    /// * The entire file name if the file name begins with `.` and has no other `.`s within;
    /// * Otherwise, the portion of the file name before the final `.`
2061
    ///
2062 2063
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
    ///
2064 2065 2066 2067 2068 2069 2070 2071 2072
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let path = Path::new("foo.rs");
    ///
    /// assert_eq!("foo", path.file_stem().unwrap());
    /// ```
A
Aaron Turon 已提交
2073
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2074 2075 2076 2077
    pub fn file_stem(&self) -> Option<&OsStr> {
        self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
    }

2078
    /// Extracts the extension of [`self.file_name`], if possible.
G
Guillaume Gomez 已提交
2079
    ///
A
Aaron Turon 已提交
2080 2081
    /// The extension is:
    ///
2082 2083 2084
    /// * [`None`], if there is no file name;
    /// * [`None`], if there is no embedded `.`;
    /// * [`None`], if the file name begins with `.` and has no other `.`s within;
A
Aaron Turon 已提交
2085
    /// * Otherwise, the portion of the file name after the final `.`
2086
    ///
2087
    /// [`self.file_name`]: struct.Path.html#method.file_name
2088 2089
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
    ///
2090 2091 2092 2093 2094 2095 2096 2097 2098
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let path = Path::new("foo.rs");
    ///
    /// assert_eq!("rs", path.extension().unwrap());
    /// ```
A
Aaron Turon 已提交
2099
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2100 2101 2102 2103
    pub fn extension(&self) -> Option<&OsStr> {
        self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
    }

G
Guillaume Gomez 已提交
2104 2105 2106
    /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
    ///
    /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
A
Aaron Turon 已提交
2107
    ///
G
Guillaume Gomez 已提交
2108 2109
    /// [`PathBuf`]: struct.PathBuf.html
    /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2110 2111 2112 2113
    ///
    /// # Examples
    ///
    /// ```
2114
    /// use std::path::{Path, PathBuf};
2115
    ///
2116
    /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2117
    /// ```
A
Aaron Turon 已提交
2118
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2119
    pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2120 2121 2122 2123
        self._join(path.as_ref())
    }

    fn _join(&self, path: &Path) -> PathBuf {
A
Aaron Turon 已提交
2124 2125 2126 2127 2128
        let mut buf = self.to_path_buf();
        buf.push(path);
        buf
    }

G
Guillaume Gomez 已提交
2129
    /// Creates an owned [`PathBuf`] like `self` but with the given file name.
A
Aaron Turon 已提交
2130
    ///
G
Guillaume Gomez 已提交
2131 2132 2133 2134
    /// See [`PathBuf::set_file_name`] for more details.
    ///
    /// [`PathBuf`]: struct.PathBuf.html
    /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2135 2136 2137 2138
    ///
    /// # Examples
    ///
    /// ```
2139
    /// use std::path::{Path, PathBuf};
2140
    ///
2141 2142
    /// let path = Path::new("/tmp/foo.txt");
    /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2143 2144 2145
    ///
    /// let path = Path::new("/tmp");
    /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2146
    /// ```
A
Aaron Turon 已提交
2147
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2148
    pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2149 2150 2151 2152
        self._with_file_name(file_name.as_ref())
    }

    fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
A
Aaron Turon 已提交
2153 2154 2155 2156 2157
        let mut buf = self.to_path_buf();
        buf.set_file_name(file_name);
        buf
    }

G
Guillaume Gomez 已提交
2158 2159 2160
    /// Creates an owned [`PathBuf`] like `self` but with the given extension.
    ///
    /// See [`PathBuf::set_extension`] for more details.
A
Aaron Turon 已提交
2161
    ///
G
Guillaume Gomez 已提交
2162 2163
    /// [`PathBuf`]: struct.PathBuf.html
    /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2164 2165 2166 2167
    ///
    /// # Examples
    ///
    /// ```
A
Alex Crichton 已提交
2168
    /// use std::path::{Path, PathBuf};
2169
    ///
2170 2171
    /// let path = Path::new("foo.rs");
    /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2172
    /// ```
A
Aaron Turon 已提交
2173
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2174
    pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2175 2176 2177 2178
        self._with_extension(extension.as_ref())
    }

    fn _with_extension(&self, extension: &OsStr) -> PathBuf {
A
Aaron Turon 已提交
2179 2180 2181 2182 2183
        let mut buf = self.to_path_buf();
        buf.set_extension(extension);
        buf
    }

2184 2185 2186 2187
    /// Produces an iterator over the [`Component`]s of the path.
    ///
    /// When parsing the path, there is a small amount of normalization:
    ///
L
lukaramu 已提交
2188
    /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2189 2190
    ///   `a` and `b` as components.
    ///
B
Bruce Mitchener 已提交
2191
    /// * Occurrences of `.` are normalized away, except if they are at the
2192 2193 2194 2195 2196 2197 2198
    ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
    ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
    ///   an additional [`CurDir`] component.
    ///
    /// Note that no other normalization takes place; in particular, `a/c`
    /// and `a/b/../c` are distinct, to account for the possibility that `b`
    /// is a symbolic link (so its parent isn't `a`).
2199 2200 2201 2202
    ///
    /// # Examples
    ///
    /// ```
2203 2204
    /// use std::path::{Path, Component};
    /// use std::ffi::OsStr;
2205
    ///
2206
    /// let mut components = Path::new("/tmp/foo.txt").components();
2207
    ///
2208 2209 2210 2211
    /// assert_eq!(components.next(), Some(Component::RootDir));
    /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
    /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
    /// assert_eq!(components.next(), None)
2212
    /// ```
2213 2214 2215
    ///
    /// [`Component`]: enum.Component.html
    /// [`CurDir`]: enum.Component.html#variant.CurDir
A
Aaron Turon 已提交
2216
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2217 2218 2219 2220
    pub fn components(&self) -> Components {
        let prefix = parse_prefix(self.as_os_str());
        Components {
            path: self.as_u8_slice(),
2221
            prefix,
2222 2223
            has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
                               has_redox_scheme(self.as_u8_slice()),
A
Aaron Turon 已提交
2224
            front: State::Prefix,
A
Aaron Turon 已提交
2225
            back: State::Body,
A
Aaron Turon 已提交
2226 2227 2228
        }
    }

2229 2230 2231 2232 2233
    /// Produces an iterator over the path's components viewed as [`OsStr`]
    /// slices.
    ///
    /// For more information about the particulars of how the path is separated
    /// into components, see [`components`].
G
Guillaume Gomez 已提交
2234
    ///
2235
    /// [`components`]: #method.components
G
Guillaume Gomez 已提交
2236
    /// [`OsStr`]: ../ffi/struct.OsStr.html
2237 2238 2239 2240
    ///
    /// # Examples
    ///
    /// ```
2241
    /// use std::path::{self, Path};
2242
    /// use std::ffi::OsStr;
2243
    ///
2244
    /// let mut it = Path::new("/tmp/foo.txt").iter();
2245
    /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2246 2247 2248
    /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
    /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
    /// assert_eq!(it.next(), None)
2249
    /// ```
A
Aaron Turon 已提交
2250
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2251 2252 2253 2254
    pub fn iter(&self) -> Iter {
        Iter { inner: self.components() }
    }

G
Guillaume Gomez 已提交
2255
    /// Returns an object that implements [`Display`] for safely printing paths
A
Aaron Turon 已提交
2256
    /// that may contain non-Unicode data.
2257
    ///
G
Guillaume Gomez 已提交
2258 2259
    /// [`Display`]: ../fmt/trait.Display.html
    ///
2260 2261 2262 2263 2264 2265 2266 2267 2268
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    ///
    /// let path = Path::new("/tmp/foo.rs");
    ///
    /// println!("{}", path.display());
    /// ```
A
Aaron Turon 已提交
2269
    #[stable(feature = "rust1", since = "1.0.0")]
M
Mazdak Farrokhzad 已提交
2270
    pub const fn display(&self) -> Display {
A
Aaron Turon 已提交
2271 2272
        Display { path: self }
    }
2273

2274
    /// Queries the file system to get information about a file, directory, etc.
2275
    ///
2276 2277
    /// This function will traverse symbolic links to query information about the
    /// destination file.
2278
    ///
2279 2280 2281
    /// This is an alias to [`fs::metadata`].
    ///
    /// [`fs::metadata`]: ../fs/fn.metadata.html
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    ///
    /// let path = Path::new("/Minas/tirith");
    /// let metadata = path.metadata().expect("metadata call failed");
    /// println!("{:?}", metadata.file_type());
    /// ```
2292 2293 2294 2295 2296
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn metadata(&self) -> io::Result<fs::Metadata> {
        fs::metadata(self)
    }

2297
    /// Queries the metadata about a file without following symlinks.
2298
    ///
2299 2300 2301
    /// This is an alias to [`fs::symlink_metadata`].
    ///
    /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    ///
    /// let path = Path::new("/Minas/tirith");
    /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
    /// println!("{:?}", metadata.file_type());
    /// ```
2312 2313 2314 2315 2316
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
        fs::symlink_metadata(self)
    }

2317 2318
    /// Returns the canonical, absolute form of the path with all intermediate
    /// components normalized and symbolic links resolved.
2319
    ///
2320 2321 2322
    /// This is an alias to [`fs::canonicalize`].
    ///
    /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2323 2324 2325 2326 2327 2328 2329 2330 2331
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::{Path, PathBuf};
    ///
    /// let path = Path::new("/foo/test/../test/bar.rs");
    /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
    /// ```
2332 2333 2334 2335 2336
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn canonicalize(&self) -> io::Result<PathBuf> {
        fs::canonicalize(self)
    }

2337
    /// Reads a symbolic link, returning the file that the link points to.
2338
    ///
2339 2340 2341
    /// This is an alias to [`fs::read_link`].
    ///
    /// [`fs::read_link`]: ../fs/fn.read_link.html
2342 2343 2344 2345 2346 2347 2348 2349 2350
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    ///
    /// let path = Path::new("/laputa/sky_castle.rs");
    /// let path_link = path.read_link().expect("read_link call failed");
    /// ```
2351 2352 2353 2354 2355
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn read_link(&self) -> io::Result<PathBuf> {
        fs::read_link(self)
    }

2356 2357
    /// Returns an iterator over the entries within a directory.
    ///
G
Guillaume Gomez 已提交
2358 2359
    /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
    /// errors may be encountered after an iterator is initially constructed.
2360
    ///
2361 2362
    /// This is an alias to [`fs::read_dir`].
    ///
G
Guillaume Gomez 已提交
2363 2364
    /// [`io::Result`]: ../io/type.Result.html
    /// [`DirEntry`]: ../fs/struct.DirEntry.html
2365
    /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    ///
    /// let path = Path::new("/laputa");
    /// for entry in path.read_dir().expect("read_dir call failed") {
    ///     if let Ok(entry) = entry {
    ///         println!("{:?}", entry.path());
    ///     }
    /// }
    /// ```
2379 2380 2381 2382 2383
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
        fs::read_dir(self)
    }

2384 2385 2386 2387 2388
    /// Returns whether the path points at an existing entity.
    ///
    /// This function will traverse symbolic links to query information about the
    /// destination file. In case of broken symbolic links this will return `false`.
    ///
2389 2390 2391
    /// If you cannot access the directory containing the file, e.g. because of a
    /// permission error, this will return `false`.
    ///
2392 2393 2394 2395 2396 2397
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
    /// ```
2398 2399 2400 2401 2402 2403 2404
    ///
    /// # See Also
    ///
    /// This is a convenience function that coerces errors to false. If you want to
    /// check errors, call [fs::metadata].
    ///
    /// [fs::metadata]: ../../std/fs/fn.metadata.html
2405 2406 2407 2408 2409
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn exists(&self) -> bool {
        fs::metadata(self).is_ok()
    }

2410
    /// Returns whether the path exists on disk and is pointing at a regular file.
2411 2412 2413 2414
    ///
    /// This function will traverse symbolic links to query information about the
    /// destination file. In case of broken symbolic links this will return `false`.
    ///
2415 2416 2417
    /// If you cannot access the directory containing the file, e.g. because of a
    /// permission error, this will return `false`.
    ///
2418 2419 2420 2421 2422 2423 2424
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
    /// assert_eq!(Path::new("a_file.txt").is_file(), true);
    /// ```
2425 2426 2427 2428 2429 2430 2431 2432 2433
    ///
    /// # See Also
    ///
    /// This is a convenience function that coerces errors to false. If you want to
    /// check errors, call [fs::metadata] and handle its Result. Then call
    /// [fs::Metadata::is_file] if it was Ok.
    ///
    /// [fs::metadata]: ../../std/fs/fn.metadata.html
    /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2434 2435 2436 2437 2438
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn is_file(&self) -> bool {
        fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
    }

2439
    /// Returns whether the path exists on disk and is pointing at a directory.
2440 2441 2442 2443
    ///
    /// This function will traverse symbolic links to query information about the
    /// destination file. In case of broken symbolic links this will return `false`.
    ///
2444 2445 2446
    /// If you cannot access the directory containing the file, e.g. because of a
    /// permission error, this will return `false`.
    ///
2447 2448 2449 2450 2451 2452 2453
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
    /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
    /// ```
2454 2455 2456 2457 2458 2459 2460 2461 2462
    ///
    /// # See Also
    ///
    /// This is a convenience function that coerces errors to false. If you want to
    /// check errors, call [fs::metadata] and handle its Result. Then call
    /// [fs::Metadata::is_dir] if it was Ok.
    ///
    /// [fs::metadata]: ../../std/fs/fn.metadata.html
    /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2463 2464 2465 2466
    #[stable(feature = "path_ext", since = "1.5.0")]
    pub fn is_dir(&self) -> bool {
        fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
    }
C
Clar Charr 已提交
2467

2468 2469 2470 2471 2472
    /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
    /// allocating.
    ///
    /// [`Box`]: ../../std/boxed/struct.Box.html
    /// [`PathBuf`]: struct.PathBuf.html
2473
    #[stable(feature = "into_boxed_path", since = "1.20.0")]
C
Clar Charr 已提交
2474
    pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2475
        let rw = Box::into_raw(self) as *mut OsStr;
2476 2477
        let inner = unsafe { Box::from_raw(rw) };
        PathBuf { inner: OsString::from(inner) }
C
Clar Charr 已提交
2478
    }
A
Aaron Turon 已提交
2479 2480
}

A
Aaron Turon 已提交
2481
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2482 2483 2484 2485 2486 2487
impl AsRef<OsStr> for Path {
    fn as_ref(&self) -> &OsStr {
        &self.inner
    }
}

A
Aaron Turon 已提交
2488
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2489
impl fmt::Debug for Path {
2490 2491
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.inner, formatter)
A
Aaron Turon 已提交
2492 2493 2494
    }
}

L
lukaramu 已提交
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
/// Helper struct for safely printing paths with [`format!`] and `{}`.
///
/// A [`Path`] might contain non-Unicode data. This `struct` implements the
/// [`Display`] trait in a way that mitigates that. It is created by the
/// [`display`][`Path::display`] method on [`Path`].
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// let path = Path::new("/tmp/foo.rs");
///
/// println!("{}", path.display());
/// ```
///
/// [`Display`]: ../../std/fmt/trait.Display.html
/// [`format!`]: ../../std/macro.format.html
/// [`Path`]: struct.Path.html
/// [`Path::display`]: struct.Path.html#method.display
A
Aaron Turon 已提交
2515
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2516
pub struct Display<'a> {
T
Tshepang Lekhonkhobe 已提交
2517
    path: &'a Path,
A
Aaron Turon 已提交
2518 2519
}

A
Aaron Turon 已提交
2520
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2521 2522
impl<'a> fmt::Debug for Display<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2523
        fmt::Debug::fmt(&self.path, f)
A
Aaron Turon 已提交
2524 2525 2526
    }
}

A
Aaron Turon 已提交
2527
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2528 2529
impl<'a> fmt::Display for Display<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2530
        self.path.inner.display(f)
A
Aaron Turon 已提交
2531 2532 2533
    }
}

A
Aaron Turon 已提交
2534
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2535 2536
impl cmp::PartialEq for Path {
    fn eq(&self, other: &Path) -> bool {
2537
        self.components().eq(other.components())
A
Aaron Turon 已提交
2538 2539 2540
    }
}

2541 2542 2543 2544 2545 2546 2547 2548 2549
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for Path {
    fn hash<H: Hasher>(&self, h: &mut H) {
        for component in self.components() {
            component.hash(h);
        }
    }
}

A
Aaron Turon 已提交
2550
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2551 2552
impl cmp::Eq for Path {}

A
Aaron Turon 已提交
2553
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2554 2555
impl cmp::PartialOrd for Path {
    fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2556
        self.components().partial_cmp(other.components())
A
Aaron Turon 已提交
2557 2558 2559
    }
}

A
Aaron Turon 已提交
2560
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
2561 2562
impl cmp::Ord for Path {
    fn cmp(&self, other: &Path) -> cmp::Ordering {
2563
        self.components().cmp(other.components())
A
Aaron Turon 已提交
2564 2565 2566
    }
}

A
Aaron Turon 已提交
2567 2568
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for Path {
T
Tshepang Lekhonkhobe 已提交
2569 2570 2571
    fn as_ref(&self) -> &Path {
        self
    }
A
Aaron Turon 已提交
2572 2573 2574 2575
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for OsStr {
T
Tshepang Lekhonkhobe 已提交
2576 2577 2578
    fn as_ref(&self) -> &Path {
        Path::new(self)
    }
A
Aaron Turon 已提交
2579 2580
}

G
Gleb Kozyrev 已提交
2581 2582 2583 2584 2585 2586 2587
#[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
impl<'a> AsRef<Path> for Cow<'a, OsStr> {
    fn as_ref(&self) -> &Path {
        Path::new(self)
    }
}

A
Aaron Turon 已提交
2588 2589
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for OsString {
T
Tshepang Lekhonkhobe 已提交
2590 2591 2592
    fn as_ref(&self) -> &Path {
        Path::new(self)
    }
A
Aaron Turon 已提交
2593 2594 2595 2596
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for str {
T
Tshepang Lekhonkhobe 已提交
2597 2598 2599
    fn as_ref(&self) -> &Path {
        Path::new(self)
    }
A
Aaron Turon 已提交
2600 2601 2602 2603
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for String {
T
Tshepang Lekhonkhobe 已提交
2604 2605 2606
    fn as_ref(&self) -> &Path {
        Path::new(self)
    }
A
Aaron Turon 已提交
2607 2608 2609 2610
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for PathBuf {
T
Tshepang Lekhonkhobe 已提交
2611 2612 2613
    fn as_ref(&self) -> &Path {
        self
    }
A
Aaron Turon 已提交
2614 2615
}

2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
#[stable(feature = "path_into_iter", since = "1.6.0")]
impl<'a> IntoIterator for &'a PathBuf {
    type Item = &'a OsStr;
    type IntoIter = Iter<'a>;
    fn into_iter(self) -> Iter<'a> { self.iter() }
}

#[stable(feature = "path_into_iter", since = "1.6.0")]
impl<'a> IntoIterator for &'a Path {
    type Item = &'a OsStr;
    type IntoIter = Iter<'a>;
    fn into_iter(self) -> Iter<'a> { self.iter() }
}

2630
macro_rules! impl_cmp {
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
    ($lhs:ty, $rhs: ty) => {
        #[stable(feature = "partialeq_path", since = "1.6.0")]
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
        }

        #[stable(feature = "partialeq_path", since = "1.6.0")]
        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
        }

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
        #[stable(feature = "cmp_path", since = "1.8.0")]
        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
            #[inline]
            fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
                <Path as PartialOrd>::partial_cmp(self, other)
            }
        }

        #[stable(feature = "cmp_path", since = "1.8.0")]
        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
            #[inline]
            fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
                <Path as PartialOrd>::partial_cmp(self, other)
            }
        }
2659 2660 2661
    }
}

2662 2663 2664 2665 2666
impl_cmp!(PathBuf, Path);
impl_cmp!(PathBuf, &'a Path);
impl_cmp!(Cow<'a, Path>, Path);
impl_cmp!(Cow<'a, Path>, &'b Path);
impl_cmp!(Cow<'a, Path>, PathBuf);
2667

2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
macro_rules! impl_cmp_os_str {
    ($lhs:ty, $rhs: ty) => {
        #[stable(feature = "cmp_path", since = "1.8.0")]
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
        }

        #[stable(feature = "cmp_path", since = "1.8.0")]
        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
        }

        #[stable(feature = "cmp_path", since = "1.8.0")]
        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
            #[inline]
            fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
                <Path as PartialOrd>::partial_cmp(self, other.as_ref())
            }
        }

        #[stable(feature = "cmp_path", since = "1.8.0")]
        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
            #[inline]
            fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
                <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
            }
        }
2697 2698 2699
    }
}

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
impl_cmp_os_str!(PathBuf, OsStr);
impl_cmp_os_str!(PathBuf, &'a OsStr);
impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
impl_cmp_os_str!(PathBuf, OsString);
impl_cmp_os_str!(Path, OsStr);
impl_cmp_os_str!(Path, &'a OsStr);
impl_cmp_os_str!(Path, Cow<'a, OsStr>);
impl_cmp_os_str!(Path, OsString);
impl_cmp_os_str!(&'a Path, OsStr);
impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
impl_cmp_os_str!(&'a Path, OsString);
impl_cmp_os_str!(Cow<'a, Path>, OsStr);
impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
impl_cmp_os_str!(Cow<'a, Path>, OsString);
2714

2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl fmt::Display for StripPrefixError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

#[stable(since = "1.7.0", feature = "strip_prefix")]
impl Error for StripPrefixError {
    fn description(&self) -> &str { "prefix not found" }
}

A
Aaron Turon 已提交
2727 2728 2729 2730
#[cfg(test)]
mod tests {
    use super::*;

2731 2732 2733
    use rc::Rc;
    use sync::Arc;

A
Aaron Turon 已提交
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
    macro_rules! t(
        ($path:expr, iter: $iter:expr) => (
            {
                let path = Path::new($path);

                // Forward iteration
                let comps = path.iter()
                    .map(|p| p.to_string_lossy().into_owned())
                    .collect::<Vec<String>>();
                let exp: &[&str] = &$iter;
                let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
                assert!(comps == exps, "iter: Expected {:?}, found {:?}",
                        exps, comps);

                // Reverse iteration
                let comps = Path::new($path).iter().rev()
                    .map(|p| p.to_string_lossy().into_owned())
                    .collect::<Vec<String>>();
                let exps = exps.into_iter().rev().collect::<Vec<String>>();
                assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
                        exps, comps);
            }
        );

        ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
            {
                let path = Path::new($path);

                let act_root = path.has_root();
                assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
                        $has_root, act_root);

                let act_abs = path.is_absolute();
                assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
                        $is_absolute, act_abs);
            }
        );

        ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
            {
                let path = Path::new($path);

                let parent = path.parent().map(|p| p.to_str().unwrap());
                let exp_parent: Option<&str> = $parent;
                assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
                        exp_parent, parent);

                let file = path.file_name().map(|p| p.to_str().unwrap());
                let exp_file: Option<&str> = $file;
                assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
                        exp_file, file);
            }
        );

        ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
            {
                let path = Path::new($path);

                let stem = path.file_stem().map(|p| p.to_str().unwrap());
                let exp_stem: Option<&str> = $file_stem;
                assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
                        exp_stem, stem);

                let ext = path.extension().map(|p| p.to_str().unwrap());
                let exp_ext: Option<&str> = $extension;
                assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
                        exp_ext, ext);
            }
        );

        ($path:expr, iter: $iter:expr,
                     has_root: $has_root:expr, is_absolute: $is_absolute:expr,
                     parent: $parent:expr, file_name: $file:expr,
                     file_stem: $file_stem:expr, extension: $extension:expr) => (
            {
                t!($path, iter: $iter);
                t!($path, has_root: $has_root, is_absolute: $is_absolute);
                t!($path, parent: $parent, file_name: $file);
                t!($path, file_stem: $file_stem, extension: $extension);
            }
        );
    );

2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
    #[test]
    fn into() {
        use borrow::Cow;

        let static_path = Path::new("/home/foo");
        let static_cow_path: Cow<'static, Path> = static_path.into();
        let pathbuf = PathBuf::from("/home/foo");

        {
            let path: &Path = &pathbuf;
            let borrowed_cow_path: Cow<Path> = path.into();

            assert_eq!(static_cow_path, borrowed_cow_path);
        }

        let owned_cow_path: Cow<'static, Path> = pathbuf.into();

        assert_eq!(static_cow_path, owned_cow_path);
    }

A
Aaron Turon 已提交
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
    #[test]
    #[cfg(unix)]
    pub fn test_decompositions_unix() {
        t!("",
           iter: [],
           has_root: false,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo",
           iter: ["foo"],
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2854
           parent: Some(""),
A
Aaron Turon 已提交
2855 2856 2857 2858 2859 2860
           file_name: Some("foo"),
           file_stem: Some("foo"),
           extension: None
           );

        t!("/",
A
Aaron Turon 已提交
2861
           iter: ["/"],
A
Aaron Turon 已提交
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("/foo",
           iter: ["/", "foo"],
           has_root: true,
           is_absolute: true,
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
           extension: None
           );

        t!("foo/",
A
Aaron Turon 已提交
2881
           iter: ["foo"],
A
Aaron Turon 已提交
2882 2883
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2884 2885 2886
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
2887 2888 2889 2890
           extension: None
           );

        t!("/foo/",
A
Aaron Turon 已提交
2891
           iter: ["/", "foo"],
A
Aaron Turon 已提交
2892 2893
           has_root: true,
           is_absolute: true,
A
Aaron Turon 已提交
2894 2895 2896
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
           extension: None
           );

        t!("foo/bar",
           iter: ["foo", "bar"],
           has_root: false,
           is_absolute: false,
           parent: Some("foo"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("/foo/bar",
           iter: ["/", "foo", "bar"],
           has_root: true,
           is_absolute: true,
           parent: Some("/foo"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("///foo///",
A
Aaron Turon 已提交
2921
           iter: ["/", "foo"],
A
Aaron Turon 已提交
2922 2923
           has_root: true,
           is_absolute: true,
A
Aaron Turon 已提交
2924 2925 2926
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
           extension: None
           );

        t!("///foo///bar",
           iter: ["/", "foo", "bar"],
           has_root: true,
           is_absolute: true,
           parent: Some("///foo"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("./.",
A
Aaron Turon 已提交
2941
           iter: ["."],
A
Aaron Turon 已提交
2942 2943
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2944
           parent: Some(""),
A
Aaron Turon 已提交
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("/..",
           iter: ["/", ".."],
           has_root: true,
           is_absolute: true,
           parent: Some("/"),
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("../",
A
Aaron Turon 已提交
2961
           iter: [".."],
A
Aaron Turon 已提交
2962 2963
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2964
           parent: Some(""),
A
Aaron Turon 已提交
2965 2966 2967 2968 2969 2970
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/.",
A
Aaron Turon 已提交
2971
           iter: ["foo"],
A
Aaron Turon 已提交
2972 2973
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2974 2975 2976
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
           extension: None
           );

        t!("foo/..",
           iter: ["foo", ".."],
           has_root: false,
           is_absolute: false,
           parent: Some("foo"),
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/./",
A
Aaron Turon 已提交
2991
           iter: ["foo"],
A
Aaron Turon 已提交
2992 2993
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2994 2995 2996
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
2997 2998 2999 3000
           extension: None
           );

        t!("foo/./bar",
A
Aaron Turon 已提交
3001
           iter: ["foo", "bar"],
A
Aaron Turon 已提交
3002 3003
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3004
           parent: Some("foo"),
A
Aaron Turon 已提交
3005 3006 3007 3008 3009 3010
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("foo/../",
A
Aaron Turon 已提交
3011
           iter: ["foo", ".."],
A
Aaron Turon 已提交
3012 3013
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3014
           parent: Some("foo"),
A
Aaron Turon 已提交
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/../bar",
           iter: ["foo", "..", "bar"],
           has_root: false,
           is_absolute: false,
           parent: Some("foo/.."),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("./a",
           iter: [".", "a"],
           has_root: false,
           is_absolute: false,
           parent: Some("."),
           file_name: Some("a"),
           file_stem: Some("a"),
           extension: None
           );

        t!(".",
           iter: ["."],
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3044
           parent: Some(""),
A
Aaron Turon 已提交
3045 3046 3047 3048 3049 3050
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("./",
A
Aaron Turon 已提交
3051
           iter: ["."],
A
Aaron Turon 已提交
3052 3053
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3054
           parent: Some(""),
A
Aaron Turon 已提交
3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("a/b",
           iter: ["a", "b"],
           has_root: false,
           is_absolute: false,
           parent: Some("a"),
           file_name: Some("b"),
           file_stem: Some("b"),
           extension: None
           );

        t!("a//b",
           iter: ["a", "b"],
           has_root: false,
           is_absolute: false,
           parent: Some("a"),
           file_name: Some("b"),
           file_stem: Some("b"),
           extension: None
           );

        t!("a/./b",
A
Aaron Turon 已提交
3081
           iter: ["a", "b"],
A
Aaron Turon 已提交
3082 3083
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3084
           parent: Some("a"),
A
Aaron Turon 已提交
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
           file_name: Some("b"),
           file_stem: Some("b"),
           extension: None
           );

        t!("a/b/c",
           iter: ["a", "b", "c"],
           has_root: false,
           is_absolute: false,
           parent: Some("a/b"),
           file_name: Some("c"),
           file_stem: Some("c"),
           extension: None
           );
A
Aaron Turon 已提交
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108

        t!(".foo",
           iter: [".foo"],
           has_root: false,
           is_absolute: false,
           parent: Some(""),
           file_name: Some(".foo"),
           file_stem: Some(".foo"),
           extension: None
           );
A
Aaron Turon 已提交
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
    }

    #[test]
    #[cfg(windows)]
    pub fn test_decompositions_windows() {
        t!("",
           iter: [],
           has_root: false,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo",
           iter: ["foo"],
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3128
           parent: Some(""),
A
Aaron Turon 已提交
3129 3130 3131 3132 3133 3134
           file_name: Some("foo"),
           file_stem: Some("foo"),
           extension: None
           );

        t!("/",
A
Aaron Turon 已提交
3135
           iter: ["\\"],
A
Aaron Turon 已提交
3136 3137 3138 3139 3140 3141 3142 3143 3144
           has_root: true,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\",
A
Aaron Turon 已提交
3145
           iter: ["\\"],
A
Aaron Turon 已提交
3146 3147 3148 3149 3150 3151 3152 3153 3154
           has_root: true,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("c:",
A
Aaron Turon 已提交
3155
           iter: ["c:"],
A
Aaron Turon 已提交
3156 3157 3158 3159 3160 3161 3162 3163 3164
           has_root: false,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("c:\\",
A
Aaron Turon 已提交
3165
           iter: ["c:", "\\"],
A
Aaron Turon 已提交
3166 3167 3168 3169 3170 3171 3172 3173 3174
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("c:/",
A
Aaron Turon 已提交
3175
           iter: ["c:", "\\"],
A
Aaron Turon 已提交
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("/foo",
           iter: ["\\", "foo"],
           has_root: true,
           is_absolute: false,
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
           extension: None
           );

        t!("foo/",
A
Aaron Turon 已提交
3195
           iter: ["foo"],
A
Aaron Turon 已提交
3196 3197
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3198 3199 3200
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
3201 3202 3203 3204
           extension: None
           );

        t!("/foo/",
A
Aaron Turon 已提交
3205
           iter: ["\\", "foo"],
A
Aaron Turon 已提交
3206 3207
           has_root: true,
           is_absolute: false,
A
Aaron Turon 已提交
3208 3209 3210
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
           extension: None
           );

        t!("foo/bar",
           iter: ["foo", "bar"],
           has_root: false,
           is_absolute: false,
           parent: Some("foo"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("/foo/bar",
           iter: ["\\", "foo", "bar"],
           has_root: true,
           is_absolute: false,
           parent: Some("/foo"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("///foo///",
A
Aaron Turon 已提交
3235
           iter: ["\\", "foo"],
A
Aaron Turon 已提交
3236 3237
           has_root: true,
           is_absolute: false,
A
Aaron Turon 已提交
3238 3239 3240
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
           extension: None
           );

        t!("///foo///bar",
           iter: ["\\", "foo", "bar"],
           has_root: true,
           is_absolute: false,
           parent: Some("///foo"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("./.",
A
Aaron Turon 已提交
3255
           iter: ["."],
A
Aaron Turon 已提交
3256 3257
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3258
           parent: Some(""),
A
Aaron Turon 已提交
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("/..",
           iter: ["\\", ".."],
           has_root: true,
           is_absolute: false,
           parent: Some("/"),
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("../",
A
Aaron Turon 已提交
3275
           iter: [".."],
A
Aaron Turon 已提交
3276 3277
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3278
           parent: Some(""),
A
Aaron Turon 已提交
3279 3280 3281 3282 3283 3284
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/.",
A
Aaron Turon 已提交
3285
           iter: ["foo"],
A
Aaron Turon 已提交
3286 3287
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3288 3289 3290
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
           extension: None
           );

        t!("foo/..",
           iter: ["foo", ".."],
           has_root: false,
           is_absolute: false,
           parent: Some("foo"),
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/./",
A
Aaron Turon 已提交
3305
           iter: ["foo"],
A
Aaron Turon 已提交
3306 3307
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3308 3309 3310
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
3311 3312 3313 3314
           extension: None
           );

        t!("foo/./bar",
A
Aaron Turon 已提交
3315
           iter: ["foo", "bar"],
A
Aaron Turon 已提交
3316 3317
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3318
           parent: Some("foo"),
A
Aaron Turon 已提交
3319 3320 3321 3322 3323 3324
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("foo/../",
A
Aaron Turon 已提交
3325
           iter: ["foo", ".."],
A
Aaron Turon 已提交
3326 3327
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3328
           parent: Some("foo"),
A
Aaron Turon 已提交
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/../bar",
           iter: ["foo", "..", "bar"],
           has_root: false,
           is_absolute: false,
           parent: Some("foo/.."),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("./a",
           iter: [".", "a"],
           has_root: false,
           is_absolute: false,
           parent: Some("."),
           file_name: Some("a"),
           file_stem: Some("a"),
           extension: None
           );

        t!(".",
           iter: ["."],
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3358
           parent: Some(""),
A
Aaron Turon 已提交
3359 3360 3361 3362 3363 3364
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("./",
A
Aaron Turon 已提交
3365
           iter: ["."],
A
Aaron Turon 已提交
3366 3367
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3368
           parent: Some(""),
A
Aaron Turon 已提交
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("a/b",
           iter: ["a", "b"],
           has_root: false,
           is_absolute: false,
           parent: Some("a"),
           file_name: Some("b"),
           file_stem: Some("b"),
           extension: None
           );

        t!("a//b",
           iter: ["a", "b"],
           has_root: false,
           is_absolute: false,
           parent: Some("a"),
           file_name: Some("b"),
           file_stem: Some("b"),
           extension: None
           );

        t!("a/./b",
A
Aaron Turon 已提交
3395
           iter: ["a", "b"],
A
Aaron Turon 已提交
3396 3397
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
3398
           parent: Some("a"),
A
Aaron Turon 已提交
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
           file_name: Some("b"),
           file_stem: Some("b"),
           extension: None
           );

        t!("a/b/c",
           iter: ["a", "b", "c"],
           has_root: false,
           is_absolute: false,
           parent: Some("a/b"),
           file_name: Some("c"),
           file_stem: Some("c"),
           extension: None);

        t!("a\\b\\c",
           iter: ["a", "b", "c"],
           has_root: false,
           is_absolute: false,
           parent: Some("a\\b"),
           file_name: Some("c"),
           file_stem: Some("c"),
           extension: None
           );

        t!("\\a",
           iter: ["\\", "a"],
           has_root: true,
           is_absolute: false,
           parent: Some("\\"),
           file_name: Some("a"),
           file_stem: Some("a"),
           extension: None
           );

        t!("c:\\foo.txt",
           iter: ["c:", "\\", "foo.txt"],
           has_root: true,
           is_absolute: true,
           parent: Some("c:\\"),
           file_name: Some("foo.txt"),
           file_stem: Some("foo"),
           extension: Some("txt")
           );

        t!("\\\\server\\share\\foo.txt",
           iter: ["\\\\server\\share", "\\", "foo.txt"],
           has_root: true,
           is_absolute: true,
           parent: Some("\\\\server\\share\\"),
           file_name: Some("foo.txt"),
           file_stem: Some("foo"),
           extension: Some("txt")
           );

        t!("\\\\server\\share",
A
Aaron Turon 已提交
3454
           iter: ["\\\\server\\share", "\\"],
A
Aaron Turon 已提交
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\server",
           iter: ["\\", "server"],
           has_root: true,
           is_absolute: false,
           parent: Some("\\"),
           file_name: Some("server"),
           file_stem: Some("server"),
           extension: None
           );

        t!("\\\\?\\bar\\foo.txt",
           iter: ["\\\\?\\bar", "\\", "foo.txt"],
           has_root: true,
           is_absolute: true,
           parent: Some("\\\\?\\bar\\"),
           file_name: Some("foo.txt"),
           file_stem: Some("foo"),
           extension: Some("txt")
           );

        t!("\\\\?\\bar",
           iter: ["\\\\?\\bar"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\?\\",
           iter: ["\\\\?\\"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\?\\UNC\\server\\share\\foo.txt",
           iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
           has_root: true,
           is_absolute: true,
           parent: Some("\\\\?\\UNC\\server\\share\\"),
           file_name: Some("foo.txt"),
           file_stem: Some("foo"),
           extension: Some("txt")
           );

        t!("\\\\?\\UNC\\server",
           iter: ["\\\\?\\UNC\\server"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\?\\UNC\\",
           iter: ["\\\\?\\UNC\\"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\?\\C:\\foo.txt",
           iter: ["\\\\?\\C:", "\\", "foo.txt"],
           has_root: true,
           is_absolute: true,
           parent: Some("\\\\?\\C:\\"),
           file_name: Some("foo.txt"),
           file_stem: Some("foo"),
           extension: Some("txt")
           );


        t!("\\\\?\\C:\\",
A
Aaron Turon 已提交
3545
           iter: ["\\\\?\\C:", "\\"],
A
Aaron Turon 已提交
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\?\\C:",
           iter: ["\\\\?\\C:"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\?\\foo/bar",
           iter: ["\\\\?\\foo/bar"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\?\\C:/foo",
           iter: ["\\\\?\\C:/foo"],
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\.\\foo\\bar",
           iter: ["\\\\.\\foo", "\\", "bar"],
           has_root: true,
           is_absolute: true,
           parent: Some("\\\\.\\foo\\"),
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );


        t!("\\\\.\\foo",
A
Aaron Turon 已提交
3600
           iter: ["\\\\.\\foo", "\\"],
A
Aaron Turon 已提交
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\.\\foo/bar",
A
Aaron Turon 已提交
3611
           iter: ["\\\\.\\foo/bar", "\\"],
A
Aaron Turon 已提交
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\.\\foo\\bar/baz",
           iter: ["\\\\.\\foo", "\\", "bar", "baz"],
           has_root: true,
           is_absolute: true,
           parent: Some("\\\\.\\foo\\bar"),
           file_name: Some("baz"),
           file_stem: Some("baz"),
           extension: None
           );


        t!("\\\\.\\",
A
Aaron Turon 已提交
3633
           iter: ["\\\\.\\", "\\"],
A
Aaron Turon 已提交
3634 3635 3636 3637 3638 3639 3640 3641 3642
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\?\\a\\b\\",
A
Aaron Turon 已提交
3643
           iter: ["\\\\?\\a", "\\", "b"],
A
Aaron Turon 已提交
3644 3645
           has_root: true,
           is_absolute: true,
A
Aaron Turon 已提交
3646 3647 3648
           parent: Some("\\\\?\\a\\"),
           file_name: Some("b"),
           file_stem: Some("b"),
A
Aaron Turon 已提交
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
           extension: None
           );
    }

    #[test]
    pub fn test_stem_ext() {
        t!("foo",
           file_stem: Some("foo"),
           extension: None
           );

        t!("foo.",
           file_stem: Some("foo"),
           extension: Some("")
           );

        t!(".foo",
           file_stem: Some(".foo"),
           extension: None
           );

        t!("foo.txt",
           file_stem: Some("foo"),
           extension: Some("txt")
           );

        t!("foo.bar.txt",
           file_stem: Some("foo.bar"),
           extension: Some("txt")
           );

        t!("foo.bar.",
           file_stem: Some("foo.bar"),
           extension: Some("")
           );

        t!(".",
           file_stem: None,
           extension: None
           );

        t!("..",
           file_stem: None,
           extension: None
           );

        t!("",
           file_stem: None,
           extension: None
           );
    }

    #[test]
    pub fn test_push() {
        macro_rules! tp(
            ($path:expr, $push:expr, $expected:expr) => ( {
3705
                let mut actual = PathBuf::from($path);
A
Aaron Turon 已提交
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765
                actual.push($push);
                assert!(actual.to_str() == Some($expected),
                        "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
                        $push, $path, $expected, actual.to_str().unwrap());
            });
        );

        if cfg!(unix) {
            tp!("", "foo", "foo");
            tp!("foo", "bar", "foo/bar");
            tp!("foo/", "bar", "foo/bar");
            tp!("foo//", "bar", "foo//bar");
            tp!("foo/.", "bar", "foo/./bar");
            tp!("foo./.", "bar", "foo././bar");
            tp!("foo", "", "foo/");
            tp!("foo", ".", "foo/.");
            tp!("foo", "..", "foo/..");
            tp!("foo", "/", "/");
            tp!("/foo/bar", "/", "/");
            tp!("/foo/bar", "/baz", "/baz");
            tp!("/foo/bar", "./baz", "/foo/bar/./baz");
        } else {
            tp!("", "foo", "foo");
            tp!("foo", "bar", r"foo\bar");
            tp!("foo/", "bar", r"foo/bar");
            tp!(r"foo\", "bar", r"foo\bar");
            tp!("foo//", "bar", r"foo//bar");
            tp!(r"foo\\", "bar", r"foo\\bar");
            tp!("foo/.", "bar", r"foo/.\bar");
            tp!("foo./.", "bar", r"foo./.\bar");
            tp!(r"foo\.", "bar", r"foo\.\bar");
            tp!(r"foo.\.", "bar", r"foo.\.\bar");
            tp!("foo", "", "foo\\");
            tp!("foo", ".", r"foo\.");
            tp!("foo", "..", r"foo\..");
            tp!("foo", "/", "/");
            tp!("foo", r"\", r"\");
            tp!("/foo/bar", "/", "/");
            tp!(r"\foo\bar", r"\", r"\");
            tp!("/foo/bar", "/baz", "/baz");
            tp!("/foo/bar", r"\baz", r"\baz");
            tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
            tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");

            tp!("c:\\", "windows", "c:\\windows");
            tp!("c:", "windows", "c:windows");

            tp!("a\\b\\c", "d", "a\\b\\c\\d");
            tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
            tp!("a\\b", "c\\d", "a\\b\\c\\d");
            tp!("a\\b", "\\c\\d", "\\c\\d");
            tp!("a\\b", ".", "a\\b\\.");
            tp!("a\\b", "..\\c", "a\\b\\..\\c");
            tp!("a\\b", "C:a.txt", "C:a.txt");
            tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
            tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
            tp!("C:\\a\\b\\c", "C:d", "C:d");
            tp!("C:a\\b\\c", "C:d", "C:d");
            tp!("C:", r"a\b\c", r"C:a\b\c");
            tp!("C:", r"..\a", r"C:..\a");
T
Tshepang Lekhonkhobe 已提交
3766 3767 3768
            tp!("\\\\server\\share\\foo",
                "bar",
                "\\\\server\\share\\foo\\bar");
A
Aaron Turon 已提交
3769 3770 3771 3772 3773
            tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
            tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
            tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
            tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
            tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
T
Tshepang Lekhonkhobe 已提交
3774 3775 3776
            tp!("\\\\?\\UNC\\server\\share\\foo",
                "bar",
                "\\\\?\\UNC\\server\\share\\foo\\bar");
A
Aaron Turon 已提交
3777 3778 3779 3780 3781 3782
            tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
            tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");

            // Note: modified from old path API
            tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");

T
Tshepang Lekhonkhobe 已提交
3783 3784 3785
            tp!("C:\\a",
                "\\\\?\\UNC\\server\\share",
                "\\\\?\\UNC\\server\\share");
A
Aaron Turon 已提交
3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798
            tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
            tp!("\\\\.\\foo\\bar", "C:a", "C:a");
            // again, not sure about the following, but I'm assuming \\.\ should be verbatim
            tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");

            tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
        }
    }

    #[test]
    pub fn test_pop() {
        macro_rules! tp(
            ($path:expr, $expected:expr, $output:expr) => ( {
3799
                let mut actual = PathBuf::from($path);
A
Aaron Turon 已提交
3800 3801 3802 3803 3804 3805 3806 3807 3808 3809
                let output = actual.pop();
                assert!(actual.to_str() == Some($expected) && output == $output,
                        "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
                        $path, $expected, $output,
                        actual.to_str().unwrap(), output);
            });
        );

        tp!("", "", false);
        tp!("/", "/", false);
A
Aaron Turon 已提交
3810 3811
        tp!("foo", "", true);
        tp!(".", "", true);
A
Aaron Turon 已提交
3812 3813 3814
        tp!("/foo", "/", true);
        tp!("/foo/bar", "/foo", true);
        tp!("foo/bar", "foo", true);
A
Aaron Turon 已提交
3815
        tp!("foo/.", "", true);
A
Aaron Turon 已提交
3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
        tp!("foo//bar", "foo", true);

        if cfg!(windows) {
            tp!("a\\b\\c", "a\\b", true);
            tp!("\\a", "\\", true);
            tp!("\\", "\\", false);

            tp!("C:\\a\\b", "C:\\a", true);
            tp!("C:\\a", "C:\\", true);
            tp!("C:\\", "C:\\", false);
            tp!("C:a\\b", "C:a", true);
            tp!("C:a", "C:", true);
            tp!("C:", "C:", false);
            tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
            tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
            tp!("\\\\server\\share", "\\\\server\\share", false);
            tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
            tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
            tp!("\\\\?\\a", "\\\\?\\a", false);
            tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
            tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
            tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
T
Tshepang Lekhonkhobe 已提交
3838 3839 3840 3841 3842 3843 3844 3845 3846
            tp!("\\\\?\\UNC\\server\\share\\a\\b",
                "\\\\?\\UNC\\server\\share\\a",
                true);
            tp!("\\\\?\\UNC\\server\\share\\a",
                "\\\\?\\UNC\\server\\share\\",
                true);
            tp!("\\\\?\\UNC\\server\\share",
                "\\\\?\\UNC\\server\\share",
                false);
A
Aaron Turon 已提交
3847 3848 3849 3850
            tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
            tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
            tp!("\\\\.\\a", "\\\\.\\a", false);

A
Aaron Turon 已提交
3851
            tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
A
Aaron Turon 已提交
3852 3853 3854 3855 3856 3857 3858
        }
    }

    #[test]
    pub fn test_set_file_name() {
        macro_rules! tfn(
                ($path:expr, $file:expr, $expected:expr) => ( {
3859
                let mut p = PathBuf::from($path);
A
Aaron Turon 已提交
3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871
                p.set_file_name($file);
                assert!(p.to_str() == Some($expected),
                        "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
                        $path, $file, $expected,
                        p.to_str().unwrap());
            });
        );

        tfn!("foo", "foo", "foo");
        tfn!("foo", "bar", "bar");
        tfn!("foo", "", "");
        tfn!("", "foo", "foo");
A
Alex Crichton 已提交
3872 3873
        if cfg!(unix) {
            tfn!(".", "foo", "./foo");
A
Aaron Turon 已提交
3874 3875
            tfn!("foo/", "bar", "bar");
            tfn!("foo/.", "bar", "bar");
A
Alex Crichton 已提交
3876 3877 3878 3879 3880
            tfn!("..", "foo", "../foo");
            tfn!("foo/..", "bar", "foo/../bar");
            tfn!("/", "foo", "/foo");
        } else {
            tfn!(".", "foo", r".\foo");
A
Aaron Turon 已提交
3881 3882
            tfn!(r"foo\", "bar", r"bar");
            tfn!(r"foo\.", "bar", r"bar");
A
Alex Crichton 已提交
3883 3884 3885 3886
            tfn!("..", "foo", r"..\foo");
            tfn!(r"foo\..", "bar", r"foo\..\bar");
            tfn!(r"\", "foo", r"\foo");
        }
A
Aaron Turon 已提交
3887 3888 3889 3890 3891 3892
    }

    #[test]
    pub fn test_set_extension() {
        macro_rules! tfe(
                ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3893
                let mut p = PathBuf::from($path);
A
Aaron Turon 已提交
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909
                let output = p.set_extension($ext);
                assert!(p.to_str() == Some($expected) && output == $output,
                        "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
                        $path, $ext, $expected, $output,
                        p.to_str().unwrap(), output);
            });
        );

        tfe!("foo", "txt", "foo.txt", true);
        tfe!("foo.bar", "txt", "foo.txt", true);
        tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
        tfe!(".test", "txt", ".test.txt", true);
        tfe!("foo.txt", "", "foo", true);
        tfe!("foo", "", "foo", true);
        tfe!("", "foo", "", false);
        tfe!(".", "foo", ".", false);
A
Aaron Turon 已提交
3910 3911
        tfe!("foo/", "bar", "foo.bar", true);
        tfe!("foo/.", "bar", "foo.bar", true);
T
Tshepang Lekhonkhobe 已提交
3912
        tfe!("..", "foo", "..", false);
A
Aaron Turon 已提交
3913 3914 3915 3916
        tfe!("foo/..", "bar", "foo/..", false);
        tfe!("/", "foo", "/", false);
    }

3917
    #[test]
M
Martin Lindhe 已提交
3918
    fn test_eq_receivers() {
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941
        use borrow::Cow;

        let borrowed: &Path = Path::new("foo/bar");
        let mut owned: PathBuf = PathBuf::new();
        owned.push("foo");
        owned.push("bar");
        let borrowed_cow: Cow<Path> = borrowed.into();
        let owned_cow: Cow<Path> = owned.clone().into();

        macro_rules! t {
            ($($current:expr),+) => {
                $(
                    assert_eq!($current, borrowed);
                    assert_eq!($current, owned);
                    assert_eq!($current, borrowed_cow);
                    assert_eq!($current, owned_cow);
                )+
            }
        }

        t!(borrowed, owned, borrowed_cow, owned_cow);
    }

A
Aaron Turon 已提交
3942 3943
    #[test]
    pub fn test_compare() {
3944 3945
        use hash::{Hash, Hasher};
        use collections::hash_map::DefaultHasher;
3946 3947

        fn hash<T: Hash>(t: T) -> u64 {
3948
            let mut s = DefaultHasher::new();
3949 3950 3951 3952
            t.hash(&mut s);
            s.finish()
        }

A
Aaron Turon 已提交
3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
        macro_rules! tc(
            ($path1:expr, $path2:expr, eq: $eq:expr,
             starts_with: $starts_with:expr, ends_with: $ends_with:expr,
             relative_from: $relative_from:expr) => ({
                 let path1 = Path::new($path1);
                 let path2 = Path::new($path2);

                 let eq = path1 == path2;
                 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
                         $path1, $path2, $eq, eq);
3963 3964 3965
                 assert!($eq == (hash(path1) == hash(path2)),
                         "{:?} == {:?}, expected {:?}, got {} and {}",
                         $path1, $path2, $eq, hash(path1), hash(path2));
A
Aaron Turon 已提交
3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976

                 let starts_with = path1.starts_with(path2);
                 assert!(starts_with == $starts_with,
                         "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
                         $starts_with, starts_with);

                 let ends_with = path1.ends_with(path2);
                 assert!(ends_with == $ends_with,
                         "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
                         $ends_with, ends_with);

A
Alex Crichton 已提交
3977 3978 3979
                 let relative_from = path1.strip_prefix(path2)
                                          .map(|p| p.to_str().unwrap())
                                          .ok();
A
Aaron Turon 已提交
3980 3981
                 let exp: Option<&str> = $relative_from;
                 assert!(relative_from == exp,
A
Alex Crichton 已提交
3982 3983
                         "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
                         $path1, $path2, exp, relative_from);
A
Aaron Turon 已提交
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
            });
        );

        tc!("", "",
            eq: true,
            starts_with: true,
            ends_with: true,
            relative_from: Some("")
            );

        tc!("foo", "",
            eq: false,
            starts_with: true,
            ends_with: true,
            relative_from: Some("foo")
            );

        tc!("", "foo",
            eq: false,
            starts_with: false,
            ends_with: false,
            relative_from: None
            );

        tc!("foo", "foo",
            eq: true,
            starts_with: true,
            ends_with: true,
            relative_from: Some("")
            );

        tc!("foo/", "foo",
A
Aaron Turon 已提交
4016
            eq: true,
A
Aaron Turon 已提交
4017
            starts_with: true,
A
Aaron Turon 已提交
4018 4019
            ends_with: true,
            relative_from: Some("")
A
Aaron Turon 已提交
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045
            );

        tc!("foo/bar", "foo",
            eq: false,
            starts_with: true,
            ends_with: false,
            relative_from: Some("bar")
            );

        tc!("foo/bar/baz", "foo/bar",
            eq: false,
            starts_with: true,
            ends_with: false,
            relative_from: Some("baz")
            );

        tc!("foo/bar", "foo/bar/baz",
            eq: false,
            starts_with: false,
            ends_with: false,
            relative_from: None
            );

        tc!("./foo/bar/", ".",
            eq: false,
            starts_with: true,
A
Aaron Turon 已提交
4046 4047
            ends_with: false,
            relative_from: Some("foo/bar")
A
Aaron Turon 已提交
4048
            );
A
Aaron Turon 已提交
4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065

        if cfg!(windows) {
            tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
                r"c:\src\rust\cargo-test\test",
                eq: false,
                starts_with: true,
                ends_with: false,
                relative_from: Some("Cargo.toml")
                );

            tc!(r"c:\foo", r"C:\foo",
                eq: true,
                starts_with: true,
                ends_with: true,
                relative_from: Some("")
                );
        }
A
Aaron Turon 已提交
4066
    }
4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087

    #[test]
    fn test_components_debug() {
        let path = Path::new("/tmp");

        let mut components = path.components();

        let expected = "Components([RootDir, Normal(\"tmp\")])";
        let actual = format!("{:?}", components);
        assert_eq!(expected, actual);

        let _ = components.next().unwrap();
        let expected = "Components([Normal(\"tmp\")])";
        let actual = format!("{:?}", components);
        assert_eq!(expected, actual);

        let _ = components.next().unwrap();
        let expected = "Components([])";
        let actual = format!("{:?}", components);
        assert_eq!(expected, actual);
    }
4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109

    #[cfg(unix)]
    #[test]
    fn test_iter_debug() {
        let path = Path::new("/tmp");

        let mut iter = path.iter();

        let expected = "Iter([\"/\", \"tmp\"])";
        let actual = format!("{:?}", iter);
        assert_eq!(expected, actual);

        let _ = iter.next().unwrap();
        let expected = "Iter([\"tmp\"])";
        let actual = format!("{:?}", iter);
        assert_eq!(expected, actual);

        let _ = iter.next().unwrap();
        let expected = "Iter([])";
        let actual = format!("{:?}", iter);
        assert_eq!(expected, actual);
    }
4110 4111 4112 4113 4114

    #[test]
    fn into_boxed() {
        let orig: &str = "some/sort/of/path";
        let path = Path::new(orig);
C
Clar Charr 已提交
4115 4116 4117 4118 4119
        let boxed: Box<Path> = Box::from(path);
        let path_buf = path.to_owned().into_boxed_path().into_path_buf();
        assert_eq!(path, &*boxed);
        assert_eq!(&*boxed, &*path_buf);
        assert_eq!(&*path_buf, path);
4120
    }
4121 4122 4123 4124 4125 4126 4127 4128 4129

    #[test]
    fn test_clone_into() {
        let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
        let path = Path::new("short");
        path.clone_into(&mut path_buf);
        assert_eq!(path, path_buf);
        assert!(path_buf.into_os_string().capacity() >= 15);
    }
4130 4131 4132 4133 4134 4135

    #[test]
    fn display_format_flags() {
        assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
        assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
    }
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152

    #[test]
    fn into_rc() {
        let orig = "hello/world";
        let path = Path::new(orig);
        let rc: Rc<Path> = Rc::from(path);
        let arc: Arc<Path> = Arc::from(path);

        assert_eq!(&*rc, path);
        assert_eq!(&*arc, path);

        let rc2: Rc<Path> = Rc::from(path.to_owned());
        let arc2: Arc<Path> = Arc::from(path.to_owned());

        assert_eq!(&*rc2, path);
        assert_eq!(&*arc2, path);
    }
A
Aaron Turon 已提交
4153
}