]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
Remove alternate stack with sigaltstack before unmapping it.
[rust.git] / src / libstd / path.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Cross-platform path manipulation.
12 //!
13 //! This module provides two types, `PathBuf` and `Path` (akin to `String` and
14 //! `str`), for working with paths abstractly. These types are thin wrappers
15 //! around `OsString` and `OsStr` respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
17 //!
18 //! ## Simple usage
19 //!
20 //! Path manipulation includes both parsing components from slices and building
21 //! new owned paths.
22 //!
23 //! To parse a path, you can create a `Path` slice from a `str`
24 //! slice and start asking questions:
25 //!
26 //! ```rust
27 //! use std::path::Path;
28 //!
29 //! let path = Path::new("/tmp/foo/bar.txt");
30 //! let file = path.file_name();
31 //! let extension = path.extension();
32 //! let parent_dir = path.parent();
33 //! ```
34 //!
35 //! To build or modify paths, use `PathBuf`:
36 //!
37 //! ```rust
38 //! use std::path::PathBuf;
39 //!
40 //! let mut path = PathBuf::from("c:\\");
41 //! path.push("windows");
42 //! path.push("system32");
43 //! path.set_extension("dll");
44 //! ```
45 //!
46 //! ## Path components and normalization
47 //!
48 //! The path APIs are built around the notion of "components", which roughly
49 //! correspond to the substrings between path separators (`/` and, on Windows,
50 //! `\`). The APIs for path parsing are largely specified in terms of the path's
51 //! components, so it's important to clearly understand how those are
52 //! determined.
53 //!
54 //! A path can always be reconstructed into an *equivalent* path by
55 //! putting together its components via `push`. Syntactically, the
56 //! paths may differ by the normalization described below.
57 //!
58 //! ### Component types
59 //!
60 //! Components come in several types:
61 //!
62 //! * Normal components are the default: standard references to files or
63 //! directories. The path `a/b` has two normal components, `a` and `b`.
64 //!
65 //! * Current directory components represent the `.` character. For example,
66 //! `./a` has a current directory component and a normal component `a`.
67 //!
68 //! * The root directory component represents a separator that designates
69 //!   starting from root. For example, `/a/b` has a root directory component
70 //!   followed by normal components `a` and `b`.
71 //!
72 //! On Windows, an additional component type comes into play:
73 //!
74 //! * Prefix components, of which there is a large variety. For example, `C:`
75 //! and `\\server\share` are prefixes. The path `C:windows` has a prefix
76 //! component `C:` and a normal component `windows`; the path `C:\windows` has a
77 //! prefix component `C:`, a root directory component, and a normal component
78 //! `windows`.
79 //!
80 //! ### Normalization
81 //!
82 //! Aside from splitting on the separator(s), there is a small amount of
83 //! "normalization":
84 //!
85 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
86 //!   and `b`.
87 //!
88 //! * Occurrences of `.` are normalized away, *except* if they are at
89 //! the beginning of the path (in which case they are often meaningful
90 //! in terms of path searching). So, for example, `a/./b`, `a/b/`,
91 //! `/a/b/.` and `a/b` all have components `a` and `b`, but `./a/b`
92 //! has a leading current directory component.
93 //!
94 //! No other normalization takes place by default. In particular,
95 //! `a/c` and `a/b/../c` are distinct, to account for the possibility
96 //! that `b` is a symbolic link (so its parent isn't `a`). Further
97 //! normalization is possible to build on top of the components APIs,
98 //! and will be included in this library in the near future.
99
100 #![stable(feature = "rust1", since = "1.0.0")]
101
102 use ascii::*;
103 #[allow(deprecated)]
104 use borrow::{Borrow, IntoCow, ToOwned, Cow};
105 use cmp;
106 use error::Error;
107 use fmt;
108 use fs;
109 use hash::{Hash, Hasher};
110 use io;
111 use iter;
112 use mem;
113 use ops::{self, Deref};
114 use string::String;
115 use vec::Vec;
116
117 use ffi::{OsStr, OsString};
118
119 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
120
121 ////////////////////////////////////////////////////////////////////////////////
122 // GENERAL NOTES
123 ////////////////////////////////////////////////////////////////////////////////
124 //
125 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
126 // taking advantage of the fact that OsStr always encodes ASCII characters
127 // as-is.  Eventually, this transmutation should be replaced by direct uses of
128 // OsStr APIs for parsing, but it will take a while for those to become
129 // available.
130
131 ////////////////////////////////////////////////////////////////////////////////
132 // Platform-specific definitions
133 ////////////////////////////////////////////////////////////////////////////////
134
135 // The following modules give the most basic tools for parsing paths on various
136 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
137
138 #[cfg(unix)]
139 mod platform {
140     use super::Prefix;
141     use ffi::OsStr;
142
143     #[inline]
144     pub fn is_sep_byte(b: u8) -> bool {
145         b == b'/'
146     }
147
148     #[inline]
149     pub fn is_verbatim_sep(b: u8) -> bool {
150         b == b'/'
151     }
152
153     pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
154         None
155     }
156
157     pub const MAIN_SEP_STR: &'static str = "/";
158     pub const MAIN_SEP: char = '/';
159 }
160
161 #[cfg(windows)]
162 mod platform {
163     use ascii::*;
164
165     use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
166     use ffi::OsStr;
167
168     #[inline]
169     pub fn is_sep_byte(b: u8) -> bool {
170         b == b'/' || b == b'\\'
171     }
172
173     #[inline]
174     pub fn is_verbatim_sep(b: u8) -> bool {
175         b == b'\\'
176     }
177
178     pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
179         use super::Prefix::*;
180         unsafe {
181             // The unsafety here stems from converting between &OsStr and &[u8]
182             // and back. This is safe to do because (1) we only look at ASCII
183             // contents of the encoding and (2) new &OsStr values are produced
184             // only from ASCII-bounded slices of existing &OsStr values.
185             let mut path = os_str_as_u8_slice(path);
186
187             if path.starts_with(br"\\") {
188                 // \\
189                 path = &path[2..];
190                 if path.starts_with(br"?\") {
191                     // \\?\
192                     path = &path[2..];
193                     if path.starts_with(br"UNC\") {
194                         // \\?\UNC\server\share
195                         path = &path[4..];
196                         let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
197                             Some((server, share)) =>
198                                 (u8_slice_as_os_str(server), u8_slice_as_os_str(share)),
199                             None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])),
200                         };
201                         return Some(VerbatimUNC(server, share));
202                     } else {
203                         // \\?\path
204                         let idx = path.iter().position(|&b| b == b'\\');
205                         if idx == Some(2) && path[1] == b':' {
206                             let c = path[0];
207                             if c.is_ascii() && (c as char).is_alphabetic() {
208                                 // \\?\C:\ path
209                                 return Some(VerbatimDisk(c.to_ascii_uppercase()));
210                             }
211                         }
212                         let slice = &path[..idx.unwrap_or(path.len())];
213                         return Some(Verbatim(u8_slice_as_os_str(slice)));
214                     }
215                 } else if path.starts_with(b".\\") {
216                     // \\.\path
217                     path = &path[2..];
218                     let pos = path.iter().position(|&b| b == b'\\');
219                     let slice = &path[..pos.unwrap_or(path.len())];
220                     return Some(DeviceNS(u8_slice_as_os_str(slice)));
221                 }
222                 match parse_two_comps(path, is_sep_byte) {
223                     Some((server, share)) if !server.is_empty() && !share.is_empty() => {
224                         // \\server\share
225                         return Some(UNC(u8_slice_as_os_str(server), u8_slice_as_os_str(share)));
226                     }
227                     _ => (),
228                 }
229             } else if path.len() > 1 && path[1] == b':' {
230                 // C:
231                 let c = path[0];
232                 if c.is_ascii() && (c as char).is_alphabetic() {
233                     return Some(Disk(c.to_ascii_uppercase()));
234                 }
235             }
236             return None;
237         }
238
239         fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
240             let first = match path.iter().position(|x| f(*x)) {
241                 None => return None,
242                 Some(x) => &path[..x],
243             };
244             path = &path[(first.len() + 1)..];
245             let idx = path.iter().position(|x| f(*x));
246             let second = &path[..idx.unwrap_or(path.len())];
247             Some((first, second))
248         }
249     }
250
251     pub const MAIN_SEP_STR: &'static str = "\\";
252     pub const MAIN_SEP: char = '\\';
253 }
254
255 ////////////////////////////////////////////////////////////////////////////////
256 // Windows Prefixes
257 ////////////////////////////////////////////////////////////////////////////////
258
259 /// Path prefixes (Windows only).
260 ///
261 /// Windows uses a variety of path styles, including references to drive
262 /// volumes (like `C:`), network shared folders (like `\\server\share`) and
263 /// others. In addition, some path prefixes are "verbatim", in which case
264 /// `/` is *not* treated as a separator and essentially no normalization is
265 /// performed.
266 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub enum Prefix<'a> {
269     /// Prefix `\\?\`, together with the given component immediately following it.
270     #[stable(feature = "rust1", since = "1.0.0")]
271     Verbatim(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
272
273     /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
274     #[stable(feature = "rust1", since = "1.0.0")]
275     VerbatimUNC(
276         #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
277         #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
278     ),
279
280     /// Prefix like `\\?\C:\`, for the given drive letter
281     #[stable(feature = "rust1", since = "1.0.0")]
282     VerbatimDisk(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] u8),
283
284     /// Prefix `\\.\`, together with the given component immediately following it.
285     #[stable(feature = "rust1", since = "1.0.0")]
286     DeviceNS(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
287
288     /// Prefix `\\server\share`, with the given "server" and "share" components.
289     #[stable(feature = "rust1", since = "1.0.0")]
290     UNC(
291         #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
292         #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
293     ),
294
295     /// Prefix `C:` for the given disk drive.
296     #[stable(feature = "rust1", since = "1.0.0")]
297     Disk(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] u8),
298 }
299
300 impl<'a> Prefix<'a> {
301     #[inline]
302     fn len(&self) -> usize {
303         use self::Prefix::*;
304         fn os_str_len(s: &OsStr) -> usize {
305             os_str_as_u8_slice(s).len()
306         }
307         match *self {
308             Verbatim(x) => 4 + os_str_len(x),
309             VerbatimUNC(x, y) => {
310                 8 + os_str_len(x) +
311                 if os_str_len(y) > 0 {
312                     1 + os_str_len(y)
313                 } else {
314                     0
315                 }
316             },
317             VerbatimDisk(_) => 6,
318             UNC(x, y) => {
319                 2 + os_str_len(x) +
320                 if os_str_len(y) > 0 {
321                     1 + os_str_len(y)
322                 } else {
323                     0
324                 }
325             },
326             DeviceNS(x) => 4 + os_str_len(x),
327             Disk(_) => 2,
328         }
329
330     }
331
332     /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
333     #[inline]
334     #[stable(feature = "rust1", since = "1.0.0")]
335     pub fn is_verbatim(&self) -> bool {
336         use self::Prefix::*;
337         match *self {
338             Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
339             _ => false,
340         }
341     }
342
343     #[inline]
344     fn is_drive(&self) -> bool {
345         match *self {
346             Prefix::Disk(_) => true,
347             _ => false,
348         }
349     }
350
351     #[inline]
352     fn has_implicit_root(&self) -> bool {
353         !self.is_drive()
354     }
355 }
356
357 ////////////////////////////////////////////////////////////////////////////////
358 // Exposed parsing helpers
359 ////////////////////////////////////////////////////////////////////////////////
360
361 /// Determines whether the character is one of the permitted path
362 /// separators for the current platform.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use std::path;
368 ///
369 /// assert!(path::is_separator('/'));
370 /// assert!(!path::is_separator('❤'));
371 /// ```
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn is_separator(c: char) -> bool {
374     c.is_ascii() && is_sep_byte(c as u8)
375 }
376
377 /// The primary separator for the current platform
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
380
381 ////////////////////////////////////////////////////////////////////////////////
382 // Misc helpers
383 ////////////////////////////////////////////////////////////////////////////////
384
385 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
386 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
387 // `iter` after having exhausted `prefix`.
388 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
389     where I: Iterator<Item = A> + Clone,
390           J: Iterator<Item = A>,
391           A: PartialEq
392 {
393     loop {
394         let mut iter_next = iter.clone();
395         match (iter_next.next(), prefix.next()) {
396             (Some(x), Some(y)) => {
397                 if x != y {
398                     return None;
399                 }
400             }
401             (Some(_), None) => return Some(iter),
402             (None, None) => return Some(iter),
403             (None, Some(_)) => return None,
404         }
405         iter = iter_next;
406     }
407 }
408
409 // See note at the top of this module to understand why these are used:
410 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
411     unsafe { mem::transmute(s) }
412 }
413 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
414     mem::transmute(s)
415 }
416
417 ////////////////////////////////////////////////////////////////////////////////
418 // Cross-platform, iterator-independent parsing
419 ////////////////////////////////////////////////////////////////////////////////
420
421 /// Says whether the first byte after the prefix is a separator.
422 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
423     let path = if let Some(p) = prefix {
424         &s[p.len()..]
425     } else {
426         s
427     };
428     !path.is_empty() && is_sep_byte(path[0])
429 }
430
431 // basic workhorse for splitting stem and extension
432 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
433     unsafe {
434         if os_str_as_u8_slice(file) == b".." {
435             return (Some(file), None);
436         }
437
438         // The unsafety here stems from converting between &OsStr and &[u8]
439         // and back. This is safe to do because (1) we only look at ASCII
440         // contents of the encoding and (2) new &OsStr values are produced
441         // only from ASCII-bounded slices of existing &OsStr values.
442
443         let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
444         let after = iter.next();
445         let before = iter.next();
446         if before == Some(b"") {
447             (Some(file), None)
448         } else {
449             (before.map(|s| u8_slice_as_os_str(s)),
450              after.map(|s| u8_slice_as_os_str(s)))
451         }
452     }
453 }
454
455 ////////////////////////////////////////////////////////////////////////////////
456 // The core iterators
457 ////////////////////////////////////////////////////////////////////////////////
458
459 /// Component parsing works by a double-ended state machine; the cursors at the
460 /// front and back of the path each keep track of what parts of the path have
461 /// been consumed so far.
462 ///
463 /// Going front to back, a path is made up of a prefix, a starting
464 /// directory component, and a body (of normal components)
465 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
466 enum State {
467     Prefix = 0,         // c:
468     StartDir = 1,       // / or . or nothing
469     Body = 2,           // foo/bar/baz
470     Done = 3,
471 }
472
473 /// A Windows path prefix, e.g. `C:` or `\server\share`.
474 ///
475 /// Does not occur on Unix.
476 #[stable(feature = "rust1", since = "1.0.0")]
477 #[derive(Copy, Clone, Eq, Debug)]
478 pub struct PrefixComponent<'a> {
479     /// The prefix as an unparsed `OsStr` slice.
480     raw: &'a OsStr,
481
482     /// The parsed prefix data.
483     parsed: Prefix<'a>,
484 }
485
486 impl<'a> PrefixComponent<'a> {
487     /// The parsed prefix data.
488     #[stable(feature = "rust1", since = "1.0.0")]
489     pub fn kind(&self) -> Prefix<'a> {
490         self.parsed
491     }
492
493     /// The raw `OsStr` slice for this prefix.
494     #[stable(feature = "rust1", since = "1.0.0")]
495     pub fn as_os_str(&self) -> &'a OsStr {
496         self.raw
497     }
498 }
499
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
502     fn eq(&self, other: &PrefixComponent<'a>) -> bool {
503         cmp::PartialEq::eq(&self.parsed, &other.parsed)
504     }
505 }
506
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
509     fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
510         cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
511     }
512 }
513
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<'a> cmp::Ord for PrefixComponent<'a> {
516     fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
517         cmp::Ord::cmp(&self.parsed, &other.parsed)
518     }
519 }
520
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl<'a> Hash for PrefixComponent<'a> {
523     fn hash<H: Hasher>(&self, h: &mut H) {
524         self.parsed.hash(h);
525     }
526 }
527
528 /// A single component of a path.
529 ///
530 /// See the module documentation for an in-depth explanation of components and
531 /// their role in the API.
532 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub enum Component<'a> {
535     /// A Windows path prefix, e.g. `C:` or `\server\share`.
536     ///
537     /// Does not occur on Unix.
538     #[stable(feature = "rust1", since = "1.0.0")]
539     Prefix(
540         #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] PrefixComponent<'a>
541     ),
542
543     /// The root directory component, appears after any prefix and before anything else
544     #[stable(feature = "rust1", since = "1.0.0")]
545     RootDir,
546
547     /// A reference to the current directory, i.e. `.`
548     #[stable(feature = "rust1", since = "1.0.0")]
549     CurDir,
550
551     /// A reference to the parent directory, i.e. `..`
552     #[stable(feature = "rust1", since = "1.0.0")]
553     ParentDir,
554
555     /// A normal component, i.e. `a` and `b` in `a/b`
556     #[stable(feature = "rust1", since = "1.0.0")]
557     Normal(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
558 }
559
560 impl<'a> Component<'a> {
561     /// Extracts the underlying `OsStr` slice
562     #[stable(feature = "rust1", since = "1.0.0")]
563     pub fn as_os_str(self) -> &'a OsStr {
564         match self {
565             Component::Prefix(p) => p.as_os_str(),
566             Component::RootDir => OsStr::new(MAIN_SEP_STR),
567             Component::CurDir => OsStr::new("."),
568             Component::ParentDir => OsStr::new(".."),
569             Component::Normal(path) => path,
570         }
571     }
572 }
573
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<'a> AsRef<OsStr> for Component<'a> {
576     fn as_ref(&self) -> &OsStr {
577         self.as_os_str()
578     }
579 }
580
581 /// The core iterator giving the components of a path.
582 ///
583 /// See the module documentation for an in-depth explanation of components and
584 /// their role in the API.
585 ///
586 /// # Examples
587 ///
588 /// ```
589 /// use std::path::Path;
590 ///
591 /// let path = Path::new("/tmp/foo/bar.txt");
592 ///
593 /// for component in path.components() {
594 ///     println!("{:?}", component);
595 /// }
596 /// ```
597 #[derive(Clone)]
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub struct Components<'a> {
600     // The path left to parse components from
601     path: &'a [u8],
602
603     // The prefix as it was originally parsed, if any
604     prefix: Option<Prefix<'a>>,
605
606     // true if path *physically* has a root separator; for most Windows
607     // prefixes, it may have a "logical" rootseparator for the purposes of
608     // normalization, e.g.  \\server\share == \\server\share\.
609     has_physical_root: bool,
610
611     // The iterator is double-ended, and these two states keep track of what has
612     // been produced from either end
613     front: State,
614     back: State,
615 }
616
617 /// An iterator over the components of a path, as `OsStr` slices.
618 #[derive(Clone)]
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub struct Iter<'a> {
621     inner: Components<'a>,
622 }
623
624 impl<'a> Components<'a> {
625     // how long is the prefix, if any?
626     #[inline]
627     fn prefix_len(&self) -> usize {
628         self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
629     }
630
631     #[inline]
632     fn prefix_verbatim(&self) -> bool {
633         self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
634     }
635
636     /// how much of the prefix is left from the point of view of iteration?
637     #[inline]
638     fn prefix_remaining(&self) -> usize {
639         if self.front == State::Prefix {
640             self.prefix_len()
641         } else {
642             0
643         }
644     }
645
646     // Given the iteration so far, how much of the pre-State::Body path is left?
647     #[inline]
648     fn len_before_body(&self) -> usize {
649         let root = if self.front <= State::StartDir && self.has_physical_root {
650             1
651         } else {
652             0
653         };
654         let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
655             1
656         } else {
657             0
658         };
659         self.prefix_remaining() + root + cur_dir
660     }
661
662     // is the iteration complete?
663     #[inline]
664     fn finished(&self) -> bool {
665         self.front == State::Done || self.back == State::Done || self.front > self.back
666     }
667
668     #[inline]
669     fn is_sep_byte(&self, b: u8) -> bool {
670         if self.prefix_verbatim() {
671             is_verbatim_sep(b)
672         } else {
673             is_sep_byte(b)
674         }
675     }
676
677     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
678     ///
679     /// # Examples
680     ///
681     /// ```
682     /// use std::path::Path;
683     ///
684     /// let mut components = Path::new("/tmp/foo/bar.txt").components();
685     /// components.next();
686     /// components.next();
687     ///
688     /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
689     /// ```
690     #[stable(feature = "rust1", since = "1.0.0")]
691     pub fn as_path(&self) -> &'a Path {
692         let mut comps = self.clone();
693         if comps.front == State::Body {
694             comps.trim_left();
695         }
696         if comps.back == State::Body {
697             comps.trim_right();
698         }
699         unsafe { Path::from_u8_slice(comps.path) }
700     }
701
702     /// Is the *original* path rooted?
703     fn has_root(&self) -> bool {
704         if self.has_physical_root {
705             return true;
706         }
707         if let Some(p) = self.prefix {
708             if p.has_implicit_root() {
709                 return true;
710             }
711         }
712         false
713     }
714
715     /// Should the normalized path include a leading . ?
716     fn include_cur_dir(&self) -> bool {
717         if self.has_root() {
718             return false;
719         }
720         let mut iter = self.path[self.prefix_len()..].iter();
721         match (iter.next(), iter.next()) {
722             (Some(&b'.'), None) => true,
723             (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
724             _ => false,
725         }
726     }
727
728     // parse a given byte sequence into the corresponding path component
729     fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
730         match comp {
731             b"." if self.prefix_verbatim() => Some(Component::CurDir),
732             b"." => None, // . components are normalized away, except at
733                           // the beginning of a path, which is treated
734                           // separately via `include_cur_dir`
735             b".." => Some(Component::ParentDir),
736             b"" => None,
737             _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
738         }
739     }
740
741     // parse a component from the left, saying how many bytes to consume to
742     // remove the component
743     fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
744         debug_assert!(self.front == State::Body);
745         let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
746             None => (0, self.path),
747             Some(i) => (1, &self.path[..i]),
748         };
749         (comp.len() + extra, self.parse_single_component(comp))
750     }
751
752     // parse a component from the right, saying how many bytes to consume to
753     // remove the component
754     fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
755         debug_assert!(self.back == State::Body);
756         let start = self.len_before_body();
757         let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
758             None => (0, &self.path[start..]),
759             Some(i) => (1, &self.path[start + i + 1..]),
760         };
761         (comp.len() + extra, self.parse_single_component(comp))
762     }
763
764     // trim away repeated separators (i.e. empty components) on the left
765     fn trim_left(&mut self) {
766         while !self.path.is_empty() {
767             let (size, comp) = self.parse_next_component();
768             if comp.is_some() {
769                 return;
770             } else {
771                 self.path = &self.path[size..];
772             }
773         }
774     }
775
776     // trim away repeated separators (i.e. empty components) on the right
777     fn trim_right(&mut self) {
778         while self.path.len() > self.len_before_body() {
779             let (size, comp) = self.parse_next_component_back();
780             if comp.is_some() {
781                 return;
782             } else {
783                 self.path = &self.path[..self.path.len() - size];
784             }
785         }
786     }
787
788     /// Examine the next component without consuming it.
789     #[unstable(feature = "path_components_peek", issue = "27727")]
790     #[rustc_deprecated(reason = "use peekable() instead",
791                        since = "1.6.0")]
792     pub fn peek(&self) -> Option<Component<'a>> {
793         self.clone().next()
794     }
795 }
796
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<'a> AsRef<Path> for Components<'a> {
799     fn as_ref(&self) -> &Path {
800         self.as_path()
801     }
802 }
803
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl<'a> AsRef<OsStr> for Components<'a> {
806     fn as_ref(&self) -> &OsStr {
807         self.as_path().as_os_str()
808     }
809 }
810
811 impl<'a> Iter<'a> {
812     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
813     #[stable(feature = "rust1", since = "1.0.0")]
814     pub fn as_path(&self) -> &'a Path {
815         self.inner.as_path()
816     }
817 }
818
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a> AsRef<Path> for Iter<'a> {
821     fn as_ref(&self) -> &Path {
822         self.as_path()
823     }
824 }
825
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<'a> AsRef<OsStr> for Iter<'a> {
828     fn as_ref(&self) -> &OsStr {
829         self.as_path().as_os_str()
830     }
831 }
832
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a> Iterator for Iter<'a> {
835     type Item = &'a OsStr;
836
837     fn next(&mut self) -> Option<&'a OsStr> {
838         self.inner.next().map(Component::as_os_str)
839     }
840 }
841
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<'a> DoubleEndedIterator for Iter<'a> {
844     fn next_back(&mut self) -> Option<&'a OsStr> {
845         self.inner.next_back().map(Component::as_os_str)
846     }
847 }
848
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a> Iterator for Components<'a> {
851     type Item = Component<'a>;
852
853     fn next(&mut self) -> Option<Component<'a>> {
854         while !self.finished() {
855             match self.front {
856                 State::Prefix if self.prefix_len() > 0 => {
857                     self.front = State::StartDir;
858                     debug_assert!(self.prefix_len() <= self.path.len());
859                     let raw = &self.path[..self.prefix_len()];
860                     self.path = &self.path[self.prefix_len()..];
861                     return Some(Component::Prefix(PrefixComponent {
862                         raw: unsafe { u8_slice_as_os_str(raw) },
863                         parsed: self.prefix.unwrap(),
864                     }));
865                 }
866                 State::Prefix => {
867                     self.front = State::StartDir;
868                 }
869                 State::StartDir => {
870                     self.front = State::Body;
871                     if self.has_physical_root {
872                         debug_assert!(!self.path.is_empty());
873                         self.path = &self.path[1..];
874                         return Some(Component::RootDir);
875                     } else if let Some(p) = self.prefix {
876                         if p.has_implicit_root() && !p.is_verbatim() {
877                             return Some(Component::RootDir);
878                         }
879                     } else if self.include_cur_dir() {
880                         debug_assert!(!self.path.is_empty());
881                         self.path = &self.path[1..];
882                         return Some(Component::CurDir);
883                     }
884                 }
885                 State::Body if !self.path.is_empty() => {
886                     let (size, comp) = self.parse_next_component();
887                     self.path = &self.path[size..];
888                     if comp.is_some() {
889                         return comp;
890                     }
891                 }
892                 State::Body => {
893                     self.front = State::Done;
894                 }
895                 State::Done => unreachable!(),
896             }
897         }
898         None
899     }
900 }
901
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a> DoubleEndedIterator for Components<'a> {
904     fn next_back(&mut self) -> Option<Component<'a>> {
905         while !self.finished() {
906             match self.back {
907                 State::Body if self.path.len() > self.len_before_body() => {
908                     let (size, comp) = self.parse_next_component_back();
909                     self.path = &self.path[..self.path.len() - size];
910                     if comp.is_some() {
911                         return comp;
912                     }
913                 }
914                 State::Body => {
915                     self.back = State::StartDir;
916                 }
917                 State::StartDir => {
918                     self.back = State::Prefix;
919                     if self.has_physical_root {
920                         self.path = &self.path[..self.path.len() - 1];
921                         return Some(Component::RootDir);
922                     } else if let Some(p) = self.prefix {
923                         if p.has_implicit_root() && !p.is_verbatim() {
924                             return Some(Component::RootDir);
925                         }
926                     } else if self.include_cur_dir() {
927                         self.path = &self.path[..self.path.len() - 1];
928                         return Some(Component::CurDir);
929                     }
930                 }
931                 State::Prefix if self.prefix_len() > 0 => {
932                     self.back = State::Done;
933                     return Some(Component::Prefix(PrefixComponent {
934                         raw: unsafe { u8_slice_as_os_str(self.path) },
935                         parsed: self.prefix.unwrap(),
936                     }));
937                 }
938                 State::Prefix => {
939                     self.back = State::Done;
940                     return None;
941                 }
942                 State::Done => unreachable!(),
943             }
944         }
945         None
946     }
947 }
948
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a> cmp::PartialEq for Components<'a> {
951     fn eq(&self, other: &Components<'a>) -> bool {
952         Iterator::eq(self.clone(), other.clone())
953     }
954 }
955
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a> cmp::Eq for Components<'a> {}
958
959 #[stable(feature = "rust1", since = "1.0.0")]
960 impl<'a> cmp::PartialOrd for Components<'a> {
961     fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
962         Iterator::partial_cmp(self.clone(), other.clone())
963     }
964 }
965
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<'a> cmp::Ord for Components<'a> {
968     fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
969         Iterator::cmp(self.clone(), other.clone())
970     }
971 }
972
973 ////////////////////////////////////////////////////////////////////////////////
974 // Basic types and traits
975 ////////////////////////////////////////////////////////////////////////////////
976
977 /// An owned, mutable path (akin to `String`).
978 ///
979 /// This type provides methods like `push` and `set_extension` that mutate the
980 /// path in place. It also implements `Deref` to `Path`, meaning that all
981 /// methods on `Path` slices are available on `PathBuf` values as well.
982 ///
983 /// More details about the overall approach can be found in
984 /// the module documentation.
985 ///
986 /// # Examples
987 ///
988 /// ```
989 /// use std::path::PathBuf;
990 ///
991 /// let mut path = PathBuf::from("c:\\");
992 /// path.push("windows");
993 /// path.push("system32");
994 /// path.set_extension("dll");
995 /// ```
996 #[derive(Clone)]
997 #[stable(feature = "rust1", since = "1.0.0")]
998 pub struct PathBuf {
999     inner: OsString,
1000 }
1001
1002 impl PathBuf {
1003     fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1004         unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1005     }
1006
1007     /// Allocates an empty `PathBuf`.
1008     #[stable(feature = "rust1", since = "1.0.0")]
1009     pub fn new() -> PathBuf {
1010         PathBuf { inner: OsString::new() }
1011     }
1012
1013     /// Coerces to a `Path` slice.
1014     #[stable(feature = "rust1", since = "1.0.0")]
1015     pub fn as_path(&self) -> &Path {
1016         self
1017     }
1018
1019     /// Extends `self` with `path`.
1020     ///
1021     /// If `path` is absolute, it replaces the current path.
1022     ///
1023     /// On Windows:
1024     ///
1025     /// * if `path` has a root but no prefix (e.g. `\windows`), it
1026     ///   replaces everything except for the prefix (if any) of `self`.
1027     /// * if `path` has a prefix but no root, it replaces `self`.
1028     ///
1029     /// # Examples
1030     ///
1031     /// ```
1032     /// use std::path::PathBuf;
1033     ///
1034     /// let mut path = PathBuf::new();
1035     /// path.push("/tmp");
1036     /// path.push("file.bk");
1037     /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1038     ///
1039     /// // Pushing an absolute path replaces the current path
1040     /// path.push("/etc/passwd");
1041     /// assert_eq!(path, PathBuf::from("/etc/passwd"));
1042     /// ```
1043     #[stable(feature = "rust1", since = "1.0.0")]
1044     pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1045         self._push(path.as_ref())
1046     }
1047
1048     #[allow(deprecated)]
1049     fn _push(&mut self, path: &Path) {
1050         // in general, a separator is needed if the rightmost byte is not a separator
1051         let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1052
1053         // in the special case of `C:` on Windows, do *not* add a separator
1054         {
1055             let comps = self.components();
1056             if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1057                comps.prefix.unwrap().is_drive() {
1058                 need_sep = false
1059             }
1060         }
1061
1062         // absolute `path` replaces `self`
1063         if path.is_absolute() || path.prefix().is_some() {
1064             self.as_mut_vec().truncate(0);
1065
1066         // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1067         } else if path.has_root() {
1068             let prefix_len = self.components().prefix_remaining();
1069             self.as_mut_vec().truncate(prefix_len);
1070
1071         // `path` is a pure relative path
1072         } else if need_sep {
1073             self.inner.push(MAIN_SEP_STR);
1074         }
1075
1076         self.inner.push(path);
1077     }
1078
1079     /// Truncate `self` to `self.parent()`.
1080     ///
1081     /// Returns false and does nothing if `self.file_name()` is `None`.
1082     /// Otherwise, returns `true`.
1083     #[stable(feature = "rust1", since = "1.0.0")]
1084     pub fn pop(&mut self) -> bool {
1085         match self.parent().map(|p| p.as_u8_slice().len()) {
1086             Some(len) => {
1087                 self.as_mut_vec().truncate(len);
1088                 true
1089             }
1090             None => false,
1091         }
1092     }
1093
1094     /// Updates `self.file_name()` to `file_name`.
1095     ///
1096     /// If `self.file_name()` was `None`, this is equivalent to pushing
1097     /// `file_name`.
1098     ///
1099     /// # Examples
1100     ///
1101     /// ```
1102     /// use std::path::PathBuf;
1103     ///
1104     /// let mut buf = PathBuf::from("/");
1105     /// assert!(buf.file_name() == None);
1106     /// buf.set_file_name("bar");
1107     /// assert!(buf == PathBuf::from("/bar"));
1108     /// assert!(buf.file_name().is_some());
1109     /// buf.set_file_name("baz.txt");
1110     /// assert!(buf == PathBuf::from("/baz.txt"));
1111     /// ```
1112     #[stable(feature = "rust1", since = "1.0.0")]
1113     pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1114         self._set_file_name(file_name.as_ref())
1115     }
1116
1117     fn _set_file_name(&mut self, file_name: &OsStr) {
1118         if self.file_name().is_some() {
1119             let popped = self.pop();
1120             debug_assert!(popped);
1121         }
1122         self.push(file_name);
1123     }
1124
1125     /// Updates `self.extension()` to `extension`.
1126     ///
1127     /// If `self.file_name()` is `None`, does nothing and returns `false`.
1128     ///
1129     /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
1130     /// is added; otherwise it is replaced.
1131     #[stable(feature = "rust1", since = "1.0.0")]
1132     pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1133         self._set_extension(extension.as_ref())
1134     }
1135
1136     fn _set_extension(&mut self, extension: &OsStr) -> bool {
1137         if self.file_name().is_none() {
1138             return false;
1139         }
1140
1141         let mut stem = match self.file_stem() {
1142             Some(stem) => stem.to_os_string(),
1143             None => OsString::new(),
1144         };
1145
1146         if !os_str_as_u8_slice(extension).is_empty() {
1147             stem.push(".");
1148             stem.push(extension);
1149         }
1150         self.set_file_name(&stem);
1151
1152         true
1153     }
1154
1155     /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
1156     #[stable(feature = "rust1", since = "1.0.0")]
1157     pub fn into_os_string(self) -> OsString {
1158         self.inner
1159     }
1160 }
1161
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1164     fn from(s: &'a T) -> PathBuf {
1165         PathBuf::from(s.as_ref().to_os_string())
1166     }
1167 }
1168
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl From<OsString> for PathBuf {
1171     fn from(s: OsString) -> PathBuf {
1172         PathBuf { inner: s }
1173     }
1174 }
1175
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl From<String> for PathBuf {
1178     fn from(s: String) -> PathBuf {
1179         PathBuf::from(OsString::from(s))
1180     }
1181 }
1182
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1185     fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1186         let mut buf = PathBuf::new();
1187         buf.extend(iter);
1188         buf
1189     }
1190 }
1191
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1194     fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1195         for p in iter {
1196             self.push(p.as_ref())
1197         }
1198     }
1199 }
1200
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl fmt::Debug for PathBuf {
1203     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1204         fmt::Debug::fmt(&**self, formatter)
1205     }
1206 }
1207
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 impl ops::Deref for PathBuf {
1210     type Target = Path;
1211
1212     fn deref(&self) -> &Path {
1213         Path::new(&self.inner)
1214     }
1215 }
1216
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl Borrow<Path> for PathBuf {
1219     fn borrow(&self) -> &Path {
1220         self.deref()
1221     }
1222 }
1223
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 #[allow(deprecated)]
1226 impl IntoCow<'static, Path> for PathBuf {
1227     fn into_cow(self) -> Cow<'static, Path> {
1228         Cow::Owned(self)
1229     }
1230 }
1231
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 #[allow(deprecated)]
1234 impl<'a> IntoCow<'a, Path> for &'a Path {
1235     fn into_cow(self) -> Cow<'a, Path> {
1236         Cow::Borrowed(self)
1237     }
1238 }
1239
1240 #[stable(feature = "cow_from_path", since = "1.6.0")]
1241 impl<'a> From<&'a Path> for Cow<'a, Path> {
1242     #[inline]
1243     fn from(s: &'a Path) -> Cow<'a, Path> {
1244         Cow::Borrowed(s)
1245     }
1246 }
1247
1248 #[stable(feature = "cow_from_path", since = "1.6.0")]
1249 impl<'a> From<PathBuf> for Cow<'a, Path> {
1250     #[inline]
1251     fn from(s: PathBuf) -> Cow<'a, Path> {
1252         Cow::Owned(s)
1253     }
1254 }
1255
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 impl ToOwned for Path {
1258     type Owned = PathBuf;
1259     fn to_owned(&self) -> PathBuf {
1260         self.to_path_buf()
1261     }
1262 }
1263
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl cmp::PartialEq for PathBuf {
1266     fn eq(&self, other: &PathBuf) -> bool {
1267         self.components() == other.components()
1268     }
1269 }
1270
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl Hash for PathBuf {
1273     fn hash<H: Hasher>(&self, h: &mut H) {
1274         self.as_path().hash(h)
1275     }
1276 }
1277
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl cmp::Eq for PathBuf {}
1280
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl cmp::PartialOrd for PathBuf {
1283     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1284         self.components().partial_cmp(other.components())
1285     }
1286 }
1287
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl cmp::Ord for PathBuf {
1290     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1291         self.components().cmp(other.components())
1292     }
1293 }
1294
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 impl AsRef<OsStr> for PathBuf {
1297     fn as_ref(&self) -> &OsStr {
1298         &self.inner[..]
1299     }
1300 }
1301
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl Into<OsString> for PathBuf {
1304     fn into(self) -> OsString {
1305         self.inner
1306     }
1307 }
1308
1309 /// A slice of a path (akin to `str`).
1310 ///
1311 /// This type supports a number of operations for inspecting a path, including
1312 /// breaking the path into its components (separated by `/` or `\`, depending on
1313 /// the platform), extracting the file name, determining whether the path is
1314 /// absolute, and so on. More details about the overall approach can be found in
1315 /// the module documentation.
1316 ///
1317 /// This is an *unsized* type, meaning that it must always be used behind a
1318 /// pointer like `&` or `Box`.
1319 ///
1320 /// # Examples
1321 ///
1322 /// ```
1323 /// use std::path::Path;
1324 ///
1325 /// let path = Path::new("/tmp/foo/bar.txt");
1326 /// let file = path.file_name();
1327 /// let extension = path.extension();
1328 /// let parent_dir = path.parent();
1329 /// ```
1330 ///
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 pub struct Path {
1333     inner: OsStr,
1334 }
1335
1336 /// An error returned from the `Path::strip_prefix` method indicating that the
1337 /// prefix was not found in `self`.
1338 #[derive(Debug, Clone, PartialEq, Eq)]
1339 #[stable(since = "1.7.0", feature = "strip_prefix")]
1340 pub struct StripPrefixError(());
1341
1342 impl Path {
1343     // The following (private!) function allows construction of a path from a u8
1344     // slice, which is only safe when it is known to follow the OsStr encoding.
1345     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1346         Path::new(u8_slice_as_os_str(s))
1347     }
1348     // The following (private!) function reveals the byte encoding used for OsStr.
1349     fn as_u8_slice(&self) -> &[u8] {
1350         os_str_as_u8_slice(&self.inner)
1351     }
1352
1353     /// Directly wrap a string slice as a `Path` slice.
1354     ///
1355     /// This is a cost-free conversion.
1356     ///
1357     /// # Examples
1358     ///
1359     /// ```
1360     /// use std::path::Path;
1361     ///
1362     /// Path::new("foo.txt");
1363     /// ```
1364     ///
1365     /// You can create `Path`s from `String`s, or even other `Path`s:
1366     ///
1367     /// ```
1368     /// use std::path::Path;
1369     ///
1370     /// let string = String::from("foo.txt");
1371     /// let from_string = Path::new(&string);
1372     /// let from_path = Path::new(&from_string);
1373     /// assert_eq!(from_string, from_path);
1374     /// ```
1375     #[stable(feature = "rust1", since = "1.0.0")]
1376     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1377         unsafe { mem::transmute(s.as_ref()) }
1378     }
1379
1380     /// Yields the underlying `OsStr` slice.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// use std::path::Path;
1386     ///
1387     /// let os_str = Path::new("foo.txt").as_os_str();
1388     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1389     /// ```
1390     #[stable(feature = "rust1", since = "1.0.0")]
1391     pub fn as_os_str(&self) -> &OsStr {
1392         &self.inner
1393     }
1394
1395     /// Yields a `&str` slice if the `Path` is valid unicode.
1396     ///
1397     /// This conversion may entail doing a check for UTF-8 validity.
1398     ///
1399     /// # Examples
1400     ///
1401     /// ```
1402     /// use std::path::Path;
1403     ///
1404     /// let path_str = Path::new("foo.txt").to_str();
1405     /// assert_eq!(path_str, Some("foo.txt"));
1406     /// ```
1407     #[stable(feature = "rust1", since = "1.0.0")]
1408     pub fn to_str(&self) -> Option<&str> {
1409         self.inner.to_str()
1410     }
1411
1412     /// Converts a `Path` to a `Cow<str>`.
1413     ///
1414     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1415     ///
1416     /// # Examples
1417     ///
1418     /// ```
1419     /// use std::path::Path;
1420     ///
1421     /// let path_str = Path::new("foo.txt").to_string_lossy();
1422     /// assert_eq!(path_str, "foo.txt");
1423     /// ```
1424     #[stable(feature = "rust1", since = "1.0.0")]
1425     pub fn to_string_lossy(&self) -> Cow<str> {
1426         self.inner.to_string_lossy()
1427     }
1428
1429     /// Converts a `Path` to an owned `PathBuf`.
1430     ///
1431     /// # Examples
1432     ///
1433     /// ```
1434     /// use std::path::Path;
1435     ///
1436     /// let path_buf = Path::new("foo.txt").to_path_buf();
1437     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1438     /// ```
1439     #[stable(feature = "rust1", since = "1.0.0")]
1440     pub fn to_path_buf(&self) -> PathBuf {
1441         PathBuf::from(self.inner.to_os_string())
1442     }
1443
1444     /// A path is *absolute* if it is independent of the current directory.
1445     ///
1446     /// * On Unix, a path is absolute if it starts with the root, so
1447     /// `is_absolute` and `has_root` are equivalent.
1448     ///
1449     /// * On Windows, a path is absolute if it has a prefix and starts with the
1450     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1451     /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1452     ///
1453     /// # Examples
1454     ///
1455     /// ```
1456     /// use std::path::Path;
1457     ///
1458     /// assert!(!Path::new("foo.txt").is_absolute());
1459     /// ```
1460     #[stable(feature = "rust1", since = "1.0.0")]
1461     #[allow(deprecated)]
1462     pub fn is_absolute(&self) -> bool {
1463         self.has_root() && (cfg!(unix) || self.prefix().is_some())
1464     }
1465
1466     /// A path is *relative* if it is not absolute.
1467     ///
1468     /// # Examples
1469     ///
1470     /// ```
1471     /// use std::path::Path;
1472     ///
1473     /// assert!(Path::new("foo.txt").is_relative());
1474     /// ```
1475     #[stable(feature = "rust1", since = "1.0.0")]
1476     pub fn is_relative(&self) -> bool {
1477         !self.is_absolute()
1478     }
1479
1480     /// Returns the *prefix* of a path, if any.
1481     ///
1482     /// Prefixes are relevant only for Windows paths, and consist of volumes
1483     /// like `C:`, UNC prefixes like `\\server`, and others described in more
1484     /// detail in `std::os::windows::PathExt`.
1485     #[unstable(feature = "path_prefix",
1486                reason = "uncertain whether to expose this convenience",
1487                issue = "27722")]
1488     #[rustc_deprecated(since = "1.7.0",
1489                        reason = "inspect components().next() instead")]
1490     pub fn prefix(&self) -> Option<Prefix> {
1491         self.components().prefix
1492     }
1493
1494     /// A path has a root if the body of the path begins with the directory separator.
1495     ///
1496     /// * On Unix, a path has a root if it begins with `/`.
1497     ///
1498     /// * On Windows, a path has a root if it:
1499     ///     * has no prefix and begins with a separator, e.g. `\\windows`
1500     ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1501     ///     * has any non-disk prefix, e.g. `\\server\share`
1502     ///
1503     /// # Examples
1504     ///
1505     /// ```
1506     /// use std::path::Path;
1507     ///
1508     /// assert!(Path::new("/etc/passwd").has_root());
1509     /// ```
1510     #[stable(feature = "rust1", since = "1.0.0")]
1511     pub fn has_root(&self) -> bool {
1512         self.components().has_root()
1513     }
1514
1515     /// The path without its final component, if any.
1516     ///
1517     /// Returns `None` if the path terminates in a root or prefix.
1518     ///
1519     /// # Examples
1520     ///
1521     /// ```
1522     /// use std::path::Path;
1523     ///
1524     /// let path = Path::new("/foo/bar");
1525     /// let parent = path.parent().unwrap();
1526     /// assert_eq!(parent, Path::new("/foo"));
1527     ///
1528     /// let grand_parent = parent.parent().unwrap();
1529     /// assert_eq!(grand_parent, Path::new("/"));
1530     /// assert_eq!(grand_parent.parent(), None);
1531     /// ```
1532     #[stable(feature = "rust1", since = "1.0.0")]
1533     pub fn parent(&self) -> Option<&Path> {
1534         let mut comps = self.components();
1535         let comp = comps.next_back();
1536         comp.and_then(|p| {
1537             match p {
1538                 Component::Normal(_) |
1539                 Component::CurDir |
1540                 Component::ParentDir => Some(comps.as_path()),
1541                 _ => None,
1542             }
1543         })
1544     }
1545
1546     /// The final component of the path, if it is a normal file.
1547     ///
1548     /// If the path terminates in `.`, `..`, or consists solely of a root of
1549     /// prefix, `file_name` will return `None`.
1550     ///
1551     /// # Examples
1552     ///
1553     /// ```
1554     /// use std::path::Path;
1555     /// use std::ffi::OsStr;
1556     ///
1557     /// let path = Path::new("foo.txt");
1558     /// let os_str = OsStr::new("foo.txt");
1559     ///
1560     /// assert_eq!(Some(os_str), path.file_name());
1561     /// ```
1562     #[stable(feature = "rust1", since = "1.0.0")]
1563     pub fn file_name(&self) -> Option<&OsStr> {
1564         self.components().next_back().and_then(|p| {
1565             match p {
1566                 Component::Normal(p) => Some(p.as_ref()),
1567                 _ => None,
1568             }
1569         })
1570     }
1571
1572     /// Returns a path that, when joined onto `base`, yields `self`.
1573     ///
1574     /// If `base` is not a prefix of `self` (i.e. `starts_with`
1575     /// returns false), then `relative_from` returns `None`.
1576     #[unstable(feature = "path_relative_from", reason = "see #23284",
1577                issue = "23284")]
1578     #[rustc_deprecated(since = "1.7.0", reason = "renamed to strip_prefix")]
1579     pub fn relative_from<'a, P: ?Sized + AsRef<Path>>(&'a self, base: &'a P) -> Option<&Path> {
1580         self._strip_prefix(base.as_ref()).ok()
1581     }
1582
1583     /// Returns a path that, when joined onto `base`, yields `self`.
1584     ///
1585     /// If `base` is not a prefix of `self` (i.e. `starts_with`
1586     /// returns false), then `relative_from` returns `None`.
1587     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1588     pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1589                                        -> Result<&'a Path, StripPrefixError>
1590         where P: AsRef<Path>
1591     {
1592         self._strip_prefix(base.as_ref())
1593     }
1594
1595     fn _strip_prefix<'a>(&'a self, base: &'a Path)
1596                          -> Result<&'a Path, StripPrefixError> {
1597         iter_after(self.components(), base.components())
1598             .map(|c| c.as_path())
1599             .ok_or(StripPrefixError(()))
1600     }
1601
1602     /// Determines whether `base` is a prefix of `self`.
1603     ///
1604     /// Only considers whole path components to match.
1605     ///
1606     /// # Examples
1607     ///
1608     /// ```
1609     /// use std::path::Path;
1610     ///
1611     /// let path = Path::new("/etc/passwd");
1612     ///
1613     /// assert!(path.starts_with("/etc"));
1614     ///
1615     /// assert!(!path.starts_with("/e"));
1616     /// ```
1617     #[stable(feature = "rust1", since = "1.0.0")]
1618     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1619         self._starts_with(base.as_ref())
1620     }
1621
1622     fn _starts_with(&self, base: &Path) -> bool {
1623         iter_after(self.components(), base.components()).is_some()
1624     }
1625
1626     /// Determines whether `child` is a suffix of `self`.
1627     ///
1628     /// Only considers whole path components to match.
1629     ///
1630     /// # Examples
1631     ///
1632     /// ```
1633     /// use std::path::Path;
1634     ///
1635     /// let path = Path::new("/etc/passwd");
1636     ///
1637     /// assert!(path.ends_with("passwd"));
1638     /// ```
1639     #[stable(feature = "rust1", since = "1.0.0")]
1640     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1641         self._ends_with(child.as_ref())
1642     }
1643
1644     fn _ends_with(&self, child: &Path) -> bool {
1645         iter_after(self.components().rev(), child.components().rev()).is_some()
1646     }
1647
1648     /// Extracts the stem (non-extension) portion of `self.file_name()`.
1649     ///
1650     /// The stem is:
1651     ///
1652     /// * None, if there is no file name;
1653     /// * The entire file name if there is no embedded `.`;
1654     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1655     /// * Otherwise, the portion of the file name before the final `.`
1656     ///
1657     /// # Examples
1658     ///
1659     /// ```
1660     /// use std::path::Path;
1661     ///
1662     /// let path = Path::new("foo.rs");
1663     ///
1664     /// assert_eq!("foo", path.file_stem().unwrap());
1665     /// ```
1666     #[stable(feature = "rust1", since = "1.0.0")]
1667     pub fn file_stem(&self) -> Option<&OsStr> {
1668         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1669     }
1670
1671     /// Extracts the extension of `self.file_name()`, if possible.
1672     ///
1673     /// The extension is:
1674     ///
1675     /// * None, if there is no file name;
1676     /// * None, if there is no embedded `.`;
1677     /// * None, if the file name begins with `.` and has no other `.`s within;
1678     /// * Otherwise, the portion of the file name after the final `.`
1679     ///
1680     /// # Examples
1681     ///
1682     /// ```
1683     /// use std::path::Path;
1684     ///
1685     /// let path = Path::new("foo.rs");
1686     ///
1687     /// assert_eq!("rs", path.extension().unwrap());
1688     /// ```
1689     #[stable(feature = "rust1", since = "1.0.0")]
1690     pub fn extension(&self) -> Option<&OsStr> {
1691         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1692     }
1693
1694     /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1695     ///
1696     /// See `PathBuf::push` for more details on what it means to adjoin a path.
1697     ///
1698     /// # Examples
1699     ///
1700     /// ```
1701     /// use std::path::{Path, PathBuf};
1702     ///
1703     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1704     /// ```
1705     #[stable(feature = "rust1", since = "1.0.0")]
1706     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1707         self._join(path.as_ref())
1708     }
1709
1710     fn _join(&self, path: &Path) -> PathBuf {
1711         let mut buf = self.to_path_buf();
1712         buf.push(path);
1713         buf
1714     }
1715
1716     /// Creates an owned `PathBuf` like `self` but with the given file name.
1717     ///
1718     /// See `PathBuf::set_file_name` for more details.
1719     ///
1720     /// # Examples
1721     ///
1722     /// ```
1723     /// use std::path::{Path, PathBuf};
1724     ///
1725     /// let path = Path::new("/tmp/foo.txt");
1726     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1727     /// ```
1728     #[stable(feature = "rust1", since = "1.0.0")]
1729     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1730         self._with_file_name(file_name.as_ref())
1731     }
1732
1733     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1734         let mut buf = self.to_path_buf();
1735         buf.set_file_name(file_name);
1736         buf
1737     }
1738
1739     /// Creates an owned `PathBuf` like `self` but with the given extension.
1740     ///
1741     /// See `PathBuf::set_extension` for more details.
1742     ///
1743     /// # Examples
1744     ///
1745     /// ```
1746     /// use std::path::{Path, PathBuf};
1747     ///
1748     /// let path = Path::new("foo.rs");
1749     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1750     /// ```
1751     #[stable(feature = "rust1", since = "1.0.0")]
1752     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1753         self._with_extension(extension.as_ref())
1754     }
1755
1756     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1757         let mut buf = self.to_path_buf();
1758         buf.set_extension(extension);
1759         buf
1760     }
1761
1762     /// Produce an iterator over the components of the path.
1763     ///
1764     /// # Examples
1765     ///
1766     /// ```
1767     /// use std::path::{Path, Component};
1768     /// use std::ffi::OsStr;
1769     ///
1770     /// let mut components = Path::new("/tmp/foo.txt").components();
1771     ///
1772     /// assert_eq!(components.next(), Some(Component::RootDir));
1773     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1774     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1775     /// assert_eq!(components.next(), None)
1776     /// ```
1777     #[stable(feature = "rust1", since = "1.0.0")]
1778     pub fn components(&self) -> Components {
1779         let prefix = parse_prefix(self.as_os_str());
1780         Components {
1781             path: self.as_u8_slice(),
1782             prefix: prefix,
1783             has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1784             front: State::Prefix,
1785             back: State::Body,
1786         }
1787     }
1788
1789     /// Produce an iterator over the path's components viewed as `OsStr` slices.
1790     ///
1791     /// # Examples
1792     ///
1793     /// ```
1794     /// use std::path::{self, Path};
1795     /// use std::ffi::OsStr;
1796     ///
1797     /// let mut it = Path::new("/tmp/foo.txt").iter();
1798     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1799     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1800     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1801     /// assert_eq!(it.next(), None)
1802     /// ```
1803     #[stable(feature = "rust1", since = "1.0.0")]
1804     pub fn iter(&self) -> Iter {
1805         Iter { inner: self.components() }
1806     }
1807
1808     /// Returns an object that implements `Display` for safely printing paths
1809     /// that may contain non-Unicode data.
1810     ///
1811     /// # Examples
1812     ///
1813     /// ```
1814     /// use std::path::Path;
1815     ///
1816     /// let path = Path::new("/tmp/foo.rs");
1817     ///
1818     /// println!("{}", path.display());
1819     /// ```
1820     #[stable(feature = "rust1", since = "1.0.0")]
1821     pub fn display(&self) -> Display {
1822         Display { path: self }
1823     }
1824
1825
1826     /// Query the file system to get information about a file, directory, etc.
1827     ///
1828     /// This function will traverse symbolic links to query information about the
1829     /// destination file.
1830     ///
1831     /// This is an alias to `fs::metadata`.
1832     #[stable(feature = "path_ext", since = "1.5.0")]
1833     pub fn metadata(&self) -> io::Result<fs::Metadata> {
1834         fs::metadata(self)
1835     }
1836
1837     /// Query the metadata about a file without following symlinks.
1838     ///
1839     /// This is an alias to `fs::symlink_metadata`.
1840     #[stable(feature = "path_ext", since = "1.5.0")]
1841     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1842         fs::symlink_metadata(self)
1843     }
1844
1845     /// Returns the canonical form of the path with all intermediate components
1846     /// normalized and symbolic links resolved.
1847     ///
1848     /// This is an alias to `fs::canonicalize`.
1849     #[stable(feature = "path_ext", since = "1.5.0")]
1850     pub fn canonicalize(&self) -> io::Result<PathBuf> {
1851         fs::canonicalize(self)
1852     }
1853
1854     /// Reads a symbolic link, returning the file that the link points to.
1855     ///
1856     /// This is an alias to `fs::read_link`.
1857     #[stable(feature = "path_ext", since = "1.5.0")]
1858     pub fn read_link(&self) -> io::Result<PathBuf> {
1859         fs::read_link(self)
1860     }
1861
1862     /// Returns an iterator over the entries within a directory.
1863     ///
1864     /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1865     /// be encountered after an iterator is initially constructed.
1866     ///
1867     /// This is an alias to `fs::read_dir`.
1868     #[stable(feature = "path_ext", since = "1.5.0")]
1869     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1870         fs::read_dir(self)
1871     }
1872
1873     /// Returns whether the path points at an existing entity.
1874     ///
1875     /// This function will traverse symbolic links to query information about the
1876     /// destination file. In case of broken symbolic links this will return `false`.
1877     ///
1878     /// # Examples
1879     ///
1880     /// ```no_run
1881     /// use std::path::Path;
1882     /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
1883     /// ```
1884     #[stable(feature = "path_ext", since = "1.5.0")]
1885     pub fn exists(&self) -> bool {
1886         fs::metadata(self).is_ok()
1887     }
1888
1889     /// Returns whether the path is pointing at a regular file.
1890     ///
1891     /// This function will traverse symbolic links to query information about the
1892     /// destination file. In case of broken symbolic links this will return `false`.
1893     ///
1894     /// # Examples
1895     ///
1896     /// ```no_run
1897     /// use std::path::Path;
1898     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
1899     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
1900     /// ```
1901     #[stable(feature = "path_ext", since = "1.5.0")]
1902     pub fn is_file(&self) -> bool {
1903         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
1904     }
1905
1906     /// Returns whether the path is pointing at a directory.
1907     ///
1908     /// This function will traverse symbolic links to query information about the
1909     /// destination file. In case of broken symbolic links this will return `false`.
1910     ///
1911     /// # Examples
1912     ///
1913     /// ```no_run
1914     /// use std::path::Path;
1915     /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
1916     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
1917     /// ```
1918     #[stable(feature = "path_ext", since = "1.5.0")]
1919     pub fn is_dir(&self) -> bool {
1920         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
1921     }
1922 }
1923
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 impl AsRef<OsStr> for Path {
1926     fn as_ref(&self) -> &OsStr {
1927         &self.inner
1928     }
1929 }
1930
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl fmt::Debug for Path {
1933     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1934         self.inner.fmt(formatter)
1935     }
1936 }
1937
1938 /// Helper struct for safely printing paths with `format!()` and `{}`
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 pub struct Display<'a> {
1941     path: &'a Path,
1942 }
1943
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<'a> fmt::Debug for Display<'a> {
1946     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1947         fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1948     }
1949 }
1950
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl<'a> fmt::Display for Display<'a> {
1953     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1954         fmt::Display::fmt(&self.path.to_string_lossy(), f)
1955     }
1956 }
1957
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl cmp::PartialEq for Path {
1960     fn eq(&self, other: &Path) -> bool {
1961         self.components().eq(other.components())
1962     }
1963 }
1964
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl Hash for Path {
1967     fn hash<H: Hasher>(&self, h: &mut H) {
1968         for component in self.components() {
1969             component.hash(h);
1970         }
1971     }
1972 }
1973
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl cmp::Eq for Path {}
1976
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl cmp::PartialOrd for Path {
1979     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1980         self.components().partial_cmp(other.components())
1981     }
1982 }
1983
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl cmp::Ord for Path {
1986     fn cmp(&self, other: &Path) -> cmp::Ordering {
1987         self.components().cmp(other.components())
1988     }
1989 }
1990
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl AsRef<Path> for Path {
1993     fn as_ref(&self) -> &Path {
1994         self
1995     }
1996 }
1997
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl AsRef<Path> for OsStr {
2000     fn as_ref(&self) -> &Path {
2001         Path::new(self)
2002     }
2003 }
2004
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl AsRef<Path> for OsString {
2007     fn as_ref(&self) -> &Path {
2008         Path::new(self)
2009     }
2010 }
2011
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl AsRef<Path> for str {
2014     fn as_ref(&self) -> &Path {
2015         Path::new(self)
2016     }
2017 }
2018
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 impl AsRef<Path> for String {
2021     fn as_ref(&self) -> &Path {
2022         Path::new(self)
2023     }
2024 }
2025
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl AsRef<Path> for PathBuf {
2028     fn as_ref(&self) -> &Path {
2029         self
2030     }
2031 }
2032
2033 #[stable(feature = "path_into_iter", since = "1.6.0")]
2034 impl<'a> IntoIterator for &'a PathBuf {
2035     type Item = &'a OsStr;
2036     type IntoIter = Iter<'a>;
2037     fn into_iter(self) -> Iter<'a> { self.iter() }
2038 }
2039
2040 #[stable(feature = "path_into_iter", since = "1.6.0")]
2041 impl<'a> IntoIterator for &'a Path {
2042     type Item = &'a OsStr;
2043     type IntoIter = Iter<'a>;
2044     fn into_iter(self) -> Iter<'a> { self.iter() }
2045 }
2046
2047 macro_rules! impl_eq {
2048     ($lhs:ty, $rhs: ty) => {
2049         #[stable(feature = "partialeq_path", since = "1.6.0")]
2050         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2051             #[inline]
2052             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2053         }
2054
2055         #[stable(feature = "partialeq_path", since = "1.6.0")]
2056         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2057             #[inline]
2058             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2059         }
2060
2061     }
2062 }
2063
2064 impl_eq!(PathBuf, Path);
2065 impl_eq!(PathBuf, &'a Path);
2066 impl_eq!(Cow<'a, Path>, Path);
2067 impl_eq!(Cow<'a, Path>, &'b Path);
2068 impl_eq!(Cow<'a, Path>, PathBuf);
2069
2070 #[stable(since = "1.7.0", feature = "strip_prefix")]
2071 impl fmt::Display for StripPrefixError {
2072     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2073         self.description().fmt(f)
2074     }
2075 }
2076
2077 #[stable(since = "1.7.0", feature = "strip_prefix")]
2078 impl Error for StripPrefixError {
2079     fn description(&self) -> &str { "prefix not found" }
2080 }
2081
2082 #[cfg(test)]
2083 mod tests {
2084     use super::*;
2085     use string::{ToString, String};
2086     use vec::Vec;
2087
2088     macro_rules! t(
2089         ($path:expr, iter: $iter:expr) => (
2090             {
2091                 let path = Path::new($path);
2092
2093                 // Forward iteration
2094                 let comps = path.iter()
2095                     .map(|p| p.to_string_lossy().into_owned())
2096                     .collect::<Vec<String>>();
2097                 let exp: &[&str] = &$iter;
2098                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2099                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2100                         exps, comps);
2101
2102                 // Reverse iteration
2103                 let comps = Path::new($path).iter().rev()
2104                     .map(|p| p.to_string_lossy().into_owned())
2105                     .collect::<Vec<String>>();
2106                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2107                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2108                         exps, comps);
2109             }
2110         );
2111
2112         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2113             {
2114                 let path = Path::new($path);
2115
2116                 let act_root = path.has_root();
2117                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2118                         $has_root, act_root);
2119
2120                 let act_abs = path.is_absolute();
2121                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2122                         $is_absolute, act_abs);
2123             }
2124         );
2125
2126         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2127             {
2128                 let path = Path::new($path);
2129
2130                 let parent = path.parent().map(|p| p.to_str().unwrap());
2131                 let exp_parent: Option<&str> = $parent;
2132                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2133                         exp_parent, parent);
2134
2135                 let file = path.file_name().map(|p| p.to_str().unwrap());
2136                 let exp_file: Option<&str> = $file;
2137                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2138                         exp_file, file);
2139             }
2140         );
2141
2142         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2143             {
2144                 let path = Path::new($path);
2145
2146                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2147                 let exp_stem: Option<&str> = $file_stem;
2148                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2149                         exp_stem, stem);
2150
2151                 let ext = path.extension().map(|p| p.to_str().unwrap());
2152                 let exp_ext: Option<&str> = $extension;
2153                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2154                         exp_ext, ext);
2155             }
2156         );
2157
2158         ($path:expr, iter: $iter:expr,
2159                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2160                      parent: $parent:expr, file_name: $file:expr,
2161                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2162             {
2163                 t!($path, iter: $iter);
2164                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2165                 t!($path, parent: $parent, file_name: $file);
2166                 t!($path, file_stem: $file_stem, extension: $extension);
2167             }
2168         );
2169     );
2170
2171     #[test]
2172     #[allow(deprecated)]
2173     fn into_cow() {
2174         use borrow::{Cow, IntoCow};
2175
2176         let static_path = Path::new("/home/foo");
2177         let static_cow_path: Cow<'static, Path> = static_path.into_cow();
2178         let pathbuf = PathBuf::from("/home/foo");
2179
2180         {
2181             let path: &Path = &pathbuf;
2182             let borrowed_cow_path: Cow<Path> = path.into_cow();
2183
2184             assert_eq!(static_cow_path, borrowed_cow_path);
2185         }
2186
2187         let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
2188
2189         assert_eq!(static_cow_path, owned_cow_path);
2190     }
2191
2192     #[test]
2193     fn into() {
2194         use borrow::Cow;
2195
2196         let static_path = Path::new("/home/foo");
2197         let static_cow_path: Cow<'static, Path> = static_path.into();
2198         let pathbuf = PathBuf::from("/home/foo");
2199
2200         {
2201             let path: &Path = &pathbuf;
2202             let borrowed_cow_path: Cow<Path> = path.into();
2203
2204             assert_eq!(static_cow_path, borrowed_cow_path);
2205         }
2206
2207         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2208
2209         assert_eq!(static_cow_path, owned_cow_path);
2210     }
2211
2212     #[test]
2213     #[cfg(unix)]
2214     pub fn test_decompositions_unix() {
2215         t!("",
2216            iter: [],
2217            has_root: false,
2218            is_absolute: false,
2219            parent: None,
2220            file_name: None,
2221            file_stem: None,
2222            extension: None
2223            );
2224
2225         t!("foo",
2226            iter: ["foo"],
2227            has_root: false,
2228            is_absolute: false,
2229            parent: Some(""),
2230            file_name: Some("foo"),
2231            file_stem: Some("foo"),
2232            extension: None
2233            );
2234
2235         t!("/",
2236            iter: ["/"],
2237            has_root: true,
2238            is_absolute: true,
2239            parent: None,
2240            file_name: None,
2241            file_stem: None,
2242            extension: None
2243            );
2244
2245         t!("/foo",
2246            iter: ["/", "foo"],
2247            has_root: true,
2248            is_absolute: true,
2249            parent: Some("/"),
2250            file_name: Some("foo"),
2251            file_stem: Some("foo"),
2252            extension: None
2253            );
2254
2255         t!("foo/",
2256            iter: ["foo"],
2257            has_root: false,
2258            is_absolute: false,
2259            parent: Some(""),
2260            file_name: Some("foo"),
2261            file_stem: Some("foo"),
2262            extension: None
2263            );
2264
2265         t!("/foo/",
2266            iter: ["/", "foo"],
2267            has_root: true,
2268            is_absolute: true,
2269            parent: Some("/"),
2270            file_name: Some("foo"),
2271            file_stem: Some("foo"),
2272            extension: None
2273            );
2274
2275         t!("foo/bar",
2276            iter: ["foo", "bar"],
2277            has_root: false,
2278            is_absolute: false,
2279            parent: Some("foo"),
2280            file_name: Some("bar"),
2281            file_stem: Some("bar"),
2282            extension: None
2283            );
2284
2285         t!("/foo/bar",
2286            iter: ["/", "foo", "bar"],
2287            has_root: true,
2288            is_absolute: true,
2289            parent: Some("/foo"),
2290            file_name: Some("bar"),
2291            file_stem: Some("bar"),
2292            extension: None
2293            );
2294
2295         t!("///foo///",
2296            iter: ["/", "foo"],
2297            has_root: true,
2298            is_absolute: true,
2299            parent: Some("/"),
2300            file_name: Some("foo"),
2301            file_stem: Some("foo"),
2302            extension: None
2303            );
2304
2305         t!("///foo///bar",
2306            iter: ["/", "foo", "bar"],
2307            has_root: true,
2308            is_absolute: true,
2309            parent: Some("///foo"),
2310            file_name: Some("bar"),
2311            file_stem: Some("bar"),
2312            extension: None
2313            );
2314
2315         t!("./.",
2316            iter: ["."],
2317            has_root: false,
2318            is_absolute: false,
2319            parent: Some(""),
2320            file_name: None,
2321            file_stem: None,
2322            extension: None
2323            );
2324
2325         t!("/..",
2326            iter: ["/", ".."],
2327            has_root: true,
2328            is_absolute: true,
2329            parent: Some("/"),
2330            file_name: None,
2331            file_stem: None,
2332            extension: None
2333            );
2334
2335         t!("../",
2336            iter: [".."],
2337            has_root: false,
2338            is_absolute: false,
2339            parent: Some(""),
2340            file_name: None,
2341            file_stem: None,
2342            extension: None
2343            );
2344
2345         t!("foo/.",
2346            iter: ["foo"],
2347            has_root: false,
2348            is_absolute: false,
2349            parent: Some(""),
2350            file_name: Some("foo"),
2351            file_stem: Some("foo"),
2352            extension: None
2353            );
2354
2355         t!("foo/..",
2356            iter: ["foo", ".."],
2357            has_root: false,
2358            is_absolute: false,
2359            parent: Some("foo"),
2360            file_name: None,
2361            file_stem: None,
2362            extension: None
2363            );
2364
2365         t!("foo/./",
2366            iter: ["foo"],
2367            has_root: false,
2368            is_absolute: false,
2369            parent: Some(""),
2370            file_name: Some("foo"),
2371            file_stem: Some("foo"),
2372            extension: None
2373            );
2374
2375         t!("foo/./bar",
2376            iter: ["foo", "bar"],
2377            has_root: false,
2378            is_absolute: false,
2379            parent: Some("foo"),
2380            file_name: Some("bar"),
2381            file_stem: Some("bar"),
2382            extension: None
2383            );
2384
2385         t!("foo/../",
2386            iter: ["foo", ".."],
2387            has_root: false,
2388            is_absolute: false,
2389            parent: Some("foo"),
2390            file_name: None,
2391            file_stem: None,
2392            extension: None
2393            );
2394
2395         t!("foo/../bar",
2396            iter: ["foo", "..", "bar"],
2397            has_root: false,
2398            is_absolute: false,
2399            parent: Some("foo/.."),
2400            file_name: Some("bar"),
2401            file_stem: Some("bar"),
2402            extension: None
2403            );
2404
2405         t!("./a",
2406            iter: [".", "a"],
2407            has_root: false,
2408            is_absolute: false,
2409            parent: Some("."),
2410            file_name: Some("a"),
2411            file_stem: Some("a"),
2412            extension: None
2413            );
2414
2415         t!(".",
2416            iter: ["."],
2417            has_root: false,
2418            is_absolute: false,
2419            parent: Some(""),
2420            file_name: None,
2421            file_stem: None,
2422            extension: None
2423            );
2424
2425         t!("./",
2426            iter: ["."],
2427            has_root: false,
2428            is_absolute: false,
2429            parent: Some(""),
2430            file_name: None,
2431            file_stem: None,
2432            extension: None
2433            );
2434
2435         t!("a/b",
2436            iter: ["a", "b"],
2437            has_root: false,
2438            is_absolute: false,
2439            parent: Some("a"),
2440            file_name: Some("b"),
2441            file_stem: Some("b"),
2442            extension: None
2443            );
2444
2445         t!("a//b",
2446            iter: ["a", "b"],
2447            has_root: false,
2448            is_absolute: false,
2449            parent: Some("a"),
2450            file_name: Some("b"),
2451            file_stem: Some("b"),
2452            extension: None
2453            );
2454
2455         t!("a/./b",
2456            iter: ["a", "b"],
2457            has_root: false,
2458            is_absolute: false,
2459            parent: Some("a"),
2460            file_name: Some("b"),
2461            file_stem: Some("b"),
2462            extension: None
2463            );
2464
2465         t!("a/b/c",
2466            iter: ["a", "b", "c"],
2467            has_root: false,
2468            is_absolute: false,
2469            parent: Some("a/b"),
2470            file_name: Some("c"),
2471            file_stem: Some("c"),
2472            extension: None
2473            );
2474
2475         t!(".foo",
2476            iter: [".foo"],
2477            has_root: false,
2478            is_absolute: false,
2479            parent: Some(""),
2480            file_name: Some(".foo"),
2481            file_stem: Some(".foo"),
2482            extension: None
2483            );
2484     }
2485
2486     #[test]
2487     #[cfg(windows)]
2488     pub fn test_decompositions_windows() {
2489         t!("",
2490            iter: [],
2491            has_root: false,
2492            is_absolute: false,
2493            parent: None,
2494            file_name: None,
2495            file_stem: None,
2496            extension: None
2497            );
2498
2499         t!("foo",
2500            iter: ["foo"],
2501            has_root: false,
2502            is_absolute: false,
2503            parent: Some(""),
2504            file_name: Some("foo"),
2505            file_stem: Some("foo"),
2506            extension: None
2507            );
2508
2509         t!("/",
2510            iter: ["\\"],
2511            has_root: true,
2512            is_absolute: false,
2513            parent: None,
2514            file_name: None,
2515            file_stem: None,
2516            extension: None
2517            );
2518
2519         t!("\\",
2520            iter: ["\\"],
2521            has_root: true,
2522            is_absolute: false,
2523            parent: None,
2524            file_name: None,
2525            file_stem: None,
2526            extension: None
2527            );
2528
2529         t!("c:",
2530            iter: ["c:"],
2531            has_root: false,
2532            is_absolute: false,
2533            parent: None,
2534            file_name: None,
2535            file_stem: None,
2536            extension: None
2537            );
2538
2539         t!("c:\\",
2540            iter: ["c:", "\\"],
2541            has_root: true,
2542            is_absolute: true,
2543            parent: None,
2544            file_name: None,
2545            file_stem: None,
2546            extension: None
2547            );
2548
2549         t!("c:/",
2550            iter: ["c:", "\\"],
2551            has_root: true,
2552            is_absolute: true,
2553            parent: None,
2554            file_name: None,
2555            file_stem: None,
2556            extension: None
2557            );
2558
2559         t!("/foo",
2560            iter: ["\\", "foo"],
2561            has_root: true,
2562            is_absolute: false,
2563            parent: Some("/"),
2564            file_name: Some("foo"),
2565            file_stem: Some("foo"),
2566            extension: None
2567            );
2568
2569         t!("foo/",
2570            iter: ["foo"],
2571            has_root: false,
2572            is_absolute: false,
2573            parent: Some(""),
2574            file_name: Some("foo"),
2575            file_stem: Some("foo"),
2576            extension: None
2577            );
2578
2579         t!("/foo/",
2580            iter: ["\\", "foo"],
2581            has_root: true,
2582            is_absolute: false,
2583            parent: Some("/"),
2584            file_name: Some("foo"),
2585            file_stem: Some("foo"),
2586            extension: None
2587            );
2588
2589         t!("foo/bar",
2590            iter: ["foo", "bar"],
2591            has_root: false,
2592            is_absolute: false,
2593            parent: Some("foo"),
2594            file_name: Some("bar"),
2595            file_stem: Some("bar"),
2596            extension: None
2597            );
2598
2599         t!("/foo/bar",
2600            iter: ["\\", "foo", "bar"],
2601            has_root: true,
2602            is_absolute: false,
2603            parent: Some("/foo"),
2604            file_name: Some("bar"),
2605            file_stem: Some("bar"),
2606            extension: None
2607            );
2608
2609         t!("///foo///",
2610            iter: ["\\", "foo"],
2611            has_root: true,
2612            is_absolute: false,
2613            parent: Some("/"),
2614            file_name: Some("foo"),
2615            file_stem: Some("foo"),
2616            extension: None
2617            );
2618
2619         t!("///foo///bar",
2620            iter: ["\\", "foo", "bar"],
2621            has_root: true,
2622            is_absolute: false,
2623            parent: Some("///foo"),
2624            file_name: Some("bar"),
2625            file_stem: Some("bar"),
2626            extension: None
2627            );
2628
2629         t!("./.",
2630            iter: ["."],
2631            has_root: false,
2632            is_absolute: false,
2633            parent: Some(""),
2634            file_name: None,
2635            file_stem: None,
2636            extension: None
2637            );
2638
2639         t!("/..",
2640            iter: ["\\", ".."],
2641            has_root: true,
2642            is_absolute: false,
2643            parent: Some("/"),
2644            file_name: None,
2645            file_stem: None,
2646            extension: None
2647            );
2648
2649         t!("../",
2650            iter: [".."],
2651            has_root: false,
2652            is_absolute: false,
2653            parent: Some(""),
2654            file_name: None,
2655            file_stem: None,
2656            extension: None
2657            );
2658
2659         t!("foo/.",
2660            iter: ["foo"],
2661            has_root: false,
2662            is_absolute: false,
2663            parent: Some(""),
2664            file_name: Some("foo"),
2665            file_stem: Some("foo"),
2666            extension: None
2667            );
2668
2669         t!("foo/..",
2670            iter: ["foo", ".."],
2671            has_root: false,
2672            is_absolute: false,
2673            parent: Some("foo"),
2674            file_name: None,
2675            file_stem: None,
2676            extension: None
2677            );
2678
2679         t!("foo/./",
2680            iter: ["foo"],
2681            has_root: false,
2682            is_absolute: false,
2683            parent: Some(""),
2684            file_name: Some("foo"),
2685            file_stem: Some("foo"),
2686            extension: None
2687            );
2688
2689         t!("foo/./bar",
2690            iter: ["foo", "bar"],
2691            has_root: false,
2692            is_absolute: false,
2693            parent: Some("foo"),
2694            file_name: Some("bar"),
2695            file_stem: Some("bar"),
2696            extension: None
2697            );
2698
2699         t!("foo/../",
2700            iter: ["foo", ".."],
2701            has_root: false,
2702            is_absolute: false,
2703            parent: Some("foo"),
2704            file_name: None,
2705            file_stem: None,
2706            extension: None
2707            );
2708
2709         t!("foo/../bar",
2710            iter: ["foo", "..", "bar"],
2711            has_root: false,
2712            is_absolute: false,
2713            parent: Some("foo/.."),
2714            file_name: Some("bar"),
2715            file_stem: Some("bar"),
2716            extension: None
2717            );
2718
2719         t!("./a",
2720            iter: [".", "a"],
2721            has_root: false,
2722            is_absolute: false,
2723            parent: Some("."),
2724            file_name: Some("a"),
2725            file_stem: Some("a"),
2726            extension: None
2727            );
2728
2729         t!(".",
2730            iter: ["."],
2731            has_root: false,
2732            is_absolute: false,
2733            parent: Some(""),
2734            file_name: None,
2735            file_stem: None,
2736            extension: None
2737            );
2738
2739         t!("./",
2740            iter: ["."],
2741            has_root: false,
2742            is_absolute: false,
2743            parent: Some(""),
2744            file_name: None,
2745            file_stem: None,
2746            extension: None
2747            );
2748
2749         t!("a/b",
2750            iter: ["a", "b"],
2751            has_root: false,
2752            is_absolute: false,
2753            parent: Some("a"),
2754            file_name: Some("b"),
2755            file_stem: Some("b"),
2756            extension: None
2757            );
2758
2759         t!("a//b",
2760            iter: ["a", "b"],
2761            has_root: false,
2762            is_absolute: false,
2763            parent: Some("a"),
2764            file_name: Some("b"),
2765            file_stem: Some("b"),
2766            extension: None
2767            );
2768
2769         t!("a/./b",
2770            iter: ["a", "b"],
2771            has_root: false,
2772            is_absolute: false,
2773            parent: Some("a"),
2774            file_name: Some("b"),
2775            file_stem: Some("b"),
2776            extension: None
2777            );
2778
2779         t!("a/b/c",
2780            iter: ["a", "b", "c"],
2781            has_root: false,
2782            is_absolute: false,
2783            parent: Some("a/b"),
2784            file_name: Some("c"),
2785            file_stem: Some("c"),
2786            extension: None);
2787
2788         t!("a\\b\\c",
2789            iter: ["a", "b", "c"],
2790            has_root: false,
2791            is_absolute: false,
2792            parent: Some("a\\b"),
2793            file_name: Some("c"),
2794            file_stem: Some("c"),
2795            extension: None
2796            );
2797
2798         t!("\\a",
2799            iter: ["\\", "a"],
2800            has_root: true,
2801            is_absolute: false,
2802            parent: Some("\\"),
2803            file_name: Some("a"),
2804            file_stem: Some("a"),
2805            extension: None
2806            );
2807
2808         t!("c:\\foo.txt",
2809            iter: ["c:", "\\", "foo.txt"],
2810            has_root: true,
2811            is_absolute: true,
2812            parent: Some("c:\\"),
2813            file_name: Some("foo.txt"),
2814            file_stem: Some("foo"),
2815            extension: Some("txt")
2816            );
2817
2818         t!("\\\\server\\share\\foo.txt",
2819            iter: ["\\\\server\\share", "\\", "foo.txt"],
2820            has_root: true,
2821            is_absolute: true,
2822            parent: Some("\\\\server\\share\\"),
2823            file_name: Some("foo.txt"),
2824            file_stem: Some("foo"),
2825            extension: Some("txt")
2826            );
2827
2828         t!("\\\\server\\share",
2829            iter: ["\\\\server\\share", "\\"],
2830            has_root: true,
2831            is_absolute: true,
2832            parent: None,
2833            file_name: None,
2834            file_stem: None,
2835            extension: None
2836            );
2837
2838         t!("\\\\server",
2839            iter: ["\\", "server"],
2840            has_root: true,
2841            is_absolute: false,
2842            parent: Some("\\"),
2843            file_name: Some("server"),
2844            file_stem: Some("server"),
2845            extension: None
2846            );
2847
2848         t!("\\\\?\\bar\\foo.txt",
2849            iter: ["\\\\?\\bar", "\\", "foo.txt"],
2850            has_root: true,
2851            is_absolute: true,
2852            parent: Some("\\\\?\\bar\\"),
2853            file_name: Some("foo.txt"),
2854            file_stem: Some("foo"),
2855            extension: Some("txt")
2856            );
2857
2858         t!("\\\\?\\bar",
2859            iter: ["\\\\?\\bar"],
2860            has_root: true,
2861            is_absolute: true,
2862            parent: None,
2863            file_name: None,
2864            file_stem: None,
2865            extension: None
2866            );
2867
2868         t!("\\\\?\\",
2869            iter: ["\\\\?\\"],
2870            has_root: true,
2871            is_absolute: true,
2872            parent: None,
2873            file_name: None,
2874            file_stem: None,
2875            extension: None
2876            );
2877
2878         t!("\\\\?\\UNC\\server\\share\\foo.txt",
2879            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2880            has_root: true,
2881            is_absolute: true,
2882            parent: Some("\\\\?\\UNC\\server\\share\\"),
2883            file_name: Some("foo.txt"),
2884            file_stem: Some("foo"),
2885            extension: Some("txt")
2886            );
2887
2888         t!("\\\\?\\UNC\\server",
2889            iter: ["\\\\?\\UNC\\server"],
2890            has_root: true,
2891            is_absolute: true,
2892            parent: None,
2893            file_name: None,
2894            file_stem: None,
2895            extension: None
2896            );
2897
2898         t!("\\\\?\\UNC\\",
2899            iter: ["\\\\?\\UNC\\"],
2900            has_root: true,
2901            is_absolute: true,
2902            parent: None,
2903            file_name: None,
2904            file_stem: None,
2905            extension: None
2906            );
2907
2908         t!("\\\\?\\C:\\foo.txt",
2909            iter: ["\\\\?\\C:", "\\", "foo.txt"],
2910            has_root: true,
2911            is_absolute: true,
2912            parent: Some("\\\\?\\C:\\"),
2913            file_name: Some("foo.txt"),
2914            file_stem: Some("foo"),
2915            extension: Some("txt")
2916            );
2917
2918
2919         t!("\\\\?\\C:\\",
2920            iter: ["\\\\?\\C:", "\\"],
2921            has_root: true,
2922            is_absolute: true,
2923            parent: None,
2924            file_name: None,
2925            file_stem: None,
2926            extension: None
2927            );
2928
2929
2930         t!("\\\\?\\C:",
2931            iter: ["\\\\?\\C:"],
2932            has_root: true,
2933            is_absolute: true,
2934            parent: None,
2935            file_name: None,
2936            file_stem: None,
2937            extension: None
2938            );
2939
2940
2941         t!("\\\\?\\foo/bar",
2942            iter: ["\\\\?\\foo/bar"],
2943            has_root: true,
2944            is_absolute: true,
2945            parent: None,
2946            file_name: None,
2947            file_stem: None,
2948            extension: None
2949            );
2950
2951
2952         t!("\\\\?\\C:/foo",
2953            iter: ["\\\\?\\C:/foo"],
2954            has_root: true,
2955            is_absolute: true,
2956            parent: None,
2957            file_name: None,
2958            file_stem: None,
2959            extension: None
2960            );
2961
2962
2963         t!("\\\\.\\foo\\bar",
2964            iter: ["\\\\.\\foo", "\\", "bar"],
2965            has_root: true,
2966            is_absolute: true,
2967            parent: Some("\\\\.\\foo\\"),
2968            file_name: Some("bar"),
2969            file_stem: Some("bar"),
2970            extension: None
2971            );
2972
2973
2974         t!("\\\\.\\foo",
2975            iter: ["\\\\.\\foo", "\\"],
2976            has_root: true,
2977            is_absolute: true,
2978            parent: None,
2979            file_name: None,
2980            file_stem: None,
2981            extension: None
2982            );
2983
2984
2985         t!("\\\\.\\foo/bar",
2986            iter: ["\\\\.\\foo/bar", "\\"],
2987            has_root: true,
2988            is_absolute: true,
2989            parent: None,
2990            file_name: None,
2991            file_stem: None,
2992            extension: None
2993            );
2994
2995
2996         t!("\\\\.\\foo\\bar/baz",
2997            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2998            has_root: true,
2999            is_absolute: true,
3000            parent: Some("\\\\.\\foo\\bar"),
3001            file_name: Some("baz"),
3002            file_stem: Some("baz"),
3003            extension: None
3004            );
3005
3006
3007         t!("\\\\.\\",
3008            iter: ["\\\\.\\", "\\"],
3009            has_root: true,
3010            is_absolute: true,
3011            parent: None,
3012            file_name: None,
3013            file_stem: None,
3014            extension: None
3015            );
3016
3017         t!("\\\\?\\a\\b\\",
3018            iter: ["\\\\?\\a", "\\", "b"],
3019            has_root: true,
3020            is_absolute: true,
3021            parent: Some("\\\\?\\a\\"),
3022            file_name: Some("b"),
3023            file_stem: Some("b"),
3024            extension: None
3025            );
3026     }
3027
3028     #[test]
3029     pub fn test_stem_ext() {
3030         t!("foo",
3031            file_stem: Some("foo"),
3032            extension: None
3033            );
3034
3035         t!("foo.",
3036            file_stem: Some("foo"),
3037            extension: Some("")
3038            );
3039
3040         t!(".foo",
3041            file_stem: Some(".foo"),
3042            extension: None
3043            );
3044
3045         t!("foo.txt",
3046            file_stem: Some("foo"),
3047            extension: Some("txt")
3048            );
3049
3050         t!("foo.bar.txt",
3051            file_stem: Some("foo.bar"),
3052            extension: Some("txt")
3053            );
3054
3055         t!("foo.bar.",
3056            file_stem: Some("foo.bar"),
3057            extension: Some("")
3058            );
3059
3060         t!(".",
3061            file_stem: None,
3062            extension: None
3063            );
3064
3065         t!("..",
3066            file_stem: None,
3067            extension: None
3068            );
3069
3070         t!("",
3071            file_stem: None,
3072            extension: None
3073            );
3074     }
3075
3076     #[test]
3077     pub fn test_push() {
3078         macro_rules! tp(
3079             ($path:expr, $push:expr, $expected:expr) => ( {
3080                 let mut actual = PathBuf::from($path);
3081                 actual.push($push);
3082                 assert!(actual.to_str() == Some($expected),
3083                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3084                         $push, $path, $expected, actual.to_str().unwrap());
3085             });
3086         );
3087
3088         if cfg!(unix) {
3089             tp!("", "foo", "foo");
3090             tp!("foo", "bar", "foo/bar");
3091             tp!("foo/", "bar", "foo/bar");
3092             tp!("foo//", "bar", "foo//bar");
3093             tp!("foo/.", "bar", "foo/./bar");
3094             tp!("foo./.", "bar", "foo././bar");
3095             tp!("foo", "", "foo/");
3096             tp!("foo", ".", "foo/.");
3097             tp!("foo", "..", "foo/..");
3098             tp!("foo", "/", "/");
3099             tp!("/foo/bar", "/", "/");
3100             tp!("/foo/bar", "/baz", "/baz");
3101             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3102         } else {
3103             tp!("", "foo", "foo");
3104             tp!("foo", "bar", r"foo\bar");
3105             tp!("foo/", "bar", r"foo/bar");
3106             tp!(r"foo\", "bar", r"foo\bar");
3107             tp!("foo//", "bar", r"foo//bar");
3108             tp!(r"foo\\", "bar", r"foo\\bar");
3109             tp!("foo/.", "bar", r"foo/.\bar");
3110             tp!("foo./.", "bar", r"foo./.\bar");
3111             tp!(r"foo\.", "bar", r"foo\.\bar");
3112             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3113             tp!("foo", "", "foo\\");
3114             tp!("foo", ".", r"foo\.");
3115             tp!("foo", "..", r"foo\..");
3116             tp!("foo", "/", "/");
3117             tp!("foo", r"\", r"\");
3118             tp!("/foo/bar", "/", "/");
3119             tp!(r"\foo\bar", r"\", r"\");
3120             tp!("/foo/bar", "/baz", "/baz");
3121             tp!("/foo/bar", r"\baz", r"\baz");
3122             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3123             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3124
3125             tp!("c:\\", "windows", "c:\\windows");
3126             tp!("c:", "windows", "c:windows");
3127
3128             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3129             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3130             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3131             tp!("a\\b", "\\c\\d", "\\c\\d");
3132             tp!("a\\b", ".", "a\\b\\.");
3133             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3134             tp!("a\\b", "C:a.txt", "C:a.txt");
3135             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3136             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3137             tp!("C:\\a\\b\\c", "C:d", "C:d");
3138             tp!("C:a\\b\\c", "C:d", "C:d");
3139             tp!("C:", r"a\b\c", r"C:a\b\c");
3140             tp!("C:", r"..\a", r"C:..\a");
3141             tp!("\\\\server\\share\\foo",
3142                 "bar",
3143                 "\\\\server\\share\\foo\\bar");
3144             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3145             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3146             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3147             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3148             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3149             tp!("\\\\?\\UNC\\server\\share\\foo",
3150                 "bar",
3151                 "\\\\?\\UNC\\server\\share\\foo\\bar");
3152             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3153             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3154
3155             // Note: modified from old path API
3156             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3157
3158             tp!("C:\\a",
3159                 "\\\\?\\UNC\\server\\share",
3160                 "\\\\?\\UNC\\server\\share");
3161             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3162             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3163             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3164             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3165
3166             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3167         }
3168     }
3169
3170     #[test]
3171     pub fn test_pop() {
3172         macro_rules! tp(
3173             ($path:expr, $expected:expr, $output:expr) => ( {
3174                 let mut actual = PathBuf::from($path);
3175                 let output = actual.pop();
3176                 assert!(actual.to_str() == Some($expected) && output == $output,
3177                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3178                         $path, $expected, $output,
3179                         actual.to_str().unwrap(), output);
3180             });
3181         );
3182
3183         tp!("", "", false);
3184         tp!("/", "/", false);
3185         tp!("foo", "", true);
3186         tp!(".", "", true);
3187         tp!("/foo", "/", true);
3188         tp!("/foo/bar", "/foo", true);
3189         tp!("foo/bar", "foo", true);
3190         tp!("foo/.", "", true);
3191         tp!("foo//bar", "foo", true);
3192
3193         if cfg!(windows) {
3194             tp!("a\\b\\c", "a\\b", true);
3195             tp!("\\a", "\\", true);
3196             tp!("\\", "\\", false);
3197
3198             tp!("C:\\a\\b", "C:\\a", true);
3199             tp!("C:\\a", "C:\\", true);
3200             tp!("C:\\", "C:\\", false);
3201             tp!("C:a\\b", "C:a", true);
3202             tp!("C:a", "C:", true);
3203             tp!("C:", "C:", false);
3204             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3205             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3206             tp!("\\\\server\\share", "\\\\server\\share", false);
3207             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3208             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3209             tp!("\\\\?\\a", "\\\\?\\a", false);
3210             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3211             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3212             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3213             tp!("\\\\?\\UNC\\server\\share\\a\\b",
3214                 "\\\\?\\UNC\\server\\share\\a",
3215                 true);
3216             tp!("\\\\?\\UNC\\server\\share\\a",
3217                 "\\\\?\\UNC\\server\\share\\",
3218                 true);
3219             tp!("\\\\?\\UNC\\server\\share",
3220                 "\\\\?\\UNC\\server\\share",
3221                 false);
3222             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3223             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3224             tp!("\\\\.\\a", "\\\\.\\a", false);
3225
3226             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3227         }
3228     }
3229
3230     #[test]
3231     pub fn test_set_file_name() {
3232         macro_rules! tfn(
3233                 ($path:expr, $file:expr, $expected:expr) => ( {
3234                 let mut p = PathBuf::from($path);
3235                 p.set_file_name($file);
3236                 assert!(p.to_str() == Some($expected),
3237                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3238                         $path, $file, $expected,
3239                         p.to_str().unwrap());
3240             });
3241         );
3242
3243         tfn!("foo", "foo", "foo");
3244         tfn!("foo", "bar", "bar");
3245         tfn!("foo", "", "");
3246         tfn!("", "foo", "foo");
3247         if cfg!(unix) {
3248             tfn!(".", "foo", "./foo");
3249             tfn!("foo/", "bar", "bar");
3250             tfn!("foo/.", "bar", "bar");
3251             tfn!("..", "foo", "../foo");
3252             tfn!("foo/..", "bar", "foo/../bar");
3253             tfn!("/", "foo", "/foo");
3254         } else {
3255             tfn!(".", "foo", r".\foo");
3256             tfn!(r"foo\", "bar", r"bar");
3257             tfn!(r"foo\.", "bar", r"bar");
3258             tfn!("..", "foo", r"..\foo");
3259             tfn!(r"foo\..", "bar", r"foo\..\bar");
3260             tfn!(r"\", "foo", r"\foo");
3261         }
3262     }
3263
3264     #[test]
3265     pub fn test_set_extension() {
3266         macro_rules! tfe(
3267                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3268                 let mut p = PathBuf::from($path);
3269                 let output = p.set_extension($ext);
3270                 assert!(p.to_str() == Some($expected) && output == $output,
3271                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3272                         $path, $ext, $expected, $output,
3273                         p.to_str().unwrap(), output);
3274             });
3275         );
3276
3277         tfe!("foo", "txt", "foo.txt", true);
3278         tfe!("foo.bar", "txt", "foo.txt", true);
3279         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3280         tfe!(".test", "txt", ".test.txt", true);
3281         tfe!("foo.txt", "", "foo", true);
3282         tfe!("foo", "", "foo", true);
3283         tfe!("", "foo", "", false);
3284         tfe!(".", "foo", ".", false);
3285         tfe!("foo/", "bar", "foo.bar", true);
3286         tfe!("foo/.", "bar", "foo.bar", true);
3287         tfe!("..", "foo", "..", false);
3288         tfe!("foo/..", "bar", "foo/..", false);
3289         tfe!("/", "foo", "/", false);
3290     }
3291
3292     #[test]
3293     fn test_eq_recievers() {
3294         use borrow::Cow;
3295
3296         let borrowed: &Path = Path::new("foo/bar");
3297         let mut owned: PathBuf = PathBuf::new();
3298         owned.push("foo");
3299         owned.push("bar");
3300         let borrowed_cow: Cow<Path> = borrowed.into();
3301         let owned_cow: Cow<Path> = owned.clone().into();
3302
3303         macro_rules! t {
3304             ($($current:expr),+) => {
3305                 $(
3306                     assert_eq!($current, borrowed);
3307                     assert_eq!($current, owned);
3308                     assert_eq!($current, borrowed_cow);
3309                     assert_eq!($current, owned_cow);
3310                 )+
3311             }
3312         }
3313
3314         t!(borrowed, owned, borrowed_cow, owned_cow);
3315     }
3316
3317     #[test]
3318     pub fn test_compare() {
3319         use hash::{Hash, Hasher, SipHasher};
3320
3321         fn hash<T: Hash>(t: T) -> u64 {
3322             let mut s = SipHasher::new_with_keys(0, 0);
3323             t.hash(&mut s);
3324             s.finish()
3325         }
3326
3327         macro_rules! tc(
3328             ($path1:expr, $path2:expr, eq: $eq:expr,
3329              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3330              relative_from: $relative_from:expr) => ({
3331                  let path1 = Path::new($path1);
3332                  let path2 = Path::new($path2);
3333
3334                  let eq = path1 == path2;
3335                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3336                          $path1, $path2, $eq, eq);
3337                  assert!($eq == (hash(path1) == hash(path2)),
3338                          "{:?} == {:?}, expected {:?}, got {} and {}",
3339                          $path1, $path2, $eq, hash(path1), hash(path2));
3340
3341                  let starts_with = path1.starts_with(path2);
3342                  assert!(starts_with == $starts_with,
3343                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3344                          $starts_with, starts_with);
3345
3346                  let ends_with = path1.ends_with(path2);
3347                  assert!(ends_with == $ends_with,
3348                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3349                          $ends_with, ends_with);
3350
3351                  let relative_from = path1.strip_prefix(path2)
3352                                           .map(|p| p.to_str().unwrap())
3353                                           .ok();
3354                  let exp: Option<&str> = $relative_from;
3355                  assert!(relative_from == exp,
3356                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3357                          $path1, $path2, exp, relative_from);
3358             });
3359         );
3360
3361         tc!("", "",
3362             eq: true,
3363             starts_with: true,
3364             ends_with: true,
3365             relative_from: Some("")
3366             );
3367
3368         tc!("foo", "",
3369             eq: false,
3370             starts_with: true,
3371             ends_with: true,
3372             relative_from: Some("foo")
3373             );
3374
3375         tc!("", "foo",
3376             eq: false,
3377             starts_with: false,
3378             ends_with: false,
3379             relative_from: None
3380             );
3381
3382         tc!("foo", "foo",
3383             eq: true,
3384             starts_with: true,
3385             ends_with: true,
3386             relative_from: Some("")
3387             );
3388
3389         tc!("foo/", "foo",
3390             eq: true,
3391             starts_with: true,
3392             ends_with: true,
3393             relative_from: Some("")
3394             );
3395
3396         tc!("foo/bar", "foo",
3397             eq: false,
3398             starts_with: true,
3399             ends_with: false,
3400             relative_from: Some("bar")
3401             );
3402
3403         tc!("foo/bar/baz", "foo/bar",
3404             eq: false,
3405             starts_with: true,
3406             ends_with: false,
3407             relative_from: Some("baz")
3408             );
3409
3410         tc!("foo/bar", "foo/bar/baz",
3411             eq: false,
3412             starts_with: false,
3413             ends_with: false,
3414             relative_from: None
3415             );
3416
3417         tc!("./foo/bar/", ".",
3418             eq: false,
3419             starts_with: true,
3420             ends_with: false,
3421             relative_from: Some("foo/bar")
3422             );
3423
3424         if cfg!(windows) {
3425             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3426                 r"c:\src\rust\cargo-test\test",
3427                 eq: false,
3428                 starts_with: true,
3429                 ends_with: false,
3430                 relative_from: Some("Cargo.toml")
3431                 );
3432
3433             tc!(r"c:\foo", r"C:\foo",
3434                 eq: true,
3435                 starts_with: true,
3436                 ends_with: true,
3437                 relative_from: Some("")
3438                 );
3439         }
3440     }
3441 }