path.rs 83.6 KB
Newer Older
A
Aaron Turon 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 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.
//!
//! This module provides two types, `PathBuf` and `Path` (akin to `String` and
//! `str`), for working with paths abstractly. These types are thin wrappers
//! around `OsString` and `OsStr` respectively, meaning that they work directly
//! on strings according to the local platform's path syntax.
//!
//! ## Simple usage
//!
A
Aaron Turon 已提交
20
//! Path manipulation includes both parsing components from slices and building
A
Aaron Turon 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
//! new owned paths.
//!
//! To parse a path, you can create a `Path` slice from a `str`
//! slice and start asking questions:
//!
//! ```rust
//! use std::path::Path;
//!
//! let path = Path::new("/tmp/foo/bar.txt");
//! let file = path.file_name();
//! let extension = path.extension();
//! let parent_dir = path.parent();
//! ```
//!
//! To build or modify paths, use `PathBuf`:
//!
//! ```rust
//! use std::path::PathBuf;
//!
//! let mut path = PathBuf::new("c:\\");
//! path.push("windows");
//! path.push("system32");
//! path.set_extension("dll");
//! ```
//!
//! ## Path components and normalization
//!
//! The path APIs are built around the notion of "components", which roughly
//! correspond to the substrings between path separators (`/` and, on Windows,
//! `\`). The APIs for path parsing are largely specified in terms of the path's
//! components, so it's important to clearly understand how those are determined.
//!
A
Aaron Turon 已提交
53 54 55
//! A path can always be reconstructed into an *equivalent* path by
//! putting together its components via `push`. Syntactically, the
//! paths may differ by the normalization described below.
A
Aaron Turon 已提交
56 57 58 59 60 61 62 63 64
//!
//! ### Component types
//!
//! Components come in several types:
//!
//! * Normal components are the default: standard references to files or
//! directories. The path `a/b` has two normal components, `a` and `b`.
//!
//! * Current directory components represent the `.` character. For example,
A
Aaron Turon 已提交
65
//! `./a` has a current directory component and a normal component `a`.
A
Aaron Turon 已提交
66 67 68 69 70
//!
//! * The root directory component represents a separator that designates
//!   starting from root. For example, `/a/b` has a root directory component
//!   followed by normal components `a` and `b`.
//!
A
Aaron Turon 已提交
71
//! On Windows, an additional component type comes into play:
A
Aaron Turon 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
//!
//! * Prefix components, of which there is a large variety. For example, `C:`
//! and `\\server\share` are prefixes. The path `C:windows` has a prefix
//! component `C:` and a normal component `windows`; the path `C:\windows` has a
//! prefix component `C:`, a root directory component, and a normal component
//! `windows`.
//!
//! ### Normalization
//!
//! Aside from splitting on the separator(s), there is a small amount of
//! "normalization":
//!
//! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
//!   and `b`.
//!
A
Aaron Turon 已提交
87 88 89 90 91
//! * Occurrences of `.` are normalized away, *except* if they are at
//! the beginning of the path (in which case they are often meaningful
//! in terms of path searching). So, fore xample, `a/./b`, `a/b/`,
//! `/a/b/.` and `a/b` all ahve components `a` and `b`, but `./a/b`
//! has a leading current directory component.
A
Aaron Turon 已提交
92
//!
A
Aaron Turon 已提交
93 94 95 96 97
//! No other normalization takes place by default. 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`). Further
//! normalization is possible to build on top of the components APIs,
//! and will be included in this library in the near future.
A
Aaron Turon 已提交
98

A
Aaron Turon 已提交
99
#![stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
100 101 102

use core::prelude::*;

A
Aaron Turon 已提交
103
use ascii::*;
J
Jorge Aparicio 已提交
104
use borrow::{Borrow, IntoCow, ToOwned, Cow};
A
Aaron Turon 已提交
105
use cmp;
A
Alexis 已提交
106
use iter::{self, IntoIterator};
A
Aaron Turon 已提交
107 108 109 110 111 112 113
use mem;
use ops::{self, Deref};
use vec::Vec;
use fmt;

use ffi::{OsStr, OsString, AsOsStr};

A
Aaron Turon 已提交
114
use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
A
Aaron Turon 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

////////////////////////////////////////////////////////////////////////////////
// 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.

////////////////////////////////////////////////////////////////////////////////
// Platform-specific definitions
////////////////////////////////////////////////////////////////////////////////

// The following modules give the most basic tools for parsing paths on various
// platforms. The bulk of the code is devoted to parsing prefixes on Windows.

#[cfg(unix)]
mod platform {
A
Aaron Turon 已提交
135
    use super::Prefix;
A
Aaron Turon 已提交
136 137 138 139
    use core::prelude::*;
    use ffi::OsStr;

    #[inline]
A
Aaron Turon 已提交
140
    pub fn is_sep_byte(b: u8) -> bool {
A
Aaron Turon 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153
        b == b'/'
    }

    #[inline]
    pub fn is_verbatim_sep(b: u8) -> bool {
        b == b'/'
    }

    pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
        None
    }

    pub const MAIN_SEP_STR: &'static str = "/";
A
Aaron Turon 已提交
154
    pub const MAIN_SEP: char = '/';
A
Aaron Turon 已提交
155 156 157 158 159
}

#[cfg(windows)]
mod platform {
    use core::prelude::*;
A
Aaron Turon 已提交
160
    use ascii::*;
A
Aaron Turon 已提交
161

A
Alex Crichton 已提交
162
    use char::CharExt as UnicodeCharExt;
A
Aaron Turon 已提交
163
    use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
A
Alex Crichton 已提交
164
    use ffi::OsStr;
A
Aaron Turon 已提交
165 166

    #[inline]
A
Aaron Turon 已提交
167
    pub fn is_sep_byte(b: u8) -> bool {
A
Aaron Turon 已提交
168 169 170 171 172 173 174 175 176
        b == b'/' || b == b'\\'
    }

    #[inline]
    pub fn is_verbatim_sep(b: u8) -> bool {
        b == b'\\'
    }

    pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
A
Aaron Turon 已提交
177
        use super::Prefix::*;
A
Aaron Turon 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        unsafe {
            // 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.
            let mut path = os_str_as_u8_slice(path);

            if path.starts_with(br"\\") {
                // \\
                path = &path[2..];
                if path.starts_with(br"?\") {
                    // \\?\
                    path = &path[2..];
                    if path.starts_with(br"UNC\") {
                        // \\?\UNC\server\share
                        path = &path[4..];
                        let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
                            Some((server, share)) => (u8_slice_as_os_str(server),
                                                      u8_slice_as_os_str(share)),
                            None => (u8_slice_as_os_str(path),
                                     u8_slice_as_os_str(&[])),
                        };
                        return Some(VerbatimUNC(server, share));
                    } else {
                        // \\?\path
                        let idx = path.position_elem(&b'\\');
                        if idx == Some(2) && path[1] == b':' {
                            let c = path[0];
                            if c.is_ascii() && (c as char).is_alphabetic() {
                                // \\?\C:\ path
A
Aaron Turon 已提交
208
                                return Some(VerbatimDisk(c.to_ascii_uppercase()));
A
Aaron Turon 已提交
209 210 211 212 213 214 215 216 217 218 219
                            }
                        }
                        let slice = &path[.. idx.unwrap_or(path.len())];
                        return Some(Verbatim(u8_slice_as_os_str(slice)));
                    }
                } else if path.starts_with(b".\\") {
                    // \\.\path
                    path = &path[2..];
                    let slice = &path[.. path.position_elem(&b'\\').unwrap_or(path.len())];
                    return Some(DeviceNS(u8_slice_as_os_str(slice)));
                }
A
Aaron Turon 已提交
220
                match parse_two_comps(path, is_sep_byte) {
A
Aaron Turon 已提交
221 222 223 224 225 226 227 228 229 230 231
                    Some((server, share)) if server.len() > 0 && share.len() > 0 => {
                        // \\server\share
                        return Some(UNC(u8_slice_as_os_str(server),
                                        u8_slice_as_os_str(share)));
                    }
                    _ => ()
                }
            } else if path.len() > 1 && path[1] == b':' {
                // C:
                let c = path[0];
                if c.is_ascii() && (c as char).is_alphabetic() {
A
Aaron Turon 已提交
232
                    return Some(Disk(c.to_ascii_uppercase()));
A
Aaron Turon 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
                }
            }
            return None;
        }

        fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
            let first = match path.iter().position(|x| f(*x)) {
                None => return None,
                Some(x) => &path[.. x]
            };
            path = &path[(first.len()+1)..];
            let idx = path.iter().position(|x| f(*x));
            let second = &path[.. idx.unwrap_or(path.len())];
            Some((first, second))
        }
    }

A
Aaron Turon 已提交
250 251 252
    pub const MAIN_SEP_STR: &'static str = "\\";
    pub const MAIN_SEP: char = '\\';
}
A
Aaron Turon 已提交
253

A
Aaron Turon 已提交
254 255 256
////////////////////////////////////////////////////////////////////////////////
// Windows Prefixes
////////////////////////////////////////////////////////////////////////////////
A
Aaron Turon 已提交
257

A
Aaron Turon 已提交
258 259 260 261 262 263 264 265
/// Path prefixes (Windows only).
///
/// Windows uses a variety of path styles, including references to drive
/// volumes (like `C:`), network shared (like `\\server\share`) and
/// others. In addition, some path prefixes are "verbatim", in which case
/// `/` is *not* treated as a separator and essentially no normalization is
/// performed.
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
A
Aaron Turon 已提交
266
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
267 268
pub enum Prefix<'a> {
    /// Prefix `\\?\`, together with the given component immediately following it.
A
Aaron Turon 已提交
269
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
270 271 272
    Verbatim(&'a OsStr),

    /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
A
Aaron Turon 已提交
273
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
274 275 276
    VerbatimUNC(&'a OsStr, &'a OsStr),

    /// Prefix like `\\?\C:\`, for the given drive letter
A
Aaron Turon 已提交
277
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
278 279 280
    VerbatimDisk(u8),

    /// Prefix `\\.\`, together with the given component immediately following it.
A
Aaron Turon 已提交
281
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
282 283 284
    DeviceNS(&'a OsStr),

    /// Prefix `\\server\share`, with the given "server" and "share" components.
A
Aaron Turon 已提交
285
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
286 287 288
    UNC(&'a OsStr, &'a OsStr),

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

A
Aaron Turon 已提交
293 294 295 296 297 298
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 已提交
299
        }
A
Aaron Turon 已提交
300 301 302 303 304 305 306 307 308 309 310
        match *self {
            Verbatim(x) => 4 + os_str_len(x),
            VerbatimUNC(x,y) => 8 + os_str_len(x) +
                if os_str_len(y) > 0 { 1 + os_str_len(y) }
                else { 0 },
            VerbatimDisk(_) => 6,
            UNC(x,y) => 2 + os_str_len(x) +
                if os_str_len(y) > 0 { 1 + os_str_len(y) }
                else { 0 },
            DeviceNS(x) => 4 + os_str_len(x),
            Disk(_) => 2
A
Aaron Turon 已提交
311 312
        }

A
Aaron Turon 已提交
313 314 315 316
    }

    /// Determine if the prefix is verbatim, i.e. begins `\\?\`.
    #[inline]
A
Aaron Turon 已提交
317
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
318 319 320 321 322
    pub fn is_verbatim(&self) -> bool {
        use self::Prefix::*;
        match *self {
            Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
            _ => false
A
Aaron Turon 已提交
323 324 325
        }
    }

A
Aaron Turon 已提交
326 327 328 329 330
    #[inline]
    fn is_drive(&self) -> bool {
        match *self {
            Prefix::Disk(_) => true,
            _ => false,
A
Aaron Turon 已提交
331 332 333
        }
    }

A
Aaron Turon 已提交
334 335 336 337
    #[inline]
    fn has_implicit_root(&self) -> bool {
        !self.is_drive()
    }
A
Aaron Turon 已提交
338 339
}

A
Aaron Turon 已提交
340 341 342 343 344 345
////////////////////////////////////////////////////////////////////////////////
// Exposed parsing helpers
////////////////////////////////////////////////////////////////////////////////

/// Determine whether the character is one of the permitted path
/// separators for the current platform.
A
Aaron Turon 已提交
346
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
347 348 349
pub fn is_separator(c: char) -> bool {
    use ascii::*;
    c.is_ascii() && is_sep_byte(c as u8)
A
Aaron Turon 已提交
350 351
}

A
Aaron Turon 已提交
352
/// The primary sperator for the current platform
A
Aaron Turon 已提交
353
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
354 355
pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;

A
Aaron Turon 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
////////////////////////////////////////////////////////////////////////////////
// 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`.
fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
    I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
{
    loop {
        let mut iter_next = iter.clone();
        match (iter_next.next(), prefix.next()) {
            (Some(x), Some(y)) => {
                if x != y { return None }
            }
            (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] {
    unsafe { mem::transmute(s) }
}
unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
    mem::transmute(s)
}

////////////////////////////////////////////////////////////////////////////////
A
Aaron Turon 已提交
389
// Cross-platform, iterator-independent parsing
A
Aaron Turon 已提交
390 391 392 393 394
////////////////////////////////////////////////////////////////////////////////

/// Says whether the first byte after the prefix is a separator.
fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
    let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
A
Aaron Turon 已提交
395
    path.len() > 0 && is_sep_byte(path[0])
A
Aaron Turon 已提交
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
}

// basic workhorse for splitting stem and extension
#[allow(unused_unsafe)] // FIXME
fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
    unsafe {
        if os_str_as_u8_slice(file) == b".." { return (Some(file), None) }

        // 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.

        let mut iter = os_str_as_u8_slice(file).rsplitn(1, |b| *b == b'.');
        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 已提交
429 430
/// 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 已提交
431
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
A
Aaron Turon 已提交
432 433
enum State {
    Prefix = 0,         // c:
A
Aaron Turon 已提交
434
    StartDir = 1,       // / or . or nothing
A
Aaron Turon 已提交
435
    Body = 2,           // foo/bar/baz
A
Aaron Turon 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    Done = 3,
}

/// A Windows path prefix, e.g. `C:` or `\server\share`.
///
/// Does not occur on Unix.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy, Clone, Eq, Hash, Debug)]
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> {
    /// The parsed prefix data.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn kind(&self) -> Prefix<'a> {
        self.parsed
    }

    /// The raw `OsStr` slice for this prefix.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn as_os_str(&self) -> &'a OsStr {
        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 已提交
485 486 487 488 489 490
}

/// A single component of a path.
///
/// See the module documentation for an in-depth explanation of components and
/// their role in the API.
A
Alex Crichton 已提交
491
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
A
Aaron Turon 已提交
492
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
493
pub enum Component<'a> {
A
Aaron Turon 已提交
494 495 496
    /// A Windows path prefix, e.g. `C:` or `\server\share`.
    ///
    /// Does not occur on Unix.
A
Aaron Turon 已提交
497 498
    #[stable(feature = "rust1", since = "1.0.0")]
    Prefix(PrefixComponent<'a>),
A
Aaron Turon 已提交
499 500

    /// The root directory component, appears after any prefix and before anything else
A
Aaron Turon 已提交
501
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
502 503 504
    RootDir,

    /// A reference to the current directory, i.e. `.`
A
Aaron Turon 已提交
505
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
506 507 508
    CurDir,

    /// A reference to the parent directory, i.e. `..`
A
Aaron Turon 已提交
509
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
510 511 512
    ParentDir,

    /// A normal component, i.e. `a` and `b` in `a/b`
A
Aaron Turon 已提交
513
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
514 515 516 517 518
    Normal(&'a OsStr),
}

impl<'a> Component<'a> {
    /// Extract the underlying `OsStr` slice
A
Aaron Turon 已提交
519
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
520 521
    pub fn as_os_str(self) -> &'a OsStr {
        match self {
A
Aaron Turon 已提交
522
            Component::Prefix(p) => p.as_os_str(),
A
Aaron Turon 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535
            Component::RootDir => OsStr::from_str(MAIN_SEP_STR),
            Component::CurDir => OsStr::from_str("."),
            Component::ParentDir => OsStr::from_str(".."),
            Component::Normal(path) => path,
        }
    }
}

/// The core iterator giving the components of a path.
///
/// See the module documentation for an in-depth explanation of components and
/// their role in the API.
#[derive(Clone)]
A
Aaron Turon 已提交
536
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
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,
}

/// An iterator over the components of a path, as `OsStr` slices.
#[derive(Clone)]
A
Aaron Turon 已提交
557
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
pub struct Iter<'a> {
    inner: Components<'a>
}

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 {
        if self.front == State::Prefix { self.prefix_len() }
        else { 0 }
    }

A
Aaron Turon 已提交
581 582 583 584 585 586
    // Given the iteration so far, how much of the pre-State::Body path is left?
    #[inline]
    fn len_before_body(&self) -> usize {
        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 };
        self.prefix_remaining() + root + cur_dir
A
Aaron Turon 已提交
587 588 589 590 591 592 593 594 595
    }

    // 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 已提交
596
    fn is_sep_byte(&self, b: u8) -> bool {
A
Aaron Turon 已提交
597 598 599
        if self.prefix_verbatim() {
            is_verbatim_sep(b)
        } else {
A
Aaron Turon 已提交
600
            is_sep_byte(b)
A
Aaron Turon 已提交
601 602 603 604 605 606 607 608
        }
    }

    /// Extract a slice corresponding to the portion of the path remaining for iteration.
    pub fn as_path(&self) -> &'a Path {
        let mut comps = self.clone();
        if comps.front == State::Body { comps.trim_left(); }
        if comps.back == State::Body { comps.trim_right(); }
A
Aaron Turon 已提交
609
        unsafe { Path::from_u8_slice(comps.path) }
A
Aaron Turon 已提交
610 611 612 613 614 615 616 617 618 619 620
    }

    /// Is the *original* path rooted?
    fn has_root(&self) -> bool {
        if self.has_physical_root { return true }
        if let Some(p) = self.prefix {
            if p.has_implicit_root() { return true }
        }
        false
    }

A
Aaron Turon 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    /// Should the normalized path include a leading . ?
    fn include_cur_dir(&self) -> bool {
        if self.has_root() { return false }
        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),
            _ => false
        }
    }

    // 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,
            _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) }))
        }
    }

A
Aaron Turon 已提交
645 646 647 648
    // 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 已提交
649
        let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
A
Aaron Turon 已提交
650 651 652
            None => (0, self.path),
            Some(i) => (1, &self.path[.. i]),
        };
A
Aaron Turon 已提交
653
        (comp.len() + extra, self.parse_single_component(comp))
A
Aaron Turon 已提交
654 655 656 657 658 659
    }

    // 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 已提交
660
        let start = self.len_before_body();
A
Aaron Turon 已提交
661
        let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
A
Aaron Turon 已提交
662 663 664
            None => (0, &self.path[start ..]),
            Some(i) => (1, &self.path[start + i + 1 ..]),
        };
A
Aaron Turon 已提交
665
        (comp.len() + extra, self.parse_single_component(comp))
A
Aaron Turon 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    }

    // trim away repeated separators (i.e. emtpy components) on the left
    fn trim_left(&mut self) {
        while !self.path.is_empty() {
            let (size, comp) = self.parse_next_component();
            if comp.is_some() {
                return;
            } else {
                self.path = &self.path[size ..];
            }
        }
    }

    // trim away repeated separators (i.e. emtpy components) on the right
    fn trim_right(&mut self) {
A
Aaron Turon 已提交
682
        while self.path.len() > self.len_before_body() {
A
Aaron Turon 已提交
683 684 685 686 687 688 689 690 691 692
            let (size, comp) = self.parse_next_component_back();
            if comp.is_some() {
                return;
            } else {
                self.path = &self.path[.. self.path.len() - size];
            }
        }
    }

    /// Examine the next component without consuming it.
A
Aaron Turon 已提交
693
    #[unstable(feature = "path_components_peek")]
A
Aaron Turon 已提交
694 695 696 697 698 699 700
    pub fn peek(&self) -> Option<Component<'a>> {
        self.clone().next()
    }
}

impl<'a> Iter<'a> {
    /// Extract a slice corresponding to the portion of the path remaining for iteration.
A
Aaron Turon 已提交
701
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
702 703 704 705 706
    pub fn as_path(&self) -> &'a Path {
        self.inner.as_path()
    }
}

A
Aaron Turon 已提交
707
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
708 709 710 711 712 713 714 715
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 已提交
716
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
717 718 719 720 721 722
impl<'a> DoubleEndedIterator for Iter<'a> {
    fn next_back(&mut self) -> Option<&'a OsStr> {
        self.inner.next_back().map(Component::as_os_str)
    }
}

A
Aaron Turon 已提交
723
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
724 725 726 727 728 729 730
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 已提交
731
                    self.front = State::StartDir;
A
Aaron Turon 已提交
732
                    debug_assert!(self.prefix_len() <= self.path.len());
A
Aaron Turon 已提交
733
                    let raw = &self.path[.. self.prefix_len()];
A
Aaron Turon 已提交
734
                    self.path = &self.path[self.prefix_len() .. ];
A
Aaron Turon 已提交
735
                    return Some(Component::Prefix(PrefixComponent {
A
Aaron Turon 已提交
736 737
                        raw: unsafe { u8_slice_as_os_str(raw) },
                        parsed: self.prefix.unwrap()
A
Aaron Turon 已提交
738
                    }))
A
Aaron Turon 已提交
739 740
                }
                State::Prefix => {
A
Aaron Turon 已提交
741
                    self.front = State::StartDir;
A
Aaron Turon 已提交
742
                }
A
Aaron Turon 已提交
743
                State::StartDir => {
A
Aaron Turon 已提交
744 745 746 747 748 749 750 751 752
                    self.front = State::Body;
                    if self.has_physical_root {
                        debug_assert!(self.path.len() > 0);
                        self.path = &self.path[1..];
                        return Some(Component::RootDir)
                    } else if let Some(p) = self.prefix {
                        if p.has_implicit_root() && !p.is_verbatim() {
                            return Some(Component::RootDir)
                        }
A
Aaron Turon 已提交
753 754 755 756
                    } else if self.include_cur_dir() {
                        debug_assert!(self.path.len() > 0);
                        self.path = &self.path[1..];
                        return Some(Component::CurDir)
A
Aaron Turon 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
                    }
                }
                State::Body if !self.path.is_empty() => {
                    let (size, comp) = self.parse_next_component();
                    self.path = &self.path[size ..];
                    if comp.is_some() { return comp }
                }
                State::Body => {
                    self.front = State::Done;
                }
                State::Done => unreachable!()
            }
        }
        None
    }
}

A
Aaron Turon 已提交
774
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
775 776 777 778
impl<'a> DoubleEndedIterator for Components<'a> {
    fn next_back(&mut self) -> Option<Component<'a>> {
        while !self.finished() {
            match self.back {
A
Aaron Turon 已提交
779
                State::Body if self.path.len() > self.len_before_body() => {
A
Aaron Turon 已提交
780 781 782 783 784
                    let (size, comp) = self.parse_next_component_back();
                    self.path = &self.path[.. self.path.len() - size];
                    if comp.is_some() { return comp }
                }
                State::Body => {
A
Aaron Turon 已提交
785
                    self.back = State::StartDir;
A
Aaron Turon 已提交
786
                }
A
Aaron Turon 已提交
787
                State::StartDir => {
A
Aaron Turon 已提交
788 789 790 791 792 793 794 795
                    self.back = State::Prefix;
                    if self.has_physical_root {
                        self.path = &self.path[.. self.path.len() - 1];
                        return Some(Component::RootDir)
                    } else if let Some(p) = self.prefix {
                        if p.has_implicit_root() && !p.is_verbatim() {
                            return Some(Component::RootDir)
                        }
A
Aaron Turon 已提交
796 797 798
                    } else if self.include_cur_dir() {
                        self.path = &self.path[.. self.path.len() - 1];
                        return Some(Component::CurDir)
A
Aaron Turon 已提交
799 800 801 802
                    }
                }
                State::Prefix if self.prefix_len() > 0 => {
                    self.back = State::Done;
A
Aaron Turon 已提交
803
                    return Some(Component::Prefix(PrefixComponent {
A
Aaron Turon 已提交
804 805
                        raw: unsafe { u8_slice_as_os_str(self.path) },
                        parsed: self.prefix.unwrap()
A
Aaron Turon 已提交
806
                    }))
A
Aaron Turon 已提交
807 808 809 810 811 812 813 814 815 816 817 818
                }
                State::Prefix => {
                    self.back = State::Done;
                    return None
                }
                State::Done => unreachable!()
            }
        }
        None
    }
}

A
Aaron Turon 已提交
819
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
820 821 822 823 824 825
impl<'a> cmp::PartialEq for Components<'a> {
    fn eq(&self, other: &Components<'a>) -> bool {
        iter::order::eq(self.clone(), other.clone())
    }
}

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

A
Aaron Turon 已提交
829
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
830 831 832 833 834 835
impl<'a> cmp::PartialOrd for Components<'a> {
    fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
        iter::order::partial_cmp(self.clone(), other.clone())
    }
}

A
Aaron Turon 已提交
836
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
impl<'a> cmp::Ord for Components<'a> {
    fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
        iter::order::cmp(self.clone(), other.clone())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Basic types and traits
////////////////////////////////////////////////////////////////////////////////

/// An owned, mutable path (akin to `String`).
///
/// 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.
///
/// More details about the overall approach can be found in
/// the module documentation.
///
S
Steve Klabnik 已提交
856
/// # Examples
A
Aaron Turon 已提交
857 858 859 860 861 862 863 864 865 866
///
/// ```rust
/// use std::path::PathBuf;
///
/// let mut path = PathBuf::new("c:\\");
/// path.push("windows");
/// path.push("system32");
/// path.set_extension("dll");
/// ```
#[derive(Clone, Hash)]
A
Aaron Turon 已提交
867
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
868 869 870 871 872 873 874 875 876 877 878
pub struct PathBuf {
    inner: OsString
}

impl PathBuf {
    fn as_mut_vec(&mut self) -> &mut Vec<u8> {
        unsafe { mem::transmute(self) }
    }

    /// Allocate a `PathBuf` with initial contents given by the
    /// argument.
A
Aaron Turon 已提交
879
    #[stable(feature = "rust1", since = "1.0.0")]
880
    pub fn new<S: AsOsStr>(s: S) -> PathBuf {
A
Aaron Turon 已提交
881 882 883 884 885 886 887 888 889 890 891 892
        PathBuf { inner: s.as_os_str().to_os_string() }
    }

    /// Extend `self` with `path`.
    ///
    /// 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`.
    /// * if `path` has a prefix but no root, it replaces `self.
A
Aaron Turon 已提交
893
    #[stable(feature = "rust1", since = "1.0.0")]
894
    pub fn push<P: AsPath>(&mut self, path: P) {
A
Aaron Turon 已提交
895 896
        let path = path.as_path();

A
Aaron Turon 已提交
897
        // in general, a separator is needed if the rightmost byte is not a separator
A
Aaron Turon 已提交
898
        let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
A
Aaron Turon 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921

        // in the special case of `C:` on Windows, do *not* add a separator
        {
            let comps = self.components();
            if comps.prefix_len() > 0 &&
                comps.prefix_len() == comps.path.len() &&
                comps.prefix.unwrap().is_drive()
            {
                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 已提交
922
            self.inner.push(MAIN_SEP_STR);
A
Aaron Turon 已提交
923 924
        }

A
Alex Crichton 已提交
925
        self.inner.push(path);
A
Aaron Turon 已提交
926 927 928 929
    }

    /// Truncate `self` to `self.parent()`.
    ///
A
Aaron Turon 已提交
930
    /// Returns false and does nothing if `self.file_name()` is `None`.
B
Ben S 已提交
931
    /// Otherwise, returns `true`.
A
Aaron Turon 已提交
932
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
    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
            }
            None => false
        }
    }

    /// Updates `self.file_name()` to `file_name`.
    ///
    /// If `self.file_name()` was `None`, this is equivalent to pushing
    /// `file_name`.
    ///
    /// # Examples
    ///
    /// ```rust
A
Aaron Turon 已提交
951
    /// use std::path::PathBuf;
A
Aaron Turon 已提交
952
    ///
A
Aaron Turon 已提交
953
    /// let mut buf = PathBuf::new("/");
A
Aaron Turon 已提交
954 955
    /// assert!(buf.file_name() == None);
    /// buf.set_file_name("bar");
A
Aaron Turon 已提交
956
    /// assert!(buf == PathBuf::new("/bar"));
A
Aaron Turon 已提交
957 958
    /// assert!(buf.file_name().is_some());
    /// buf.set_file_name("baz.txt");
A
Aaron Turon 已提交
959
    /// assert!(buf == PathBuf::new("/baz.txt"));
A
Aaron Turon 已提交
960
    /// ```
A
Aaron Turon 已提交
961
    #[stable(feature = "rust1", since = "1.0.0")]
962
    pub fn set_file_name<S: AsOsStr>(&mut self, file_name: S) {
A
Aaron Turon 已提交
963 964 965
        if self.file_name().is_some() {
            let popped = self.pop();
            debug_assert!(popped);
A
Aaron Turon 已提交
966 967 968 969 970 971 972 973
        }
        self.push(file_name.as_os_str());
    }

    /// Updates `self.extension()` to `extension`.
    ///
    /// If `self.file_name()` is `None`, does nothing and returns `false`.
    ///
J
Joseph Crail 已提交
974
    /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
A
Aaron Turon 已提交
975
    /// is added; otherwise it is replaced.
A
Aaron Turon 已提交
976
    #[stable(feature = "rust1", since = "1.0.0")]
977
    pub fn set_extension<S: AsOsStr>(&mut self, extension: S) -> bool {
A
Aaron Turon 已提交
978 979 980 981 982 983 984 985 986
        if self.file_name().is_none() { return false; }

        let mut stem = match self.file_stem() {
            Some(stem) => stem.to_os_string(),
            None => OsString::from_str(""),
        };

        let extension = extension.as_os_str();
        if os_str_as_u8_slice(extension).len() > 0 {
A
Alex Crichton 已提交
987 988
            stem.push(".");
            stem.push(extension);
A
Aaron Turon 已提交
989 990 991 992 993
        }
        self.set_file_name(&stem);

        true
    }
A
Aaron Turon 已提交
994 995

    /// Consume the `PathBuf`, yielding its internal `OsString` storage
A
Aaron Turon 已提交
996
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
997 998 999
    pub fn into_os_string(self) -> OsString {
        self.inner
    }
A
Aaron Turon 已提交
1000 1001
}

A
Aaron Turon 已提交
1002
#[stable(feature = "rust1", since = "1.0.0")]
1003 1004
impl<P: AsPath> iter::FromIterator<P> for PathBuf {
    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
A
Aaron Turon 已提交
1005 1006 1007 1008 1009 1010
        let mut buf = PathBuf::new("");
        buf.extend(iter);
        buf
    }
}

A
Aaron Turon 已提交
1011
#[stable(feature = "rust1", since = "1.0.0")]
1012 1013
impl<P: AsPath> iter::Extend<P> for PathBuf {
    fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
A
Aaron Turon 已提交
1014 1015 1016 1017 1018 1019
        for p in iter {
            self.push(p)
        }
    }
}

A
Aaron Turon 已提交
1020
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1021 1022 1023 1024 1025 1026
impl fmt::Debug for PathBuf {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        fmt::Debug::fmt(&**self, formatter)
    }
}

A
Aaron Turon 已提交
1027
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1028 1029 1030 1031
impl ops::Deref for PathBuf {
    type Target = Path;

    fn deref(&self) -> &Path {
1032
        unsafe { mem::transmute(&self.inner[..]) }
A
Aaron Turon 已提交
1033 1034 1035
    }
}

A
Aaron Turon 已提交
1036
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1037 1038 1039
impl Borrow<Path> for PathBuf {
    fn borrow(&self) -> &Path {
        self.deref()
A
Aaron Turon 已提交
1040 1041 1042
    }
}

A
Aaron Turon 已提交
1043
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1044 1045 1046 1047 1048 1049
impl IntoCow<'static, Path> for PathBuf {
    fn into_cow(self) -> Cow<'static, Path> {
        Cow::Owned(self)
    }
}

A
Aaron Turon 已提交
1050
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1051 1052 1053 1054 1055 1056
impl<'a> IntoCow<'a, Path> for &'a Path {
    fn into_cow(self) -> Cow<'a, Path> {
        Cow::Borrowed(self)
    }
}

A
Aaron Turon 已提交
1057
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1058 1059 1060 1061 1062
impl ToOwned for Path {
    type Owned = PathBuf;
    fn to_owned(&self) -> PathBuf { self.to_path_buf() }
}

A
Aaron Turon 已提交
1063
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1064 1065 1066 1067 1068 1069
impl cmp::PartialEq for PathBuf {
    fn eq(&self, other: &PathBuf) -> bool {
        self.components() == other.components()
    }
}

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

A
Aaron Turon 已提交
1073
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1074 1075 1076 1077 1078 1079
impl cmp::PartialOrd for PathBuf {
    fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
        self.components().partial_cmp(&other.components())
    }
}

A
Aaron Turon 已提交
1080
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1081 1082 1083 1084 1085 1086
impl cmp::Ord for PathBuf {
    fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
        self.components().cmp(&other.components())
    }
}

A
Aaron Turon 已提交
1087
#[stable(feature = "rust1", since = "1.0.0")]
A
Alex Crichton 已提交
1088 1089
impl AsOsStr for PathBuf {
    fn as_os_str(&self) -> &OsStr {
1090
        &self.inner[..]
A
Alex Crichton 已提交
1091 1092 1093
    }
}

A
Aaron Turon 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
/// A slice of a path (akin to `str`).
///
/// This type supports a number of operations for inspecting a path, including
/// breaking the path into its components (separated by `/` or `\`, depending on
/// the platform), extracting the file name, determining whether the path is
/// absolute, and so on. More details about the overall approach can be found in
/// the module documentation.
///
/// This is an *unsized* type, meaning that it must always be used with behind a
/// pointer like `&` or `Box`.
///
S
Steve Klabnik 已提交
1105
/// # Examples
A
Aaron Turon 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
///
/// ```rust
/// use std::path::Path;
///
/// let path = Path::new("/tmp/foo/bar.txt");
/// let file = path.file_name();
/// let extension = path.extension();
/// let parent_dir = path.parent();
/// ```
///
1116
#[derive(Hash)]
A
Aaron Turon 已提交
1117
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
pub struct Path {
    inner: OsStr
}

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 {
        mem::transmute(s)
    }
    // The following (private!) function reveals the byte encoding used for OsStr.
    fn as_u8_slice(&self) -> &[u8] {
        unsafe { mem::transmute(self) }
    }

    /// Directly wrap a string slice as a `Path` slice.
    ///
    /// This is a cost-free conversion.
A
Aaron Turon 已提交
1136
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1137 1138 1139 1140 1141 1142 1143
    pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path {
        unsafe { mem::transmute(s.as_os_str()) }
    }

    /// Yield a `&str` slice if the `Path` is valid unicode.
    ///
    /// This conversion may entail doing a check for UTF-8 validity.
A
Aaron Turon 已提交
1144
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1145 1146 1147 1148
    pub fn to_str(&self) -> Option<&str> {
        self.inner.to_str()
    }

A
Aaron Turon 已提交
1149
    /// Convert a `Path` to a `Cow<str>`.
A
Aaron Turon 已提交
1150 1151
    ///
    /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
A
Aaron Turon 已提交
1152
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1153
    pub fn to_string_lossy(&self) -> Cow<str> {
A
Aaron Turon 已提交
1154 1155 1156 1157
        self.inner.to_string_lossy()
    }

    /// Convert a `Path` to an owned `PathBuf`.
A
Aaron Turon 已提交
1158
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1159 1160 1161 1162
    pub fn to_path_buf(&self) -> PathBuf {
        PathBuf::new(self)
    }

J
Joseph Crail 已提交
1163
    /// A path is *absolute* if it is independent of the current directory.
A
Aaron Turon 已提交
1164 1165 1166 1167 1168 1169 1170
    ///
    /// * On Unix, a path is absolute if it starts with the root, so
    /// `is_absolute` and `has_root` are equivalent.
    ///
    /// * On Windows, a path is absolute if it has a prefix and starts with the
    /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
    /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
A
Aaron Turon 已提交
1171
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1172 1173 1174 1175 1176 1177
    pub fn is_absolute(&self) -> bool {
        self.has_root() &&
            (cfg!(unix) || self.prefix().is_some())
    }

    /// A path is *relative* if it is not absolute.
A
Aaron Turon 已提交
1178
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187
    pub fn is_relative(&self) -> bool {
        !self.is_absolute()
    }

    /// Returns the *prefix* of a path, if any.
    ///
    /// Prefixes are relevant only for Windows paths, and consist of volumes
    /// like `C:`, UNC prefixes like `\\server`, and others described in more
    /// detail in `std::os::windows::PathExt`.
A
Aaron Turon 已提交
1188 1189 1190
    #[unstable(feature = "path_prefix", reason = "uncertain whether to expose this convenience")]
    pub fn prefix(&self) -> Option<Prefix> {
        self.components().prefix
A
Aaron Turon 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    }

    /// A path has a root if the body of the path begins with the directory separator.
    ///
    /// * On Unix, a path has a root if it begins with `/`.
    ///
    /// * On Windows, a path has a root if it:
    ///     * has no prefix and begins with a separator, e.g. `\\windows`
    ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
    ///     * has any non-disk prefix, e.g. `\\server\share`
A
Aaron Turon 已提交
1201
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1202 1203 1204 1205
    pub fn has_root(&self) -> bool {
         self.components().has_root()
    }

A
Aaron Turon 已提交
1206
    /// The path without its final component, if any.
A
Aaron Turon 已提交
1207
    ///
A
Aaron Turon 已提交
1208
    /// Returns `None` if the path terminates in a root or prefix.
A
Aaron Turon 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::path::Path;
    ///
    /// let path = Path::new("/foo/bar");
    /// let foo = path.parent().unwrap();
    /// assert!(foo == Path::new("/foo"));
    /// let root = foo.parent().unwrap();
    /// assert!(root == Path::new("/"));
    /// assert!(root.parent() == None);
    /// ```
A
Aaron Turon 已提交
1222
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1223 1224 1225
    pub fn parent(&self) -> Option<&Path> {
        let mut comps = self.components();
        let comp = comps.next_back();
A
Aaron Turon 已提交
1226 1227 1228 1229 1230 1231
        comp.and_then(|p| match p {
            Component::Normal(_) |
            Component::CurDir |
            Component::ParentDir => Some(comps.as_path()),
            _ => None
        })
A
Aaron Turon 已提交
1232 1233 1234 1235 1236
    }

    /// The final component of the path, if it is a normal file.
    ///
    /// If the path terminates in `.`, `..`, or consists solely or a root of
A
Aaron Turon 已提交
1237 1238
    /// prefix, `file_name` will return `None`.
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1239 1240 1241 1242 1243 1244 1245 1246
    pub fn file_name(&self) -> Option<&OsStr> {
        self.components().next_back().and_then(|p| match p {
            Component::Normal(p) => Some(p.as_os_str()),
            _ => None
        })
    }

    /// Returns a path that, when joined onto `base`, yields `self`.
A
Aaron Turon 已提交
1247
    #[unstable(feature = "path_relative_from", reason = "see #23284")]
A
Aaron Turon 已提交
1248 1249 1250 1251 1252 1253 1254
    pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where
        P: AsPath
    {
        iter_after(self.components(), base.as_path().components()).map(|c| c.as_path())
    }

    /// Determines whether `base` is a prefix of `self`.
A
Aaron Turon 已提交
1255
    #[stable(feature = "rust1", since = "1.0.0")]
1256
    pub fn starts_with<P: AsPath>(&self, base: P) -> bool {
A
Aaron Turon 已提交
1257 1258 1259
        iter_after(self.components(), base.as_path().components()).is_some()
    }

1260
    /// Determines whether `child` is a suffix of `self`.
A
Aaron Turon 已提交
1261
    #[stable(feature = "rust1", since = "1.0.0")]
1262
    pub fn ends_with<P: AsPath>(&self, child: P) -> bool {
A
Aaron Turon 已提交
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        iter_after(self.components().rev(), child.as_path().components().rev()).is_some()
    }

    /// Extract the stem (non-extension) portion of `self.file()`.
    ///
    /// The stem is:
    ///
    /// * None, if there is no file name;
    /// * 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 `.`
A
Aaron Turon 已提交
1274
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
    pub fn file_stem(&self) -> Option<&OsStr> {
        self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
    }

    /// Extract the extension of `self.file()`, if possible.
    ///
    /// The extension is:
    ///
    /// * 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;
    /// * Otherwise, the portion of the file name after the final `.`
A
Aaron Turon 已提交
1287
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1288 1289 1290 1291 1292 1293 1294
    pub fn extension(&self) -> Option<&OsStr> {
        self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
    }

    /// 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 已提交
1295
    #[stable(feature = "rust1", since = "1.0.0")]
1296
    pub fn join<P: AsPath>(&self, path: P) -> PathBuf {
A
Aaron Turon 已提交
1297 1298 1299 1300 1301 1302 1303 1304
        let mut buf = self.to_path_buf();
        buf.push(path);
        buf
    }

    /// Creates an owned `PathBuf` like `self` but with the given file name.
    ///
    /// See `PathBuf::set_file_name` for more details.
A
Aaron Turon 已提交
1305
    #[stable(feature = "rust1", since = "1.0.0")]
1306
    pub fn with_file_name<S: AsOsStr>(&self, file_name: S) -> PathBuf {
A
Aaron Turon 已提交
1307 1308 1309 1310 1311 1312 1313 1314
        let mut buf = self.to_path_buf();
        buf.set_file_name(file_name);
        buf
    }

    /// Creates an owned `PathBuf` like `self` but with the given extension.
    ///
    /// See `PathBuf::set_extension` for more details.
A
Aaron Turon 已提交
1315
    #[stable(feature = "rust1", since = "1.0.0")]
1316
    pub fn with_extension<S: AsOsStr>(&self, extension: S) -> PathBuf {
A
Aaron Turon 已提交
1317 1318 1319 1320 1321 1322
        let mut buf = self.to_path_buf();
        buf.set_extension(extension);
        buf
    }

    /// Produce an iterator over the components of the path.
A
Aaron Turon 已提交
1323
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1324 1325 1326 1327 1328 1329 1330
    pub fn components(&self) -> Components {
        let prefix = parse_prefix(self.as_os_str());
        Components {
            path: self.as_u8_slice(),
            prefix: prefix,
            has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
            front: State::Prefix,
A
Aaron Turon 已提交
1331
            back: State::Body,
A
Aaron Turon 已提交
1332 1333 1334 1335
        }
    }

    /// Produce an iterator over the path's components viewed as `OsStr` slices.
A
Aaron Turon 已提交
1336
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1337 1338 1339 1340 1341 1342
    pub fn iter(&self) -> Iter {
        Iter { inner: self.components() }
    }

    /// Returns an object that implements `Display` for safely printing paths
    /// that may contain non-Unicode data.
A
Aaron Turon 已提交
1343
    #[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1344 1345 1346 1347 1348
    pub fn display(&self) -> Display {
        Display { path: self }
    }
}

A
Aaron Turon 已提交
1349
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1350 1351 1352 1353 1354 1355
impl AsOsStr for Path {
    fn as_os_str(&self) -> &OsStr {
        &self.inner
    }
}

A
Aaron Turon 已提交
1356
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1357 1358 1359 1360 1361 1362 1363
impl fmt::Debug for Path {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.inner.fmt(formatter)
    }
}

/// Helper struct for safely printing paths with `format!()` and `{}`
A
Aaron Turon 已提交
1364
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1365 1366 1367 1368
pub struct Display<'a> {
    path: &'a Path
}

A
Aaron Turon 已提交
1369
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1370 1371 1372 1373 1374 1375
impl<'a> fmt::Debug for Display<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.path.to_string_lossy(), f)
    }
}

A
Aaron Turon 已提交
1376
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1377 1378 1379 1380 1381 1382
impl<'a> fmt::Display for Display<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.path.to_string_lossy(), f)
    }
}

A
Aaron Turon 已提交
1383
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1384 1385 1386 1387 1388 1389
impl cmp::PartialEq for Path {
    fn eq(&self, other: &Path) -> bool {
        iter::order::eq(self.components(), other.components())
    }
}

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

A
Aaron Turon 已提交
1393
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1394 1395 1396 1397 1398 1399
impl cmp::PartialOrd for Path {
    fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
        self.components().partial_cmp(&other.components())
    }
}

A
Aaron Turon 已提交
1400
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1401 1402 1403 1404 1405 1406 1407
impl cmp::Ord for Path {
    fn cmp(&self, other: &Path) -> cmp::Ordering {
        self.components().cmp(&other.components())
    }
}

/// Freely convertible to a `Path`.
A
Aaron Turon 已提交
1408
#[unstable(feature = "std_misc")]
A
Aaron Turon 已提交
1409 1410
pub trait AsPath {
    /// Convert to a `Path`.
A
Aaron Turon 已提交
1411
    #[unstable(feature = "std_misc")]
A
Aaron Turon 已提交
1412 1413 1414
    fn as_path(&self) -> &Path;
}

A
Aaron Turon 已提交
1415
#[unstable(feature = "std_misc")]
A
Aaron Turon 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
impl<T: AsOsStr + ?Sized> AsPath for T {
    fn as_path(&self) -> &Path { Path::new(self.as_os_str()) }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::prelude::*;
    use string::{ToString, String};
    use vec::Vec;

    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);
            }
        );
    );

J
Jorge Aparicio 已提交
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    #[test]
    fn into_cow() {
        use borrow::{Cow, IntoCow};

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

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

            assert_eq!(static_cow_path, borrowed_cow_path);
        }

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

        assert_eq!(static_cow_path, owned_cow_path);
    }

A
Aaron Turon 已提交
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    #[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 已提交
1547
           parent: Some(""),
A
Aaron Turon 已提交
1548 1549 1550 1551 1552 1553
           file_name: Some("foo"),
           file_stem: Some("foo"),
           extension: None
           );

        t!("/",
A
Aaron Turon 已提交
1554
           iter: ["/"],
A
Aaron Turon 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
           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 已提交
1574
           iter: ["foo"],
A
Aaron Turon 已提交
1575 1576
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1577 1578 1579
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1580 1581 1582 1583
           extension: None
           );

        t!("/foo/",
A
Aaron Turon 已提交
1584
           iter: ["/", "foo"],
A
Aaron Turon 已提交
1585 1586
           has_root: true,
           is_absolute: true,
A
Aaron Turon 已提交
1587 1588 1589
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
           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 已提交
1614
           iter: ["/", "foo"],
A
Aaron Turon 已提交
1615 1616
           has_root: true,
           is_absolute: true,
A
Aaron Turon 已提交
1617 1618 1619
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
           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 已提交
1634
           iter: ["."],
A
Aaron Turon 已提交
1635 1636
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1637
           parent: Some(""),
A
Aaron Turon 已提交
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
           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 已提交
1654
           iter: [".."],
A
Aaron Turon 已提交
1655 1656
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1657
           parent: Some(""),
A
Aaron Turon 已提交
1658 1659 1660 1661 1662 1663
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/.",
A
Aaron Turon 已提交
1664
           iter: ["foo"],
A
Aaron Turon 已提交
1665 1666
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1667 1668 1669
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
           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 已提交
1684
           iter: ["foo"],
A
Aaron Turon 已提交
1685 1686
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1687 1688 1689
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1690 1691 1692 1693
           extension: None
           );

        t!("foo/./bar",
A
Aaron Turon 已提交
1694
           iter: ["foo", "bar"],
A
Aaron Turon 已提交
1695 1696
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1697
           parent: Some("foo"),
A
Aaron Turon 已提交
1698 1699 1700 1701 1702 1703
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("foo/../",
A
Aaron Turon 已提交
1704
           iter: ["foo", ".."],
A
Aaron Turon 已提交
1705 1706
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1707
           parent: Some("foo"),
A
Aaron Turon 已提交
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
           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 已提交
1737
           parent: Some(""),
A
Aaron Turon 已提交
1738 1739 1740 1741 1742 1743
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("./",
A
Aaron Turon 已提交
1744
           iter: ["."],
A
Aaron Turon 已提交
1745 1746
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1747
           parent: Some(""),
A
Aaron Turon 已提交
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
           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 已提交
1774
           iter: ["a", "b"],
A
Aaron Turon 已提交
1775 1776
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1777
           parent: Some("a"),
A
Aaron Turon 已提交
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
           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 已提交
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801

        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 已提交
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
    }

    #[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 已提交
1821
           parent: Some(""),
A
Aaron Turon 已提交
1822 1823 1824 1825 1826 1827
           file_name: Some("foo"),
           file_stem: Some("foo"),
           extension: None
           );

        t!("/",
A
Aaron Turon 已提交
1828
           iter: ["\\"],
A
Aaron Turon 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837
           has_root: true,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\",
A
Aaron Turon 已提交
1838
           iter: ["\\"],
A
Aaron Turon 已提交
1839 1840 1841 1842 1843 1844 1845 1846 1847
           has_root: true,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("c:",
A
Aaron Turon 已提交
1848
           iter: ["c:"],
A
Aaron Turon 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857
           has_root: false,
           is_absolute: false,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("c:\\",
A
Aaron Turon 已提交
1858
           iter: ["c:", "\\"],
A
Aaron Turon 已提交
1859 1860 1861 1862 1863 1864 1865 1866 1867
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("c:/",
A
Aaron Turon 已提交
1868
           iter: ["c:", "\\"],
A
Aaron Turon 已提交
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
           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 已提交
1888
           iter: ["foo"],
A
Aaron Turon 已提交
1889 1890
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1891 1892 1893
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1894 1895 1896 1897
           extension: None
           );

        t!("/foo/",
A
Aaron Turon 已提交
1898
           iter: ["\\", "foo"],
A
Aaron Turon 已提交
1899 1900
           has_root: true,
           is_absolute: false,
A
Aaron Turon 已提交
1901 1902 1903
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
           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 已提交
1928
           iter: ["\\", "foo"],
A
Aaron Turon 已提交
1929 1930
           has_root: true,
           is_absolute: false,
A
Aaron Turon 已提交
1931 1932 1933
           parent: Some("/"),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
           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 已提交
1948
           iter: ["."],
A
Aaron Turon 已提交
1949 1950
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1951
           parent: Some(""),
A
Aaron Turon 已提交
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
           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 已提交
1968
           iter: [".."],
A
Aaron Turon 已提交
1969 1970
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1971
           parent: Some(""),
A
Aaron Turon 已提交
1972 1973 1974 1975 1976 1977
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("foo/.",
A
Aaron Turon 已提交
1978
           iter: ["foo"],
A
Aaron Turon 已提交
1979 1980
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
1981 1982 1983
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
           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 已提交
1998
           iter: ["foo"],
A
Aaron Turon 已提交
1999 2000
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2001 2002 2003
           parent: Some(""),
           file_name: Some("foo"),
           file_stem: Some("foo"),
A
Aaron Turon 已提交
2004 2005 2006 2007
           extension: None
           );

        t!("foo/./bar",
A
Aaron Turon 已提交
2008
           iter: ["foo", "bar"],
A
Aaron Turon 已提交
2009 2010
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2011
           parent: Some("foo"),
A
Aaron Turon 已提交
2012 2013 2014 2015 2016 2017
           file_name: Some("bar"),
           file_stem: Some("bar"),
           extension: None
           );

        t!("foo/../",
A
Aaron Turon 已提交
2018
           iter: ["foo", ".."],
A
Aaron Turon 已提交
2019 2020
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2021
           parent: Some("foo"),
A
Aaron Turon 已提交
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
           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 已提交
2051
           parent: Some(""),
A
Aaron Turon 已提交
2052 2053 2054 2055 2056 2057
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("./",
A
Aaron Turon 已提交
2058
           iter: ["."],
A
Aaron Turon 已提交
2059 2060
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2061
           parent: Some(""),
A
Aaron Turon 已提交
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
           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 已提交
2088
           iter: ["a", "b"],
A
Aaron Turon 已提交
2089 2090
           has_root: false,
           is_absolute: false,
A
Aaron Turon 已提交
2091
           parent: Some("a"),
A
Aaron Turon 已提交
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
           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 已提交
2147
           iter: ["\\\\server\\share", "\\"],
A
Aaron Turon 已提交
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
           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 已提交
2238
           iter: ["\\\\?\\C:", "\\"],
A
Aaron Turon 已提交
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
           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 已提交
2293
           iter: ["\\\\.\\foo", "\\"],
A
Aaron Turon 已提交
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );


        t!("\\\\.\\foo/bar",
A
Aaron Turon 已提交
2304
           iter: ["\\\\.\\foo/bar", "\\"],
A
Aaron Turon 已提交
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
           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 已提交
2326
           iter: ["\\\\.\\", "\\"],
A
Aaron Turon 已提交
2327 2328 2329 2330 2331 2332 2333 2334 2335
           has_root: true,
           is_absolute: true,
           parent: None,
           file_name: None,
           file_stem: None,
           extension: None
           );

        t!("\\\\?\\a\\b\\",
A
Aaron Turon 已提交
2336
           iter: ["\\\\?\\a", "\\", "b"],
A
Aaron Turon 已提交
2337 2338
           has_root: true,
           is_absolute: true,
A
Aaron Turon 已提交
2339 2340 2341
           parent: Some("\\\\?\\a\\"),
           file_name: Some("b"),
           file_stem: Some("b"),
A
Aaron Turon 已提交
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
           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) => ( {
                let mut actual = PathBuf::new($path);
                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");
            tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
            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");
            tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
            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");

            tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
            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) => ( {
                let mut actual = PathBuf::new($path);
                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 已提交
2497 2498
        tp!("foo", "", true);
        tp!(".", "", true);
A
Aaron Turon 已提交
2499 2500 2501
        tp!("/foo", "/", true);
        tp!("/foo/bar", "/foo", true);
        tp!("foo/bar", "foo", true);
A
Aaron Turon 已提交
2502
        tp!("foo/.", "", true);
A
Aaron Turon 已提交
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
        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);
            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);
            tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
            tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
            tp!("\\\\.\\a", "\\\\.\\a", false);

A
Aaron Turon 已提交
2532
            tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
A
Aaron Turon 已提交
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
        }
    }

    #[test]
    pub fn test_set_file_name() {
        macro_rules! tfn(
                ($path:expr, $file:expr, $expected:expr) => ( {
                let mut p = PathBuf::new($path);
                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 已提交
2553 2554
        if cfg!(unix) {
            tfn!(".", "foo", "./foo");
A
Aaron Turon 已提交
2555 2556
            tfn!("foo/", "bar", "bar");
            tfn!("foo/.", "bar", "bar");
A
Alex Crichton 已提交
2557 2558 2559 2560 2561
            tfn!("..", "foo", "../foo");
            tfn!("foo/..", "bar", "foo/../bar");
            tfn!("/", "foo", "/foo");
        } else {
            tfn!(".", "foo", r".\foo");
A
Aaron Turon 已提交
2562 2563
            tfn!(r"foo\", "bar", r"bar");
            tfn!(r"foo\.", "bar", r"bar");
A
Alex Crichton 已提交
2564 2565 2566 2567
            tfn!("..", "foo", r"..\foo");
            tfn!(r"foo\..", "bar", r"foo\..\bar");
            tfn!(r"\", "foo", r"\foo");
        }
A
Aaron Turon 已提交
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
    }

    #[test]
    pub fn test_set_extension() {
        macro_rules! tfe(
                ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
                let mut p = PathBuf::new($path);
                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 已提交
2591 2592
        tfe!("foo/", "bar", "foo.bar", true);
        tfe!("foo/.", "bar", "foo.bar", true);
A
Aaron Turon 已提交
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
        tfe!("..", "foo", "..",  false);
        tfe!("foo/..", "bar", "foo/..", false);
        tfe!("/", "foo", "/", false);
    }

    #[test]
    pub fn test_compare() {
        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);

                 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);

                 let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
                 let exp: Option<&str> = $relative_from;
                 assert!(relative_from == exp,
                         "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
                         exp, relative_from);
            });
        );

        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 已提交
2658
            eq: true,
A
Aaron Turon 已提交
2659
            starts_with: true,
A
Aaron Turon 已提交
2660 2661
            ends_with: true,
            relative_from: Some("")
A
Aaron Turon 已提交
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
            );

        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 已提交
2688 2689
            ends_with: false,
            relative_from: Some("foo/bar")
A
Aaron Turon 已提交
2690
            );
A
Aaron Turon 已提交
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707

        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 已提交
2708 2709
    }
}