]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
SGX target: fix std unit tests
[rust.git] / src / libstd / path.rs
1 //! Cross-platform path manipulation.
2 //!
3 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
4 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
5 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
6 //! on strings according to the local platform's path syntax.
7 //!
8 //! Paths can be parsed into [`Component`]s by iterating over the structure
9 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
10 //! correspond to the substrings between path separators (`/` or `\`). You can
11 //! reconstruct an equivalent path from components with the [`push`] method on
12 //! [`PathBuf`]; note that the paths may differ syntactically by the
13 //! normalization described in the documentation for the [`components`] method.
14 //!
15 //! ## Simple usage
16 //!
17 //! Path manipulation includes both parsing components from slices and building
18 //! new owned paths.
19 //!
20 //! To parse a path, you can create a [`Path`] slice from a [`str`]
21 //! slice and start asking questions:
22 //!
23 //! ```
24 //! use std::path::Path;
25 //! use std::ffi::OsStr;
26 //!
27 //! let path = Path::new("/tmp/foo/bar.txt");
28 //!
29 //! let parent = path.parent();
30 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
31 //!
32 //! let file_stem = path.file_stem();
33 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
34 //!
35 //! let extension = path.extension();
36 //! assert_eq!(extension, Some(OsStr::new("txt")));
37 //! ```
38 //!
39 //! To build or modify paths, use [`PathBuf`]:
40 //!
41 //! ```
42 //! use std::path::PathBuf;
43 //!
44 //! // This way works...
45 //! let mut path = PathBuf::from("c:\\");
46 //!
47 //! path.push("windows");
48 //! path.push("system32");
49 //!
50 //! path.set_extension("dll");
51 //!
52 //! // ... but push is best used if you don't know everything up
53 //! // front. If you do, this way is better:
54 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
55 //! ```
56 //!
57 //! [`Component`]: ../../std/path/enum.Component.html
58 //! [`components`]: ../../std/path/struct.Path.html#method.components
59 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
60 //! [`Path`]: ../../std/path/struct.Path.html
61 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
62 //! [`String`]: ../../std/string/struct.String.html
63 //!
64 //! [`str`]: ../../std/primitive.str.html
65 //! [`OsString`]: ../../std/ffi/struct.OsString.html
66 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
67
68 #![stable(feature = "rust1", since = "1.0.0")]
69
70 use crate::borrow::{Borrow, Cow};
71 use crate::cmp;
72 use crate::error::Error;
73 use crate::fmt;
74 use crate::fs;
75 use crate::hash::{Hash, Hasher};
76 use crate::io;
77 use crate::iter::{self, FusedIterator};
78 use crate::ops::{self, Deref};
79 use crate::rc::Rc;
80 use crate::str::FromStr;
81 use crate::sync::Arc;
82
83 use crate::ffi::{OsStr, OsString};
84
85 use crate::sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
86
87 ////////////////////////////////////////////////////////////////////////////////
88 // GENERAL NOTES
89 ////////////////////////////////////////////////////////////////////////////////
90 //
91 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
92 // taking advantage of the fact that OsStr always encodes ASCII characters
93 // as-is.  Eventually, this transmutation should be replaced by direct uses of
94 // OsStr APIs for parsing, but it will take a while for those to become
95 // available.
96
97 ////////////////////////////////////////////////////////////////////////////////
98 // Windows Prefixes
99 ////////////////////////////////////////////////////////////////////////////////
100
101 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
102 ///
103 /// Windows uses a variety of path prefix styles, including references to drive
104 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
105 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
106 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
107 /// no normalization is performed.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use std::path::{Component, Path, Prefix};
113 /// use std::path::Prefix::*;
114 /// use std::ffi::OsStr;
115 ///
116 /// fn get_path_prefix(s: &str) -> Prefix {
117 ///     let path = Path::new(s);
118 ///     match path.components().next().unwrap() {
119 ///         Component::Prefix(prefix_component) => prefix_component.kind(),
120 ///         _ => panic!(),
121 ///     }
122 /// }
123 ///
124 /// # if cfg!(windows) {
125 /// assert_eq!(Verbatim(OsStr::new("pictures")),
126 ///            get_path_prefix(r"\\?\pictures\kittens"));
127 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
128 ///            get_path_prefix(r"\\?\UNC\server\share"));
129 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
130 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
131 ///            get_path_prefix(r"\\.\BrainInterface"));
132 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
133 ///            get_path_prefix(r"\\server\share"));
134 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
135 /// # }
136 /// ```
137 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub enum Prefix<'a> {
140     /// Verbatim prefix, e.g., `\\?\cat_pics`.
141     ///
142     /// Verbatim prefixes consist of `\\?\` immediately followed by the given
143     /// component.
144     #[stable(feature = "rust1", since = "1.0.0")]
145     Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
146
147     /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
148     /// e.g., `\\?\UNC\server\share`.
149     ///
150     /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
151     /// server's hostname and a share name.
152     #[stable(feature = "rust1", since = "1.0.0")]
153     VerbatimUNC(
154         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
155         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
156     ),
157
158     /// Verbatim disk prefix, e.g., `\\?\C:\`.
159     ///
160     /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
161     /// drive letter and `:\`.
162     #[stable(feature = "rust1", since = "1.0.0")]
163     VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
164
165     /// Device namespace prefix, e.g., `\\.\COM42`.
166     ///
167     /// Device namespace prefixes consist of `\\.\` immediately followed by the
168     /// device name.
169     #[stable(feature = "rust1", since = "1.0.0")]
170     DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
171
172     /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
173     /// `\\server\share`.
174     ///
175     /// UNC prefixes consist of the server's hostname and a share name.
176     #[stable(feature = "rust1", since = "1.0.0")]
177     UNC(
178         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
179         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
180     ),
181
182     /// Prefix `C:` for the given disk drive.
183     #[stable(feature = "rust1", since = "1.0.0")]
184     Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
185 }
186
187 impl<'a> Prefix<'a> {
188     #[inline]
189     fn len(&self) -> usize {
190         use self::Prefix::*;
191         fn os_str_len(s: &OsStr) -> usize {
192             os_str_as_u8_slice(s).len()
193         }
194         match *self {
195             Verbatim(x) => 4 + os_str_len(x),
196             VerbatimUNC(x, y) => {
197                 8 + os_str_len(x) +
198                 if os_str_len(y) > 0 {
199                     1 + os_str_len(y)
200                 } else {
201                     0
202                 }
203             },
204             VerbatimDisk(_) => 6,
205             UNC(x, y) => {
206                 2 + os_str_len(x) +
207                 if os_str_len(y) > 0 {
208                     1 + os_str_len(y)
209                 } else {
210                     0
211                 }
212             },
213             DeviceNS(x) => 4 + os_str_len(x),
214             Disk(_) => 2,
215         }
216
217     }
218
219     /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
220     ///
221     /// # Examples
222     ///
223     /// ```
224     /// use std::path::Prefix::*;
225     /// use std::ffi::OsStr;
226     ///
227     /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
228     /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
229     /// assert!(VerbatimDisk(b'C').is_verbatim());
230     /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
231     /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
232     /// assert!(!Disk(b'C').is_verbatim());
233     /// ```
234     #[inline]
235     #[stable(feature = "rust1", since = "1.0.0")]
236     pub fn is_verbatim(&self) -> bool {
237         use self::Prefix::*;
238         match *self {
239             Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
240             _ => false,
241         }
242     }
243
244     #[inline]
245     fn is_drive(&self) -> bool {
246         match *self {
247             Prefix::Disk(_) => true,
248             _ => false,
249         }
250     }
251
252     #[inline]
253     fn has_implicit_root(&self) -> bool {
254         !self.is_drive()
255     }
256 }
257
258 ////////////////////////////////////////////////////////////////////////////////
259 // Exposed parsing helpers
260 ////////////////////////////////////////////////////////////////////////////////
261
262 /// Determines whether the character is one of the permitted path
263 /// separators for the current platform.
264 ///
265 /// # Examples
266 ///
267 /// ```
268 /// use std::path;
269 ///
270 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
271 /// assert!(!path::is_separator('❤'));
272 /// ```
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub fn is_separator(c: char) -> bool {
275     c.is_ascii() && is_sep_byte(c as u8)
276 }
277
278 /// The primary separator of path components for the current platform.
279 ///
280 /// For example, `/` on Unix and `\` on Windows.
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
283
284 ////////////////////////////////////////////////////////////////////////////////
285 // Misc helpers
286 ////////////////////////////////////////////////////////////////////////////////
287
288 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
289 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
290 // `iter` after having exhausted `prefix`.
291 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
292     where I: Iterator<Item = Component<'a>> + Clone,
293           J: Iterator<Item = Component<'b>>,
294 {
295     loop {
296         let mut iter_next = iter.clone();
297         match (iter_next.next(), prefix.next()) {
298             (Some(ref x), Some(ref y)) if x == y => (),
299             (Some(_), Some(_)) => return None,
300             (Some(_), None) => return Some(iter),
301             (None, None) => return Some(iter),
302             (None, Some(_)) => return None,
303         }
304         iter = iter_next;
305     }
306 }
307
308 // See note at the top of this module to understand why these are used:
309 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
310     unsafe { &*(s as *const OsStr as *const [u8]) }
311 }
312 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
313     &*(s as *const [u8] as *const OsStr)
314 }
315
316 // Detect scheme on Redox
317 fn has_redox_scheme(s: &[u8]) -> bool {
318     cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
319 }
320
321 ////////////////////////////////////////////////////////////////////////////////
322 // Cross-platform, iterator-independent parsing
323 ////////////////////////////////////////////////////////////////////////////////
324
325 /// Says whether the first byte after the prefix is a separator.
326 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
327     let path = if let Some(p) = prefix {
328         &s[p.len()..]
329     } else {
330         s
331     };
332     !path.is_empty() && is_sep_byte(path[0])
333 }
334
335 // basic workhorse for splitting stem and extension
336 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
337     unsafe {
338         if os_str_as_u8_slice(file) == b".." {
339             return (Some(file), None);
340         }
341
342         // The unsafety here stems from converting between &OsStr and &[u8]
343         // and back. This is safe to do because (1) we only look at ASCII
344         // contents of the encoding and (2) new &OsStr values are produced
345         // only from ASCII-bounded slices of existing &OsStr values.
346
347         let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
348         let after = iter.next();
349         let before = iter.next();
350         if before == Some(b"") {
351             (Some(file), None)
352         } else {
353             (before.map(|s| u8_slice_as_os_str(s)),
354              after.map(|s| u8_slice_as_os_str(s)))
355         }
356     }
357 }
358
359 ////////////////////////////////////////////////////////////////////////////////
360 // The core iterators
361 ////////////////////////////////////////////////////////////////////////////////
362
363 /// Component parsing works by a double-ended state machine; the cursors at the
364 /// front and back of the path each keep track of what parts of the path have
365 /// been consumed so far.
366 ///
367 /// Going front to back, a path is made up of a prefix, a starting
368 /// directory component, and a body (of normal components)
369 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
370 enum State {
371     Prefix = 0,         // c:
372     StartDir = 1,       // / or . or nothing
373     Body = 2,           // foo/bar/baz
374     Done = 3,
375 }
376
377 /// A structure wrapping a Windows path prefix as well as its unparsed string
378 /// representation.
379 ///
380 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
381 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
382 /// returned by [`as_os_str`].
383 ///
384 /// Instances of this `struct` can be obtained by matching against the
385 /// [`Prefix` variant] on [`Component`].
386 ///
387 /// Does not occur on Unix.
388 ///
389 /// # Examples
390 ///
391 /// ```
392 /// # if cfg!(windows) {
393 /// use std::path::{Component, Path, Prefix};
394 /// use std::ffi::OsStr;
395 ///
396 /// let path = Path::new(r"c:\you\later\");
397 /// match path.components().next().unwrap() {
398 ///     Component::Prefix(prefix_component) => {
399 ///         assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
400 ///         assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
401 ///     }
402 ///     _ => unreachable!(),
403 /// }
404 /// # }
405 /// ```
406 ///
407 /// [`as_os_str`]: #method.as_os_str
408 /// [`Component`]: enum.Component.html
409 /// [`kind`]: #method.kind
410 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
411 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
412 /// [`Prefix`]: enum.Prefix.html
413 #[stable(feature = "rust1", since = "1.0.0")]
414 #[derive(Copy, Clone, Eq, Debug)]
415 pub struct PrefixComponent<'a> {
416     /// The prefix as an unparsed `OsStr` slice.
417     raw: &'a OsStr,
418
419     /// The parsed prefix data.
420     parsed: Prefix<'a>,
421 }
422
423 impl<'a> PrefixComponent<'a> {
424     /// Returns the parsed prefix data.
425     ///
426     /// See [`Prefix`]'s documentation for more information on the different
427     /// kinds of prefixes.
428     ///
429     /// [`Prefix`]: enum.Prefix.html
430     #[stable(feature = "rust1", since = "1.0.0")]
431     pub fn kind(&self) -> Prefix<'a> {
432         self.parsed
433     }
434
435     /// Returns the raw [`OsStr`] slice for this prefix.
436     ///
437     /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
438     #[stable(feature = "rust1", since = "1.0.0")]
439     pub fn as_os_str(&self) -> &'a OsStr {
440         self.raw
441     }
442 }
443
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
446     fn eq(&self, other: &PrefixComponent<'a>) -> bool {
447         cmp::PartialEq::eq(&self.parsed, &other.parsed)
448     }
449 }
450
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
453     fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
454         cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
455     }
456 }
457
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl cmp::Ord for PrefixComponent<'_> {
460     fn cmp(&self, other: &Self) -> cmp::Ordering {
461         cmp::Ord::cmp(&self.parsed, &other.parsed)
462     }
463 }
464
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl Hash for PrefixComponent<'_> {
467     fn hash<H: Hasher>(&self, h: &mut H) {
468         self.parsed.hash(h);
469     }
470 }
471
472 /// A single component of a path.
473 ///
474 /// A `Component` roughly corresponds to a substring between path separators
475 /// (`/` or `\`).
476 ///
477 /// This `enum` is created by iterating over [`Components`], which in turn is
478 /// created by the [`components`][`Path::components`] method on [`Path`].
479 ///
480 /// # Examples
481 ///
482 /// ```rust
483 /// use std::path::{Component, Path};
484 ///
485 /// let path = Path::new("/tmp/foo/bar.txt");
486 /// let components = path.components().collect::<Vec<_>>();
487 /// assert_eq!(&components, &[
488 ///     Component::RootDir,
489 ///     Component::Normal("tmp".as_ref()),
490 ///     Component::Normal("foo".as_ref()),
491 ///     Component::Normal("bar.txt".as_ref()),
492 /// ]);
493 /// ```
494 ///
495 /// [`Components`]: struct.Components.html
496 /// [`Path`]: struct.Path.html
497 /// [`Path::components`]: struct.Path.html#method.components
498 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub enum Component<'a> {
501     /// A Windows path prefix, e.g., `C:` or `\\server\share`.
502     ///
503     /// There is a large variety of prefix types, see [`Prefix`]'s documentation
504     /// for more.
505     ///
506     /// Does not occur on Unix.
507     ///
508     /// [`Prefix`]: enum.Prefix.html
509     #[stable(feature = "rust1", since = "1.0.0")]
510     Prefix(
511         #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
512     ),
513
514     /// The root directory component, appears after any prefix and before anything else.
515     ///
516     /// It represents a separator that designates that a path starts from root.
517     #[stable(feature = "rust1", since = "1.0.0")]
518     RootDir,
519
520     /// A reference to the current directory, i.e., `.`.
521     #[stable(feature = "rust1", since = "1.0.0")]
522     CurDir,
523
524     /// A reference to the parent directory, i.e., `..`.
525     #[stable(feature = "rust1", since = "1.0.0")]
526     ParentDir,
527
528     /// A normal component, e.g., `a` and `b` in `a/b`.
529     ///
530     /// This variant is the most common one, it represents references to files
531     /// or directories.
532     #[stable(feature = "rust1", since = "1.0.0")]
533     Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
534 }
535
536 impl<'a> Component<'a> {
537     /// Extracts the underlying [`OsStr`] slice.
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// use std::path::Path;
543     ///
544     /// let path = Path::new("./tmp/foo/bar.txt");
545     /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
546     /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
547     /// ```
548     ///
549     /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
550     #[stable(feature = "rust1", since = "1.0.0")]
551     pub fn as_os_str(self) -> &'a OsStr {
552         match self {
553             Component::Prefix(p) => p.as_os_str(),
554             Component::RootDir => OsStr::new(MAIN_SEP_STR),
555             Component::CurDir => OsStr::new("."),
556             Component::ParentDir => OsStr::new(".."),
557             Component::Normal(path) => path,
558         }
559     }
560 }
561
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl AsRef<OsStr> for Component<'_> {
564     fn as_ref(&self) -> &OsStr {
565         self.as_os_str()
566     }
567 }
568
569 #[stable(feature = "path_component_asref", since = "1.25.0")]
570 impl AsRef<Path> for Component<'_> {
571     fn as_ref(&self) -> &Path {
572         self.as_os_str().as_ref()
573     }
574 }
575
576 /// An iterator over the [`Component`]s of a [`Path`].
577 ///
578 /// This `struct` is created by the [`components`] method on [`Path`].
579 /// See its documentation for more.
580 ///
581 /// # Examples
582 ///
583 /// ```
584 /// use std::path::Path;
585 ///
586 /// let path = Path::new("/tmp/foo/bar.txt");
587 ///
588 /// for component in path.components() {
589 ///     println!("{:?}", component);
590 /// }
591 /// ```
592 ///
593 /// [`Component`]: enum.Component.html
594 /// [`components`]: struct.Path.html#method.components
595 /// [`Path`]: struct.Path.html
596 #[derive(Clone)]
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub struct Components<'a> {
599     // The path left to parse components from
600     path: &'a [u8],
601
602     // The prefix as it was originally parsed, if any
603     prefix: Option<Prefix<'a>>,
604
605     // true if path *physically* has a root separator; for most Windows
606     // prefixes, it may have a "logical" rootseparator for the purposes of
607     // normalization, e.g.,  \\server\share == \\server\share\.
608     has_physical_root: bool,
609
610     // The iterator is double-ended, and these two states keep track of what has
611     // been produced from either end
612     front: State,
613     back: State,
614 }
615
616 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
617 ///
618 /// This `struct` is created by the [`iter`] method on [`Path`].
619 /// See its documentation for more.
620 ///
621 /// [`Component`]: enum.Component.html
622 /// [`iter`]: struct.Path.html#method.iter
623 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
624 /// [`Path`]: struct.Path.html
625 #[derive(Clone)]
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub struct Iter<'a> {
628     inner: Components<'a>,
629 }
630
631 #[stable(feature = "path_components_debug", since = "1.13.0")]
632 impl fmt::Debug for Components<'_> {
633     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
634         struct DebugHelper<'a>(&'a Path);
635
636         impl fmt::Debug for DebugHelper<'_> {
637             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
638                 f.debug_list()
639                     .entries(self.0.components())
640                     .finish()
641             }
642         }
643
644         f.debug_tuple("Components")
645             .field(&DebugHelper(self.as_path()))
646             .finish()
647     }
648 }
649
650 impl<'a> Components<'a> {
651     // how long is the prefix, if any?
652     #[inline]
653     fn prefix_len(&self) -> usize {
654         self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
655     }
656
657     #[inline]
658     fn prefix_verbatim(&self) -> bool {
659         self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
660     }
661
662     /// how much of the prefix is left from the point of view of iteration?
663     #[inline]
664     fn prefix_remaining(&self) -> usize {
665         if self.front == State::Prefix {
666             self.prefix_len()
667         } else {
668             0
669         }
670     }
671
672     // Given the iteration so far, how much of the pre-State::Body path is left?
673     #[inline]
674     fn len_before_body(&self) -> usize {
675         let root = if self.front <= State::StartDir && self.has_physical_root {
676             1
677         } else {
678             0
679         };
680         let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
681             1
682         } else {
683             0
684         };
685         self.prefix_remaining() + root + cur_dir
686     }
687
688     // is the iteration complete?
689     #[inline]
690     fn finished(&self) -> bool {
691         self.front == State::Done || self.back == State::Done || self.front > self.back
692     }
693
694     #[inline]
695     fn is_sep_byte(&self, b: u8) -> bool {
696         if self.prefix_verbatim() {
697             is_verbatim_sep(b)
698         } else {
699             is_sep_byte(b)
700         }
701     }
702
703     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
704     ///
705     /// # Examples
706     ///
707     /// ```
708     /// use std::path::Path;
709     ///
710     /// let mut components = Path::new("/tmp/foo/bar.txt").components();
711     /// components.next();
712     /// components.next();
713     ///
714     /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
715     /// ```
716     #[stable(feature = "rust1", since = "1.0.0")]
717     pub fn as_path(&self) -> &'a Path {
718         let mut comps = self.clone();
719         if comps.front == State::Body {
720             comps.trim_left();
721         }
722         if comps.back == State::Body {
723             comps.trim_right();
724         }
725         unsafe { Path::from_u8_slice(comps.path) }
726     }
727
728     /// Is the *original* path rooted?
729     fn has_root(&self) -> bool {
730         if self.has_physical_root {
731             return true;
732         }
733         if let Some(p) = self.prefix {
734             if p.has_implicit_root() {
735                 return true;
736             }
737         }
738         false
739     }
740
741     /// Should the normalized path include a leading . ?
742     fn include_cur_dir(&self) -> bool {
743         if self.has_root() {
744             return false;
745         }
746         let mut iter = self.path[self.prefix_len()..].iter();
747         match (iter.next(), iter.next()) {
748             (Some(&b'.'), None) => true,
749             (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
750             _ => false,
751         }
752     }
753
754     // parse a given byte sequence into the corresponding path component
755     fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
756         match comp {
757             b"." if self.prefix_verbatim() => Some(Component::CurDir),
758             b"." => None, // . components are normalized away, except at
759                           // the beginning of a path, which is treated
760                           // separately via `include_cur_dir`
761             b".." => Some(Component::ParentDir),
762             b"" => None,
763             _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
764         }
765     }
766
767     // parse a component from the left, saying how many bytes to consume to
768     // remove the component
769     fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
770         debug_assert!(self.front == State::Body);
771         let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
772             None => (0, self.path),
773             Some(i) => (1, &self.path[..i]),
774         };
775         (comp.len() + extra, self.parse_single_component(comp))
776     }
777
778     // parse a component from the right, saying how many bytes to consume to
779     // remove the component
780     fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
781         debug_assert!(self.back == State::Body);
782         let start = self.len_before_body();
783         let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
784             None => (0, &self.path[start..]),
785             Some(i) => (1, &self.path[start + i + 1..]),
786         };
787         (comp.len() + extra, self.parse_single_component(comp))
788     }
789
790     // trim away repeated separators (i.e., empty components) on the left
791     fn trim_left(&mut self) {
792         while !self.path.is_empty() {
793             let (size, comp) = self.parse_next_component();
794             if comp.is_some() {
795                 return;
796             } else {
797                 self.path = &self.path[size..];
798             }
799         }
800     }
801
802     // trim away repeated separators (i.e., empty components) on the right
803     fn trim_right(&mut self) {
804         while self.path.len() > self.len_before_body() {
805             let (size, comp) = self.parse_next_component_back();
806             if comp.is_some() {
807                 return;
808             } else {
809                 self.path = &self.path[..self.path.len() - size];
810             }
811         }
812     }
813 }
814
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl AsRef<Path> for Components<'_> {
817     fn as_ref(&self) -> &Path {
818         self.as_path()
819     }
820 }
821
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl AsRef<OsStr> for Components<'_> {
824     fn as_ref(&self) -> &OsStr {
825         self.as_path().as_os_str()
826     }
827 }
828
829 #[stable(feature = "path_iter_debug", since = "1.13.0")]
830 impl fmt::Debug for Iter<'_> {
831     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
832         struct DebugHelper<'a>(&'a Path);
833
834         impl fmt::Debug for DebugHelper<'_> {
835             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
836                 f.debug_list()
837                     .entries(self.0.iter())
838                     .finish()
839             }
840         }
841
842         f.debug_tuple("Iter")
843             .field(&DebugHelper(self.as_path()))
844             .finish()
845     }
846 }
847
848 impl<'a> Iter<'a> {
849     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
850     ///
851     /// # Examples
852     ///
853     /// ```
854     /// use std::path::Path;
855     ///
856     /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
857     /// iter.next();
858     /// iter.next();
859     ///
860     /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
861     /// ```
862     #[stable(feature = "rust1", since = "1.0.0")]
863     pub fn as_path(&self) -> &'a Path {
864         self.inner.as_path()
865     }
866 }
867
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl AsRef<Path> for Iter<'_> {
870     fn as_ref(&self) -> &Path {
871         self.as_path()
872     }
873 }
874
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl AsRef<OsStr> for Iter<'_> {
877     fn as_ref(&self) -> &OsStr {
878         self.as_path().as_os_str()
879     }
880 }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<'a> Iterator for Iter<'a> {
884     type Item = &'a OsStr;
885
886     fn next(&mut self) -> Option<&'a OsStr> {
887         self.inner.next().map(Component::as_os_str)
888     }
889 }
890
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<'a> DoubleEndedIterator for Iter<'a> {
893     fn next_back(&mut self) -> Option<&'a OsStr> {
894         self.inner.next_back().map(Component::as_os_str)
895     }
896 }
897
898 #[stable(feature = "fused", since = "1.26.0")]
899 impl FusedIterator for Iter<'_> {}
900
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> Iterator for Components<'a> {
903     type Item = Component<'a>;
904
905     fn next(&mut self) -> Option<Component<'a>> {
906         while !self.finished() {
907             match self.front {
908                 State::Prefix if self.prefix_len() > 0 => {
909                     self.front = State::StartDir;
910                     debug_assert!(self.prefix_len() <= self.path.len());
911                     let raw = &self.path[..self.prefix_len()];
912                     self.path = &self.path[self.prefix_len()..];
913                     return Some(Component::Prefix(PrefixComponent {
914                         raw: unsafe { u8_slice_as_os_str(raw) },
915                         parsed: self.prefix.unwrap(),
916                     }));
917                 }
918                 State::Prefix => {
919                     self.front = State::StartDir;
920                 }
921                 State::StartDir => {
922                     self.front = State::Body;
923                     if self.has_physical_root {
924                         debug_assert!(!self.path.is_empty());
925                         self.path = &self.path[1..];
926                         return Some(Component::RootDir);
927                     } else if let Some(p) = self.prefix {
928                         if p.has_implicit_root() && !p.is_verbatim() {
929                             return Some(Component::RootDir);
930                         }
931                     } else if self.include_cur_dir() {
932                         debug_assert!(!self.path.is_empty());
933                         self.path = &self.path[1..];
934                         return Some(Component::CurDir);
935                     }
936                 }
937                 State::Body if !self.path.is_empty() => {
938                     let (size, comp) = self.parse_next_component();
939                     self.path = &self.path[size..];
940                     if comp.is_some() {
941                         return comp;
942                     }
943                 }
944                 State::Body => {
945                     self.front = State::Done;
946                 }
947                 State::Done => unreachable!(),
948             }
949         }
950         None
951     }
952 }
953
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl<'a> DoubleEndedIterator for Components<'a> {
956     fn next_back(&mut self) -> Option<Component<'a>> {
957         while !self.finished() {
958             match self.back {
959                 State::Body if self.path.len() > self.len_before_body() => {
960                     let (size, comp) = self.parse_next_component_back();
961                     self.path = &self.path[..self.path.len() - size];
962                     if comp.is_some() {
963                         return comp;
964                     }
965                 }
966                 State::Body => {
967                     self.back = State::StartDir;
968                 }
969                 State::StartDir => {
970                     self.back = State::Prefix;
971                     if self.has_physical_root {
972                         self.path = &self.path[..self.path.len() - 1];
973                         return Some(Component::RootDir);
974                     } else if let Some(p) = self.prefix {
975                         if p.has_implicit_root() && !p.is_verbatim() {
976                             return Some(Component::RootDir);
977                         }
978                     } else if self.include_cur_dir() {
979                         self.path = &self.path[..self.path.len() - 1];
980                         return Some(Component::CurDir);
981                     }
982                 }
983                 State::Prefix if self.prefix_len() > 0 => {
984                     self.back = State::Done;
985                     return Some(Component::Prefix(PrefixComponent {
986                         raw: unsafe { u8_slice_as_os_str(self.path) },
987                         parsed: self.prefix.unwrap(),
988                     }));
989                 }
990                 State::Prefix => {
991                     self.back = State::Done;
992                     return None;
993                 }
994                 State::Done => unreachable!(),
995             }
996         }
997         None
998     }
999 }
1000
1001 #[stable(feature = "fused", since = "1.26.0")]
1002 impl FusedIterator for Components<'_> {}
1003
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<'a> cmp::PartialEq for Components<'a> {
1006     fn eq(&self, other: &Components<'a>) -> bool {
1007         Iterator::eq(self.clone(), other.clone())
1008     }
1009 }
1010
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl cmp::Eq for Components<'_> {}
1013
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<'a> cmp::PartialOrd for Components<'a> {
1016     fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1017         Iterator::partial_cmp(self.clone(), other.clone())
1018     }
1019 }
1020
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl cmp::Ord for Components<'_> {
1023     fn cmp(&self, other: &Self) -> cmp::Ordering {
1024         Iterator::cmp(self.clone(), other.clone())
1025     }
1026 }
1027
1028 /// An iterator over [`Path`] and its ancestors.
1029 ///
1030 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1031 /// See its documentation for more.
1032 ///
1033 /// # Examples
1034 ///
1035 /// ```
1036 /// use std::path::Path;
1037 ///
1038 /// let path = Path::new("/foo/bar");
1039 ///
1040 /// for ancestor in path.ancestors() {
1041 ///     println!("{}", ancestor.display());
1042 /// }
1043 /// ```
1044 ///
1045 /// [`ancestors`]: struct.Path.html#method.ancestors
1046 /// [`Path`]: struct.Path.html
1047 #[derive(Copy, Clone, Debug)]
1048 #[stable(feature = "path_ancestors", since = "1.28.0")]
1049 pub struct Ancestors<'a> {
1050     next: Option<&'a Path>,
1051 }
1052
1053 #[stable(feature = "path_ancestors", since = "1.28.0")]
1054 impl<'a> Iterator for Ancestors<'a> {
1055     type Item = &'a Path;
1056
1057     fn next(&mut self) -> Option<Self::Item> {
1058         let next = self.next;
1059         self.next = next.and_then(Path::parent);
1060         next
1061     }
1062 }
1063
1064 #[stable(feature = "path_ancestors", since = "1.28.0")]
1065 impl FusedIterator for Ancestors<'_> {}
1066
1067 ////////////////////////////////////////////////////////////////////////////////
1068 // Basic types and traits
1069 ////////////////////////////////////////////////////////////////////////////////
1070
1071 /// An owned, mutable path (akin to [`String`]).
1072 ///
1073 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1074 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1075 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1076 ///
1077 /// [`String`]: ../string/struct.String.html
1078 /// [`Path`]: struct.Path.html
1079 /// [`push`]: struct.PathBuf.html#method.push
1080 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1081 /// [`Deref`]: ../ops/trait.Deref.html
1082 ///
1083 /// More details about the overall approach can be found in
1084 /// the [module documentation](index.html).
1085 ///
1086 /// # Examples
1087 ///
1088 /// You can use [`push`] to build up a `PathBuf` from
1089 /// components:
1090 ///
1091 /// ```
1092 /// use std::path::PathBuf;
1093 ///
1094 /// let mut path = PathBuf::new();
1095 ///
1096 /// path.push(r"C:\");
1097 /// path.push("windows");
1098 /// path.push("system32");
1099 ///
1100 /// path.set_extension("dll");
1101 /// ```
1102 ///
1103 /// However, [`push`] is best used for dynamic situations. This is a better way
1104 /// to do this when you know all of the components ahead of time:
1105 ///
1106 /// ```
1107 /// use std::path::PathBuf;
1108 ///
1109 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1110 /// ```
1111 ///
1112 /// We can still do better than this! Since these are all strings, we can use
1113 /// `From::from`:
1114 ///
1115 /// ```
1116 /// use std::path::PathBuf;
1117 ///
1118 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1119 /// ```
1120 ///
1121 /// Which method works best depends on what kind of situation you're in.
1122 #[derive(Clone)]
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub struct PathBuf {
1125     inner: OsString,
1126 }
1127
1128 impl PathBuf {
1129     fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1130         unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1131     }
1132
1133     /// Allocates an empty `PathBuf`.
1134     ///
1135     /// # Examples
1136     ///
1137     /// ```
1138     /// use std::path::PathBuf;
1139     ///
1140     /// let path = PathBuf::new();
1141     /// ```
1142     #[stable(feature = "rust1", since = "1.0.0")]
1143     pub fn new() -> PathBuf {
1144         PathBuf { inner: OsString::new() }
1145     }
1146
1147     /// Creates a new `PathBuf` with a given capacity used to create the
1148     /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1149     ///
1150     /// # Examples
1151     ///
1152     /// ```
1153     /// #![feature(path_buf_capacity)]
1154     /// use std::path::PathBuf;
1155     ///
1156     /// let mut path = PathBuf::with_capacity(10);
1157     /// let capacity = path.capacity();
1158     ///
1159     /// // This push is done without reallocating
1160     /// path.push(r"C:\");
1161     ///
1162     /// assert_eq!(capacity, path.capacity());
1163     /// ```
1164     ///
1165     /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1166     /// [`OsString`]: ../ffi/struct.OsString.html
1167     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1168     pub fn with_capacity(capacity: usize) -> PathBuf {
1169         PathBuf {
1170             inner: OsString::with_capacity(capacity)
1171         }
1172     }
1173
1174     /// Coerces to a [`Path`] slice.
1175     ///
1176     /// [`Path`]: struct.Path.html
1177     ///
1178     /// # Examples
1179     ///
1180     /// ```
1181     /// use std::path::{Path, PathBuf};
1182     ///
1183     /// let p = PathBuf::from("/test");
1184     /// assert_eq!(Path::new("/test"), p.as_path());
1185     /// ```
1186     #[stable(feature = "rust1", since = "1.0.0")]
1187     pub fn as_path(&self) -> &Path {
1188         self
1189     }
1190
1191     /// Extends `self` with `path`.
1192     ///
1193     /// If `path` is absolute, it replaces the current path.
1194     ///
1195     /// On Windows:
1196     ///
1197     /// * if `path` has a root but no prefix (e.g., `\windows`), it
1198     ///   replaces everything except for the prefix (if any) of `self`.
1199     /// * if `path` has a prefix but no root, it replaces `self`.
1200     ///
1201     /// # Examples
1202     ///
1203     /// Pushing a relative path extends the existing path:
1204     ///
1205     /// ```
1206     /// use std::path::PathBuf;
1207     ///
1208     /// let mut path = PathBuf::from("/tmp");
1209     /// path.push("file.bk");
1210     /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1211     /// ```
1212     ///
1213     /// Pushing an absolute path replaces the existing path:
1214     ///
1215     /// ```
1216     /// use std::path::PathBuf;
1217     ///
1218     /// let mut path = PathBuf::from("/tmp");
1219     /// path.push("/etc");
1220     /// assert_eq!(path, PathBuf::from("/etc"));
1221     /// ```
1222     #[stable(feature = "rust1", since = "1.0.0")]
1223     pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1224         self._push(path.as_ref())
1225     }
1226
1227     fn _push(&mut self, path: &Path) {
1228         // in general, a separator is needed if the rightmost byte is not a separator
1229         let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1230
1231         // in the special case of `C:` on Windows, do *not* add a separator
1232         {
1233             let comps = self.components();
1234             if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1235                comps.prefix.unwrap().is_drive() {
1236                 need_sep = false
1237             }
1238         }
1239
1240         // absolute `path` replaces `self`
1241         if path.is_absolute() || path.prefix().is_some() {
1242             self.as_mut_vec().truncate(0);
1243
1244         // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1245         } else if path.has_root() {
1246             let prefix_len = self.components().prefix_remaining();
1247             self.as_mut_vec().truncate(prefix_len);
1248
1249         // `path` is a pure relative path
1250         } else if need_sep {
1251             self.inner.push(MAIN_SEP_STR);
1252         }
1253
1254         self.inner.push(path);
1255     }
1256
1257     /// Truncates `self` to [`self.parent`].
1258     ///
1259     /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1260     /// Otherwise, returns `true`.
1261     ///
1262     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1263     /// [`self.parent`]: struct.PathBuf.html#method.parent
1264     ///
1265     /// # Examples
1266     ///
1267     /// ```
1268     /// use std::path::{Path, PathBuf};
1269     ///
1270     /// let mut p = PathBuf::from("/test/test.rs");
1271     ///
1272     /// p.pop();
1273     /// assert_eq!(Path::new("/test"), p);
1274     /// p.pop();
1275     /// assert_eq!(Path::new("/"), p);
1276     /// ```
1277     #[stable(feature = "rust1", since = "1.0.0")]
1278     pub fn pop(&mut self) -> bool {
1279         match self.parent().map(|p| p.as_u8_slice().len()) {
1280             Some(len) => {
1281                 self.as_mut_vec().truncate(len);
1282                 true
1283             }
1284             None => false,
1285         }
1286     }
1287
1288     /// Updates [`self.file_name`] to `file_name`.
1289     ///
1290     /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1291     /// `file_name`.
1292     ///
1293     /// Otherwise it is equivalent to calling [`pop`] and then pushing
1294     /// `file_name`. The new path will be a sibling of the original path.
1295     /// (That is, it will have the same parent.)
1296     ///
1297     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1298     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1299     /// [`pop`]: struct.PathBuf.html#method.pop
1300     ///
1301     /// # Examples
1302     ///
1303     /// ```
1304     /// use std::path::PathBuf;
1305     ///
1306     /// let mut buf = PathBuf::from("/");
1307     /// assert!(buf.file_name() == None);
1308     /// buf.set_file_name("bar");
1309     /// assert!(buf == PathBuf::from("/bar"));
1310     /// assert!(buf.file_name().is_some());
1311     /// buf.set_file_name("baz.txt");
1312     /// assert!(buf == PathBuf::from("/baz.txt"));
1313     /// ```
1314     #[stable(feature = "rust1", since = "1.0.0")]
1315     pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1316         self._set_file_name(file_name.as_ref())
1317     }
1318
1319     fn _set_file_name(&mut self, file_name: &OsStr) {
1320         if self.file_name().is_some() {
1321             let popped = self.pop();
1322             debug_assert!(popped);
1323         }
1324         self.push(file_name);
1325     }
1326
1327     /// Updates [`self.extension`] to `extension`.
1328     ///
1329     /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1330     /// returns `true` and updates the extension otherwise.
1331     ///
1332     /// If [`self.extension`] is [`None`], the extension is added; otherwise
1333     /// it is replaced.
1334     ///
1335     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1336     /// [`self.extension`]: struct.PathBuf.html#method.extension
1337     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1338     ///
1339     /// # Examples
1340     ///
1341     /// ```
1342     /// use std::path::{Path, PathBuf};
1343     ///
1344     /// let mut p = PathBuf::from("/feel/the");
1345     ///
1346     /// p.set_extension("force");
1347     /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1348     ///
1349     /// p.set_extension("dark_side");
1350     /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1351     /// ```
1352     #[stable(feature = "rust1", since = "1.0.0")]
1353     pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1354         self._set_extension(extension.as_ref())
1355     }
1356
1357     fn _set_extension(&mut self, extension: &OsStr) -> bool {
1358         if self.file_name().is_none() {
1359             return false;
1360         }
1361
1362         let mut stem = match self.file_stem() {
1363             Some(stem) => stem.to_os_string(),
1364             None => OsString::new(),
1365         };
1366
1367         if !os_str_as_u8_slice(extension).is_empty() {
1368             stem.push(".");
1369             stem.push(extension);
1370         }
1371         self.set_file_name(&stem);
1372
1373         true
1374     }
1375
1376     /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1377     ///
1378     /// [`OsString`]: ../ffi/struct.OsString.html
1379     ///
1380     /// # Examples
1381     ///
1382     /// ```
1383     /// use std::path::PathBuf;
1384     ///
1385     /// let p = PathBuf::from("/the/head");
1386     /// let os_str = p.into_os_string();
1387     /// ```
1388     #[stable(feature = "rust1", since = "1.0.0")]
1389     pub fn into_os_string(self) -> OsString {
1390         self.inner
1391     }
1392
1393     /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1394     ///
1395     /// [`Box`]: ../../std/boxed/struct.Box.html
1396     /// [`Path`]: struct.Path.html
1397     #[stable(feature = "into_boxed_path", since = "1.20.0")]
1398     pub fn into_boxed_path(self) -> Box<Path> {
1399         let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1400         unsafe { Box::from_raw(rw) }
1401     }
1402
1403     /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1404     ///
1405     /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1406     /// [`OsString`]: ../ffi/struct.OsString.html
1407     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1408     pub fn capacity(&self) -> usize {
1409         self.inner.capacity()
1410     }
1411
1412     /// Invokes [`clear`] on the underlying instance of [`OsString`].
1413     ///
1414     /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1415     /// [`OsString`]: ../ffi/struct.OsString.html
1416     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1417     pub fn clear(&mut self) {
1418         self.inner.clear()
1419     }
1420
1421     /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1422     ///
1423     /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1424     /// [`OsString`]: ../ffi/struct.OsString.html
1425     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1426     pub fn reserve(&mut self, additional: usize) {
1427         self.inner.reserve(additional)
1428     }
1429
1430     /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1431     ///
1432     /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1433     /// [`OsString`]: ../ffi/struct.OsString.html
1434     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1435     pub fn reserve_exact(&mut self, additional: usize) {
1436         self.inner.reserve_exact(additional)
1437     }
1438
1439     /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1440     ///
1441     /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1442     /// [`OsString`]: ../ffi/struct.OsString.html
1443     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1444     pub fn shrink_to_fit(&mut self) {
1445         self.inner.shrink_to_fit()
1446     }
1447
1448     /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1449     ///
1450     /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1451     /// [`OsString`]: ../ffi/struct.OsString.html
1452     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1453     pub fn shrink_to(&mut self, min_capacity: usize) {
1454         self.inner.shrink_to(min_capacity)
1455     }
1456 }
1457
1458 #[stable(feature = "box_from_path", since = "1.17.0")]
1459 impl From<&Path> for Box<Path> {
1460     fn from(path: &Path) -> Box<Path> {
1461         let boxed: Box<OsStr> = path.inner.into();
1462         let rw = Box::into_raw(boxed) as *mut Path;
1463         unsafe { Box::from_raw(rw) }
1464     }
1465 }
1466
1467 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1468 impl From<Box<Path>> for PathBuf {
1469     /// Converts a `Box<Path>` into a `PathBuf`
1470     ///
1471     /// This conversion does not allocate or copy memory.
1472     fn from(boxed: Box<Path>) -> PathBuf {
1473         boxed.into_path_buf()
1474     }
1475 }
1476
1477 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1478 impl From<PathBuf> for Box<Path> {
1479     /// Converts a `PathBuf` into a `Box<Path>`
1480     ///
1481     /// This conversion currently should not allocate memory,
1482     /// but this behavior is not guaranteed on all platforms or in all future versions.
1483     fn from(p: PathBuf) -> Box<Path> {
1484         p.into_boxed_path()
1485     }
1486 }
1487
1488 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1489 impl Clone for Box<Path> {
1490     #[inline]
1491     fn clone(&self) -> Self {
1492         self.to_path_buf().into_boxed_path()
1493     }
1494 }
1495
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1498     fn from(s: &T) -> PathBuf {
1499         PathBuf::from(s.as_ref().to_os_string())
1500     }
1501 }
1502
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl From<OsString> for PathBuf {
1505     /// Converts a `OsString` into a `PathBuf`
1506     ///
1507     /// This conversion does not allocate or copy memory.
1508     fn from(s: OsString) -> PathBuf {
1509         PathBuf { inner: s }
1510     }
1511 }
1512
1513 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1514 impl From<PathBuf> for OsString {
1515     /// Converts a `PathBuf` into a `OsString`
1516     ///
1517     /// This conversion does not allocate or copy memory.
1518     fn from(path_buf : PathBuf) -> OsString {
1519         path_buf.inner
1520     }
1521 }
1522
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl From<String> for PathBuf {
1525     /// Converts a `String` into a `PathBuf`
1526     ///
1527     /// This conversion does not allocate or copy memory.
1528     fn from(s: String) -> PathBuf {
1529         PathBuf::from(OsString::from(s))
1530     }
1531 }
1532
1533 #[stable(feature = "path_from_str", since = "1.32.0")]
1534 impl FromStr for PathBuf {
1535     type Err = core::convert::Infallible;
1536
1537     fn from_str(s: &str) -> Result<Self, Self::Err> {
1538         Ok(PathBuf::from(s))
1539     }
1540 }
1541
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1544     fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1545         let mut buf = PathBuf::new();
1546         buf.extend(iter);
1547         buf
1548     }
1549 }
1550
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1553     fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1554         for p in iter {
1555             self.push(p.as_ref())
1556         }
1557     }
1558 }
1559
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl fmt::Debug for PathBuf {
1562     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1563         fmt::Debug::fmt(&**self, formatter)
1564     }
1565 }
1566
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl ops::Deref for PathBuf {
1569     type Target = Path;
1570
1571     fn deref(&self) -> &Path {
1572         Path::new(&self.inner)
1573     }
1574 }
1575
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl Borrow<Path> for PathBuf {
1578     fn borrow(&self) -> &Path {
1579         self.deref()
1580     }
1581 }
1582
1583 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1584 impl Default for PathBuf {
1585     fn default() -> Self {
1586         PathBuf::new()
1587     }
1588 }
1589
1590 #[stable(feature = "cow_from_path", since = "1.6.0")]
1591 impl<'a> From<&'a Path> for Cow<'a, Path> {
1592     #[inline]
1593     fn from(s: &'a Path) -> Cow<'a, Path> {
1594         Cow::Borrowed(s)
1595     }
1596 }
1597
1598 #[stable(feature = "cow_from_path", since = "1.6.0")]
1599 impl<'a> From<PathBuf> for Cow<'a, Path> {
1600     #[inline]
1601     fn from(s: PathBuf) -> Cow<'a, Path> {
1602         Cow::Owned(s)
1603     }
1604 }
1605
1606 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1607 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1608     #[inline]
1609     fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1610         Cow::Borrowed(p.as_path())
1611     }
1612 }
1613
1614 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1615 impl<'a> From<Cow<'a, Path>> for PathBuf {
1616     #[inline]
1617     fn from(p: Cow<'a, Path>) -> Self {
1618         p.into_owned()
1619     }
1620 }
1621
1622 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1623 impl From<PathBuf> for Arc<Path> {
1624     /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1625     #[inline]
1626     fn from(s: PathBuf) -> Arc<Path> {
1627         let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1628         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1629     }
1630 }
1631
1632 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1633 impl From<&Path> for Arc<Path> {
1634     /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1635     #[inline]
1636     fn from(s: &Path) -> Arc<Path> {
1637         let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1638         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1639     }
1640 }
1641
1642 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1643 impl From<PathBuf> for Rc<Path> {
1644     /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1645     #[inline]
1646     fn from(s: PathBuf) -> Rc<Path> {
1647         let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1648         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1649     }
1650 }
1651
1652 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1653 impl From<&Path> for Rc<Path> {
1654     /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1655     #[inline]
1656     fn from(s: &Path) -> Rc<Path> {
1657         let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1658         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1659     }
1660 }
1661
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl ToOwned for Path {
1664     type Owned = PathBuf;
1665     fn to_owned(&self) -> PathBuf {
1666         self.to_path_buf()
1667     }
1668     fn clone_into(&self, target: &mut PathBuf) {
1669         self.inner.clone_into(&mut target.inner);
1670     }
1671 }
1672
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl cmp::PartialEq for PathBuf {
1675     fn eq(&self, other: &PathBuf) -> bool {
1676         self.components() == other.components()
1677     }
1678 }
1679
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl Hash for PathBuf {
1682     fn hash<H: Hasher>(&self, h: &mut H) {
1683         self.as_path().hash(h)
1684     }
1685 }
1686
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl cmp::Eq for PathBuf {}
1689
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl cmp::PartialOrd for PathBuf {
1692     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1693         self.components().partial_cmp(other.components())
1694     }
1695 }
1696
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl cmp::Ord for PathBuf {
1699     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1700         self.components().cmp(other.components())
1701     }
1702 }
1703
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 impl AsRef<OsStr> for PathBuf {
1706     fn as_ref(&self) -> &OsStr {
1707         &self.inner[..]
1708     }
1709 }
1710
1711 /// A slice of a path (akin to [`str`]).
1712 ///
1713 /// This type supports a number of operations for inspecting a path, including
1714 /// breaking the path into its components (separated by `/` on Unix and by either
1715 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1716 /// is absolute, and so on.
1717 ///
1718 /// This is an *unsized* type, meaning that it must always be used behind a
1719 /// pointer like `&` or [`Box`]. For an owned version of this type,
1720 /// see [`PathBuf`].
1721 ///
1722 /// [`str`]: ../primitive.str.html
1723 /// [`Box`]: ../boxed/struct.Box.html
1724 /// [`PathBuf`]: struct.PathBuf.html
1725 ///
1726 /// More details about the overall approach can be found in
1727 /// the [module documentation](index.html).
1728 ///
1729 /// # Examples
1730 ///
1731 /// ```
1732 /// use std::path::Path;
1733 /// use std::ffi::OsStr;
1734 ///
1735 /// // Note: this example does work on Windows
1736 /// let path = Path::new("./foo/bar.txt");
1737 ///
1738 /// let parent = path.parent();
1739 /// assert_eq!(parent, Some(Path::new("./foo")));
1740 ///
1741 /// let file_stem = path.file_stem();
1742 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1743 ///
1744 /// let extension = path.extension();
1745 /// assert_eq!(extension, Some(OsStr::new("txt")));
1746 /// ```
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 pub struct Path {
1749     inner: OsStr,
1750 }
1751
1752 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1753 /// was not found.
1754 ///
1755 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1756 /// See its documentation for more.
1757 ///
1758 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1759 /// [`Path`]: struct.Path.html
1760 #[derive(Debug, Clone, PartialEq, Eq)]
1761 #[stable(since = "1.7.0", feature = "strip_prefix")]
1762 pub struct StripPrefixError(());
1763
1764 impl Path {
1765     // The following (private!) function allows construction of a path from a u8
1766     // slice, which is only safe when it is known to follow the OsStr encoding.
1767     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1768         Path::new(u8_slice_as_os_str(s))
1769     }
1770     // The following (private!) function reveals the byte encoding used for OsStr.
1771     fn as_u8_slice(&self) -> &[u8] {
1772         os_str_as_u8_slice(&self.inner)
1773     }
1774
1775     /// Directly wraps a string slice as a `Path` slice.
1776     ///
1777     /// This is a cost-free conversion.
1778     ///
1779     /// # Examples
1780     ///
1781     /// ```
1782     /// use std::path::Path;
1783     ///
1784     /// Path::new("foo.txt");
1785     /// ```
1786     ///
1787     /// You can create `Path`s from `String`s, or even other `Path`s:
1788     ///
1789     /// ```
1790     /// use std::path::Path;
1791     ///
1792     /// let string = String::from("foo.txt");
1793     /// let from_string = Path::new(&string);
1794     /// let from_path = Path::new(&from_string);
1795     /// assert_eq!(from_string, from_path);
1796     /// ```
1797     #[stable(feature = "rust1", since = "1.0.0")]
1798     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1799         unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1800     }
1801
1802     /// Yields the underlying [`OsStr`] slice.
1803     ///
1804     /// [`OsStr`]: ../ffi/struct.OsStr.html
1805     ///
1806     /// # Examples
1807     ///
1808     /// ```
1809     /// use std::path::Path;
1810     ///
1811     /// let os_str = Path::new("foo.txt").as_os_str();
1812     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1813     /// ```
1814     #[stable(feature = "rust1", since = "1.0.0")]
1815     pub fn as_os_str(&self) -> &OsStr {
1816         &self.inner
1817     }
1818
1819     /// Yields a [`&str`] slice if the `Path` is valid unicode.
1820     ///
1821     /// This conversion may entail doing a check for UTF-8 validity.
1822     ///
1823     /// [`&str`]: ../primitive.str.html
1824     ///
1825     /// # Examples
1826     ///
1827     /// ```
1828     /// use std::path::Path;
1829     ///
1830     /// let path = Path::new("foo.txt");
1831     /// assert_eq!(path.to_str(), Some("foo.txt"));
1832     /// ```
1833     #[stable(feature = "rust1", since = "1.0.0")]
1834     pub fn to_str(&self) -> Option<&str> {
1835         self.inner.to_str()
1836     }
1837
1838     /// Converts a `Path` to a [`Cow<str>`].
1839     ///
1840     /// Any non-Unicode sequences are replaced with
1841     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1842     ///
1843     /// [`Cow<str>`]: ../borrow/enum.Cow.html
1844     /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1845     ///
1846     /// # Examples
1847     ///
1848     /// Calling `to_string_lossy` on a `Path` with valid unicode:
1849     ///
1850     /// ```
1851     /// use std::path::Path;
1852     ///
1853     /// let path = Path::new("foo.txt");
1854     /// assert_eq!(path.to_string_lossy(), "foo.txt");
1855     /// ```
1856     ///
1857     /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1858     /// have returned `"fo�.txt"`.
1859     #[stable(feature = "rust1", since = "1.0.0")]
1860     pub fn to_string_lossy(&self) -> Cow<str> {
1861         self.inner.to_string_lossy()
1862     }
1863
1864     /// Converts a `Path` to an owned [`PathBuf`].
1865     ///
1866     /// [`PathBuf`]: struct.PathBuf.html
1867     ///
1868     /// # Examples
1869     ///
1870     /// ```
1871     /// use std::path::Path;
1872     ///
1873     /// let path_buf = Path::new("foo.txt").to_path_buf();
1874     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1875     /// ```
1876     #[rustc_conversion_suggestion]
1877     #[stable(feature = "rust1", since = "1.0.0")]
1878     pub fn to_path_buf(&self) -> PathBuf {
1879         PathBuf::from(self.inner.to_os_string())
1880     }
1881
1882     /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1883     /// the current directory.
1884     ///
1885     /// * On Unix, a path is absolute if it starts with the root, so
1886     /// `is_absolute` and [`has_root`] are equivalent.
1887     ///
1888     /// * On Windows, a path is absolute if it has a prefix and starts with the
1889     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1890     ///
1891     /// # Examples
1892     ///
1893     /// ```
1894     /// use std::path::Path;
1895     ///
1896     /// assert!(!Path::new("foo.txt").is_absolute());
1897     /// ```
1898     ///
1899     /// [`has_root`]: #method.has_root
1900     #[stable(feature = "rust1", since = "1.0.0")]
1901     #[allow(deprecated)]
1902     pub fn is_absolute(&self) -> bool {
1903         if cfg!(target_os = "redox") {
1904             // FIXME: Allow Redox prefixes
1905             self.has_root() || has_redox_scheme(self.as_u8_slice())
1906         } else {
1907             self.has_root() && (cfg!(unix) || self.prefix().is_some())
1908         }
1909     }
1910
1911     /// Returns `true` if the `Path` is relative, i.e., not absolute.
1912     ///
1913     /// See [`is_absolute`]'s documentation for more details.
1914     ///
1915     /// # Examples
1916     ///
1917     /// ```
1918     /// use std::path::Path;
1919     ///
1920     /// assert!(Path::new("foo.txt").is_relative());
1921     /// ```
1922     ///
1923     /// [`is_absolute`]: #method.is_absolute
1924     #[stable(feature = "rust1", since = "1.0.0")]
1925     pub fn is_relative(&self) -> bool {
1926         !self.is_absolute()
1927     }
1928
1929     fn prefix(&self) -> Option<Prefix> {
1930         self.components().prefix
1931     }
1932
1933     /// Returns `true` if the `Path` has a root.
1934     ///
1935     /// * On Unix, a path has a root if it begins with `/`.
1936     ///
1937     /// * On Windows, a path has a root if it:
1938     ///     * has no prefix and begins with a separator, e.g., `\windows`
1939     ///     * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1940     ///     * has any non-disk prefix, e.g., `\\server\share`
1941     ///
1942     /// # Examples
1943     ///
1944     /// ```
1945     /// use std::path::Path;
1946     ///
1947     /// assert!(Path::new("/etc/passwd").has_root());
1948     /// ```
1949     #[stable(feature = "rust1", since = "1.0.0")]
1950     pub fn has_root(&self) -> bool {
1951         self.components().has_root()
1952     }
1953
1954     /// Returns the `Path` without its final component, if there is one.
1955     ///
1956     /// Returns [`None`] if the path terminates in a root or prefix.
1957     ///
1958     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1959     ///
1960     /// # Examples
1961     ///
1962     /// ```
1963     /// use std::path::Path;
1964     ///
1965     /// let path = Path::new("/foo/bar");
1966     /// let parent = path.parent().unwrap();
1967     /// assert_eq!(parent, Path::new("/foo"));
1968     ///
1969     /// let grand_parent = parent.parent().unwrap();
1970     /// assert_eq!(grand_parent, Path::new("/"));
1971     /// assert_eq!(grand_parent.parent(), None);
1972     /// ```
1973     #[stable(feature = "rust1", since = "1.0.0")]
1974     pub fn parent(&self) -> Option<&Path> {
1975         let mut comps = self.components();
1976         let comp = comps.next_back();
1977         comp.and_then(|p| {
1978             match p {
1979                 Component::Normal(_) |
1980                 Component::CurDir |
1981                 Component::ParentDir => Some(comps.as_path()),
1982                 _ => None,
1983             }
1984         })
1985     }
1986
1987     /// Produces an iterator over `Path` and its ancestors.
1988     ///
1989     /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1990     /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1991     /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1992     /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1993     /// namely `&self`.
1994     ///
1995     /// # Examples
1996     ///
1997     /// ```
1998     /// use std::path::Path;
1999     ///
2000     /// let mut ancestors = Path::new("/foo/bar").ancestors();
2001     /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2002     /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2003     /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2004     /// assert_eq!(ancestors.next(), None);
2005     /// ```
2006     ///
2007     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2008     /// [`parent`]: struct.Path.html#method.parent
2009     #[stable(feature = "path_ancestors", since = "1.28.0")]
2010     pub fn ancestors(&self) -> Ancestors {
2011         Ancestors {
2012             next: Some(&self),
2013         }
2014     }
2015
2016     /// Returns the final component of the `Path`, if there is one.
2017     ///
2018     /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2019     /// is the directory name.
2020     ///
2021     /// Returns [`None`] if the path terminates in `..`.
2022     ///
2023     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2024     ///
2025     /// # Examples
2026     ///
2027     /// ```
2028     /// use std::path::Path;
2029     /// use std::ffi::OsStr;
2030     ///
2031     /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2032     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2033     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2034     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2035     /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2036     /// assert_eq!(None, Path::new("/").file_name());
2037     /// ```
2038     #[stable(feature = "rust1", since = "1.0.0")]
2039     pub fn file_name(&self) -> Option<&OsStr> {
2040         self.components().next_back().and_then(|p| {
2041             match p {
2042                 Component::Normal(p) => Some(p.as_ref()),
2043                 _ => None,
2044             }
2045         })
2046     }
2047
2048     /// Returns a path that, when joined onto `base`, yields `self`.
2049     ///
2050     /// # Errors
2051     ///
2052     /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2053     /// returns `false`), returns [`Err`].
2054     ///
2055     /// [`starts_with`]: #method.starts_with
2056     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2057     ///
2058     /// # Examples
2059     ///
2060     /// ```
2061     /// use std::path::{Path, PathBuf};
2062     ///
2063     /// let path = Path::new("/test/haha/foo.txt");
2064     ///
2065     /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2066     /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2067     /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2068     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2069     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2070     /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2071     /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2072     ///
2073     /// let prefix = PathBuf::from("/test/");
2074     /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2075     /// ```
2076     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2077     pub fn strip_prefix<P>(&self, base: P)
2078                            -> Result<&Path, StripPrefixError>
2079         where P: AsRef<Path>
2080     {
2081         self._strip_prefix(base.as_ref())
2082     }
2083
2084     fn _strip_prefix(&self, base: &Path)
2085                      -> Result<&Path, StripPrefixError> {
2086         iter_after(self.components(), base.components())
2087             .map(|c| c.as_path())
2088             .ok_or(StripPrefixError(()))
2089     }
2090
2091     /// Determines whether `base` is a prefix of `self`.
2092     ///
2093     /// Only considers whole path components to match.
2094     ///
2095     /// # Examples
2096     ///
2097     /// ```
2098     /// use std::path::Path;
2099     ///
2100     /// let path = Path::new("/etc/passwd");
2101     ///
2102     /// assert!(path.starts_with("/etc"));
2103     /// assert!(path.starts_with("/etc/"));
2104     /// assert!(path.starts_with("/etc/passwd"));
2105     /// assert!(path.starts_with("/etc/passwd/"));
2106     ///
2107     /// assert!(!path.starts_with("/e"));
2108     /// ```
2109     #[stable(feature = "rust1", since = "1.0.0")]
2110     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2111         self._starts_with(base.as_ref())
2112     }
2113
2114     fn _starts_with(&self, base: &Path) -> bool {
2115         iter_after(self.components(), base.components()).is_some()
2116     }
2117
2118     /// Determines whether `child` is a suffix of `self`.
2119     ///
2120     /// Only considers whole path components to match.
2121     ///
2122     /// # Examples
2123     ///
2124     /// ```
2125     /// use std::path::Path;
2126     ///
2127     /// let path = Path::new("/etc/passwd");
2128     ///
2129     /// assert!(path.ends_with("passwd"));
2130     /// ```
2131     #[stable(feature = "rust1", since = "1.0.0")]
2132     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2133         self._ends_with(child.as_ref())
2134     }
2135
2136     fn _ends_with(&self, child: &Path) -> bool {
2137         iter_after(self.components().rev(), child.components().rev()).is_some()
2138     }
2139
2140     /// Extracts the stem (non-extension) portion of [`self.file_name`].
2141     ///
2142     /// [`self.file_name`]: struct.Path.html#method.file_name
2143     ///
2144     /// The stem is:
2145     ///
2146     /// * [`None`], if there is no file name;
2147     /// * The entire file name if there is no embedded `.`;
2148     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2149     /// * Otherwise, the portion of the file name before the final `.`
2150     ///
2151     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2152     ///
2153     /// # Examples
2154     ///
2155     /// ```
2156     /// use std::path::Path;
2157     ///
2158     /// let path = Path::new("foo.rs");
2159     ///
2160     /// assert_eq!("foo", path.file_stem().unwrap());
2161     /// ```
2162     #[stable(feature = "rust1", since = "1.0.0")]
2163     pub fn file_stem(&self) -> Option<&OsStr> {
2164         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2165     }
2166
2167     /// Extracts the extension of [`self.file_name`], if possible.
2168     ///
2169     /// The extension is:
2170     ///
2171     /// * [`None`], if there is no file name;
2172     /// * [`None`], if there is no embedded `.`;
2173     /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2174     /// * Otherwise, the portion of the file name after the final `.`
2175     ///
2176     /// [`self.file_name`]: struct.Path.html#method.file_name
2177     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2178     ///
2179     /// # Examples
2180     ///
2181     /// ```
2182     /// use std::path::Path;
2183     ///
2184     /// let path = Path::new("foo.rs");
2185     ///
2186     /// assert_eq!("rs", path.extension().unwrap());
2187     /// ```
2188     #[stable(feature = "rust1", since = "1.0.0")]
2189     pub fn extension(&self) -> Option<&OsStr> {
2190         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2191     }
2192
2193     /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2194     ///
2195     /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2196     ///
2197     /// [`PathBuf`]: struct.PathBuf.html
2198     /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2199     ///
2200     /// # Examples
2201     ///
2202     /// ```
2203     /// use std::path::{Path, PathBuf};
2204     ///
2205     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2206     /// ```
2207     #[stable(feature = "rust1", since = "1.0.0")]
2208     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2209         self._join(path.as_ref())
2210     }
2211
2212     fn _join(&self, path: &Path) -> PathBuf {
2213         let mut buf = self.to_path_buf();
2214         buf.push(path);
2215         buf
2216     }
2217
2218     /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2219     ///
2220     /// See [`PathBuf::set_file_name`] for more details.
2221     ///
2222     /// [`PathBuf`]: struct.PathBuf.html
2223     /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2224     ///
2225     /// # Examples
2226     ///
2227     /// ```
2228     /// use std::path::{Path, PathBuf};
2229     ///
2230     /// let path = Path::new("/tmp/foo.txt");
2231     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2232     ///
2233     /// let path = Path::new("/tmp");
2234     /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2235     /// ```
2236     #[stable(feature = "rust1", since = "1.0.0")]
2237     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2238         self._with_file_name(file_name.as_ref())
2239     }
2240
2241     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2242         let mut buf = self.to_path_buf();
2243         buf.set_file_name(file_name);
2244         buf
2245     }
2246
2247     /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2248     ///
2249     /// See [`PathBuf::set_extension`] for more details.
2250     ///
2251     /// [`PathBuf`]: struct.PathBuf.html
2252     /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2253     ///
2254     /// # Examples
2255     ///
2256     /// ```
2257     /// use std::path::{Path, PathBuf};
2258     ///
2259     /// let path = Path::new("foo.rs");
2260     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2261     /// ```
2262     #[stable(feature = "rust1", since = "1.0.0")]
2263     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2264         self._with_extension(extension.as_ref())
2265     }
2266
2267     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2268         let mut buf = self.to_path_buf();
2269         buf.set_extension(extension);
2270         buf
2271     }
2272
2273     /// Produces an iterator over the [`Component`]s of the path.
2274     ///
2275     /// When parsing the path, there is a small amount of normalization:
2276     ///
2277     /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2278     ///   `a` and `b` as components.
2279     ///
2280     /// * Occurrences of `.` are normalized away, except if they are at the
2281     ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2282     ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
2283     ///   an additional [`CurDir`] component.
2284     ///
2285     /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2286     ///
2287     /// Note that no other normalization takes place; in particular, `a/c`
2288     /// and `a/b/../c` are distinct, to account for the possibility that `b`
2289     /// is a symbolic link (so its parent isn't `a`).
2290     ///
2291     /// # Examples
2292     ///
2293     /// ```
2294     /// use std::path::{Path, Component};
2295     /// use std::ffi::OsStr;
2296     ///
2297     /// let mut components = Path::new("/tmp/foo.txt").components();
2298     ///
2299     /// assert_eq!(components.next(), Some(Component::RootDir));
2300     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2301     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2302     /// assert_eq!(components.next(), None)
2303     /// ```
2304     ///
2305     /// [`Component`]: enum.Component.html
2306     /// [`CurDir`]: enum.Component.html#variant.CurDir
2307     #[stable(feature = "rust1", since = "1.0.0")]
2308     pub fn components(&self) -> Components {
2309         let prefix = parse_prefix(self.as_os_str());
2310         Components {
2311             path: self.as_u8_slice(),
2312             prefix,
2313             has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2314                                has_redox_scheme(self.as_u8_slice()),
2315             front: State::Prefix,
2316             back: State::Body,
2317         }
2318     }
2319
2320     /// Produces an iterator over the path's components viewed as [`OsStr`]
2321     /// slices.
2322     ///
2323     /// For more information about the particulars of how the path is separated
2324     /// into components, see [`components`].
2325     ///
2326     /// [`components`]: #method.components
2327     /// [`OsStr`]: ../ffi/struct.OsStr.html
2328     ///
2329     /// # Examples
2330     ///
2331     /// ```
2332     /// use std::path::{self, Path};
2333     /// use std::ffi::OsStr;
2334     ///
2335     /// let mut it = Path::new("/tmp/foo.txt").iter();
2336     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2337     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2338     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2339     /// assert_eq!(it.next(), None)
2340     /// ```
2341     #[stable(feature = "rust1", since = "1.0.0")]
2342     pub fn iter(&self) -> Iter {
2343         Iter { inner: self.components() }
2344     }
2345
2346     /// Returns an object that implements [`Display`] for safely printing paths
2347     /// that may contain non-Unicode data.
2348     ///
2349     /// [`Display`]: ../fmt/trait.Display.html
2350     ///
2351     /// # Examples
2352     ///
2353     /// ```
2354     /// use std::path::Path;
2355     ///
2356     /// let path = Path::new("/tmp/foo.rs");
2357     ///
2358     /// println!("{}", path.display());
2359     /// ```
2360     #[stable(feature = "rust1", since = "1.0.0")]
2361     pub fn display(&self) -> Display {
2362         Display { path: self }
2363     }
2364
2365     /// Queries the file system to get information about a file, directory, etc.
2366     ///
2367     /// This function will traverse symbolic links to query information about the
2368     /// destination file.
2369     ///
2370     /// This is an alias to [`fs::metadata`].
2371     ///
2372     /// [`fs::metadata`]: ../fs/fn.metadata.html
2373     ///
2374     /// # Examples
2375     ///
2376     /// ```no_run
2377     /// use std::path::Path;
2378     ///
2379     /// let path = Path::new("/Minas/tirith");
2380     /// let metadata = path.metadata().expect("metadata call failed");
2381     /// println!("{:?}", metadata.file_type());
2382     /// ```
2383     #[stable(feature = "path_ext", since = "1.5.0")]
2384     pub fn metadata(&self) -> io::Result<fs::Metadata> {
2385         fs::metadata(self)
2386     }
2387
2388     /// Queries the metadata about a file without following symlinks.
2389     ///
2390     /// This is an alias to [`fs::symlink_metadata`].
2391     ///
2392     /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2393     ///
2394     /// # Examples
2395     ///
2396     /// ```no_run
2397     /// use std::path::Path;
2398     ///
2399     /// let path = Path::new("/Minas/tirith");
2400     /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2401     /// println!("{:?}", metadata.file_type());
2402     /// ```
2403     #[stable(feature = "path_ext", since = "1.5.0")]
2404     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2405         fs::symlink_metadata(self)
2406     }
2407
2408     /// Returns the canonical, absolute form of the path with all intermediate
2409     /// components normalized and symbolic links resolved.
2410     ///
2411     /// This is an alias to [`fs::canonicalize`].
2412     ///
2413     /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2414     ///
2415     /// # Examples
2416     ///
2417     /// ```no_run
2418     /// use std::path::{Path, PathBuf};
2419     ///
2420     /// let path = Path::new("/foo/test/../test/bar.rs");
2421     /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2422     /// ```
2423     #[stable(feature = "path_ext", since = "1.5.0")]
2424     pub fn canonicalize(&self) -> io::Result<PathBuf> {
2425         fs::canonicalize(self)
2426     }
2427
2428     /// Reads a symbolic link, returning the file that the link points to.
2429     ///
2430     /// This is an alias to [`fs::read_link`].
2431     ///
2432     /// [`fs::read_link`]: ../fs/fn.read_link.html
2433     ///
2434     /// # Examples
2435     ///
2436     /// ```no_run
2437     /// use std::path::Path;
2438     ///
2439     /// let path = Path::new("/laputa/sky_castle.rs");
2440     /// let path_link = path.read_link().expect("read_link call failed");
2441     /// ```
2442     #[stable(feature = "path_ext", since = "1.5.0")]
2443     pub fn read_link(&self) -> io::Result<PathBuf> {
2444         fs::read_link(self)
2445     }
2446
2447     /// Returns an iterator over the entries within a directory.
2448     ///
2449     /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2450     /// errors may be encountered after an iterator is initially constructed.
2451     ///
2452     /// This is an alias to [`fs::read_dir`].
2453     ///
2454     /// [`io::Result`]: ../io/type.Result.html
2455     /// [`DirEntry`]: ../fs/struct.DirEntry.html
2456     /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2457     ///
2458     /// # Examples
2459     ///
2460     /// ```no_run
2461     /// use std::path::Path;
2462     ///
2463     /// let path = Path::new("/laputa");
2464     /// for entry in path.read_dir().expect("read_dir call failed") {
2465     ///     if let Ok(entry) = entry {
2466     ///         println!("{:?}", entry.path());
2467     ///     }
2468     /// }
2469     /// ```
2470     #[stable(feature = "path_ext", since = "1.5.0")]
2471     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2472         fs::read_dir(self)
2473     }
2474
2475     /// Returns `true` if the path points at an existing entity.
2476     ///
2477     /// This function will traverse symbolic links to query information about the
2478     /// destination file. In case of broken symbolic links this will return `false`.
2479     ///
2480     /// If you cannot access the directory containing the file, e.g., because of a
2481     /// permission error, this will return `false`.
2482     ///
2483     /// # Examples
2484     ///
2485     /// ```no_run
2486     /// use std::path::Path;
2487     /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2488     /// ```
2489     ///
2490     /// # See Also
2491     ///
2492     /// This is a convenience function that coerces errors to false. If you want to
2493     /// check errors, call [fs::metadata].
2494     ///
2495     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2496     #[stable(feature = "path_ext", since = "1.5.0")]
2497     pub fn exists(&self) -> bool {
2498         fs::metadata(self).is_ok()
2499     }
2500
2501     /// Returns `true` if the path exists on disk and is pointing at a regular file.
2502     ///
2503     /// This function will traverse symbolic links to query information about the
2504     /// destination file. In case of broken symbolic links this will return `false`.
2505     ///
2506     /// If you cannot access the directory containing the file, e.g., because of a
2507     /// permission error, this will return `false`.
2508     ///
2509     /// # Examples
2510     ///
2511     /// ```no_run
2512     /// use std::path::Path;
2513     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2514     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2515     /// ```
2516     ///
2517     /// # See Also
2518     ///
2519     /// This is a convenience function that coerces errors to false. If you want to
2520     /// check errors, call [fs::metadata] and handle its Result. Then call
2521     /// [fs::Metadata::is_file] if it was Ok.
2522     ///
2523     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2524     /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2525     #[stable(feature = "path_ext", since = "1.5.0")]
2526     pub fn is_file(&self) -> bool {
2527         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2528     }
2529
2530     /// Returns `true` if the path exists on disk and is pointing at a directory.
2531     ///
2532     /// This function will traverse symbolic links to query information about the
2533     /// destination file. In case of broken symbolic links this will return `false`.
2534     ///
2535     /// If you cannot access the directory containing the file, e.g., because of a
2536     /// permission error, this will return `false`.
2537     ///
2538     /// # Examples
2539     ///
2540     /// ```no_run
2541     /// use std::path::Path;
2542     /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2543     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2544     /// ```
2545     ///
2546     /// # See Also
2547     ///
2548     /// This is a convenience function that coerces errors to false. If you want to
2549     /// check errors, call [fs::metadata] and handle its Result. Then call
2550     /// [fs::Metadata::is_dir] if it was Ok.
2551     ///
2552     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2553     /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2554     #[stable(feature = "path_ext", since = "1.5.0")]
2555     pub fn is_dir(&self) -> bool {
2556         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2557     }
2558
2559     /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2560     /// allocating.
2561     ///
2562     /// [`Box`]: ../../std/boxed/struct.Box.html
2563     /// [`PathBuf`]: struct.PathBuf.html
2564     #[stable(feature = "into_boxed_path", since = "1.20.0")]
2565     pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2566         let rw = Box::into_raw(self) as *mut OsStr;
2567         let inner = unsafe { Box::from_raw(rw) };
2568         PathBuf { inner: OsString::from(inner) }
2569     }
2570 }
2571
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 impl AsRef<OsStr> for Path {
2574     fn as_ref(&self) -> &OsStr {
2575         &self.inner
2576     }
2577 }
2578
2579 #[stable(feature = "rust1", since = "1.0.0")]
2580 impl fmt::Debug for Path {
2581     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2582         fmt::Debug::fmt(&self.inner, formatter)
2583     }
2584 }
2585
2586 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2587 ///
2588 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2589 /// [`Display`] trait in a way that mitigates that. It is created by the
2590 /// [`display`][`Path::display`] method on [`Path`].
2591 ///
2592 /// # Examples
2593 ///
2594 /// ```
2595 /// use std::path::Path;
2596 ///
2597 /// let path = Path::new("/tmp/foo.rs");
2598 ///
2599 /// println!("{}", path.display());
2600 /// ```
2601 ///
2602 /// [`Display`]: ../../std/fmt/trait.Display.html
2603 /// [`format!`]: ../../std/macro.format.html
2604 /// [`Path`]: struct.Path.html
2605 /// [`Path::display`]: struct.Path.html#method.display
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 pub struct Display<'a> {
2608     path: &'a Path,
2609 }
2610
2611 #[stable(feature = "rust1", since = "1.0.0")]
2612 impl fmt::Debug for Display<'_> {
2613     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2614         fmt::Debug::fmt(&self.path, f)
2615     }
2616 }
2617
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 impl fmt::Display for Display<'_> {
2620     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2621         self.path.inner.display(f)
2622     }
2623 }
2624
2625 #[stable(feature = "rust1", since = "1.0.0")]
2626 impl cmp::PartialEq for Path {
2627     fn eq(&self, other: &Path) -> bool {
2628         self.components().eq(other.components())
2629     }
2630 }
2631
2632 #[stable(feature = "rust1", since = "1.0.0")]
2633 impl Hash for Path {
2634     fn hash<H: Hasher>(&self, h: &mut H) {
2635         for component in self.components() {
2636             component.hash(h);
2637         }
2638     }
2639 }
2640
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 impl cmp::Eq for Path {}
2643
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 impl cmp::PartialOrd for Path {
2646     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2647         self.components().partial_cmp(other.components())
2648     }
2649 }
2650
2651 #[stable(feature = "rust1", since = "1.0.0")]
2652 impl cmp::Ord for Path {
2653     fn cmp(&self, other: &Path) -> cmp::Ordering {
2654         self.components().cmp(other.components())
2655     }
2656 }
2657
2658 #[stable(feature = "rust1", since = "1.0.0")]
2659 impl AsRef<Path> for Path {
2660     fn as_ref(&self) -> &Path {
2661         self
2662     }
2663 }
2664
2665 #[stable(feature = "rust1", since = "1.0.0")]
2666 impl AsRef<Path> for OsStr {
2667     fn as_ref(&self) -> &Path {
2668         Path::new(self)
2669     }
2670 }
2671
2672 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2673 impl AsRef<Path> for Cow<'_, OsStr> {
2674     fn as_ref(&self) -> &Path {
2675         Path::new(self)
2676     }
2677 }
2678
2679 #[stable(feature = "rust1", since = "1.0.0")]
2680 impl AsRef<Path> for OsString {
2681     fn as_ref(&self) -> &Path {
2682         Path::new(self)
2683     }
2684 }
2685
2686 #[stable(feature = "rust1", since = "1.0.0")]
2687 impl AsRef<Path> for str {
2688     fn as_ref(&self) -> &Path {
2689         Path::new(self)
2690     }
2691 }
2692
2693 #[stable(feature = "rust1", since = "1.0.0")]
2694 impl AsRef<Path> for String {
2695     fn as_ref(&self) -> &Path {
2696         Path::new(self)
2697     }
2698 }
2699
2700 #[stable(feature = "rust1", since = "1.0.0")]
2701 impl AsRef<Path> for PathBuf {
2702     fn as_ref(&self) -> &Path {
2703         self
2704     }
2705 }
2706
2707 #[stable(feature = "path_into_iter", since = "1.6.0")]
2708 impl<'a> IntoIterator for &'a PathBuf {
2709     type Item = &'a OsStr;
2710     type IntoIter = Iter<'a>;
2711     fn into_iter(self) -> Iter<'a> { self.iter() }
2712 }
2713
2714 #[stable(feature = "path_into_iter", since = "1.6.0")]
2715 impl<'a> IntoIterator for &'a Path {
2716     type Item = &'a OsStr;
2717     type IntoIter = Iter<'a>;
2718     fn into_iter(self) -> Iter<'a> { self.iter() }
2719 }
2720
2721 macro_rules! impl_cmp {
2722     ($lhs:ty, $rhs: ty) => {
2723         #[stable(feature = "partialeq_path", since = "1.6.0")]
2724         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2725             #[inline]
2726             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2727         }
2728
2729         #[stable(feature = "partialeq_path", since = "1.6.0")]
2730         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2731             #[inline]
2732             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2733         }
2734
2735         #[stable(feature = "cmp_path", since = "1.8.0")]
2736         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2737             #[inline]
2738             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2739                 <Path as PartialOrd>::partial_cmp(self, other)
2740             }
2741         }
2742
2743         #[stable(feature = "cmp_path", since = "1.8.0")]
2744         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2745             #[inline]
2746             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2747                 <Path as PartialOrd>::partial_cmp(self, other)
2748             }
2749         }
2750     }
2751 }
2752
2753 impl_cmp!(PathBuf, Path);
2754 impl_cmp!(PathBuf, &'a Path);
2755 impl_cmp!(Cow<'a, Path>, Path);
2756 impl_cmp!(Cow<'a, Path>, &'b Path);
2757 impl_cmp!(Cow<'a, Path>, PathBuf);
2758
2759 macro_rules! impl_cmp_os_str {
2760     ($lhs:ty, $rhs: ty) => {
2761         #[stable(feature = "cmp_path", since = "1.8.0")]
2762         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2763             #[inline]
2764             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2765         }
2766
2767         #[stable(feature = "cmp_path", since = "1.8.0")]
2768         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2769             #[inline]
2770             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2771         }
2772
2773         #[stable(feature = "cmp_path", since = "1.8.0")]
2774         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2775             #[inline]
2776             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2777                 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2778             }
2779         }
2780
2781         #[stable(feature = "cmp_path", since = "1.8.0")]
2782         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2783             #[inline]
2784             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2785                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2786             }
2787         }
2788     }
2789 }
2790
2791 impl_cmp_os_str!(PathBuf, OsStr);
2792 impl_cmp_os_str!(PathBuf, &'a OsStr);
2793 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2794 impl_cmp_os_str!(PathBuf, OsString);
2795 impl_cmp_os_str!(Path, OsStr);
2796 impl_cmp_os_str!(Path, &'a OsStr);
2797 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2798 impl_cmp_os_str!(Path, OsString);
2799 impl_cmp_os_str!(&'a Path, OsStr);
2800 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2801 impl_cmp_os_str!(&'a Path, OsString);
2802 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2803 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2804 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2805
2806 #[stable(since = "1.7.0", feature = "strip_prefix")]
2807 impl fmt::Display for StripPrefixError {
2808     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2809         self.description().fmt(f)
2810     }
2811 }
2812
2813 #[stable(since = "1.7.0", feature = "strip_prefix")]
2814 impl Error for StripPrefixError {
2815     fn description(&self) -> &str { "prefix not found" }
2816 }
2817
2818 #[cfg(test)]
2819 mod tests {
2820     use super::*;
2821
2822     use crate::rc::Rc;
2823     use crate::sync::Arc;
2824
2825     macro_rules! t(
2826         ($path:expr, iter: $iter:expr) => (
2827             {
2828                 let path = Path::new($path);
2829
2830                 // Forward iteration
2831                 let comps = path.iter()
2832                     .map(|p| p.to_string_lossy().into_owned())
2833                     .collect::<Vec<String>>();
2834                 let exp: &[&str] = &$iter;
2835                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2836                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2837                         exps, comps);
2838
2839                 // Reverse iteration
2840                 let comps = Path::new($path).iter().rev()
2841                     .map(|p| p.to_string_lossy().into_owned())
2842                     .collect::<Vec<String>>();
2843                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2844                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2845                         exps, comps);
2846             }
2847         );
2848
2849         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2850             {
2851                 let path = Path::new($path);
2852
2853                 let act_root = path.has_root();
2854                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2855                         $has_root, act_root);
2856
2857                 let act_abs = path.is_absolute();
2858                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2859                         $is_absolute, act_abs);
2860             }
2861         );
2862
2863         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2864             {
2865                 let path = Path::new($path);
2866
2867                 let parent = path.parent().map(|p| p.to_str().unwrap());
2868                 let exp_parent: Option<&str> = $parent;
2869                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2870                         exp_parent, parent);
2871
2872                 let file = path.file_name().map(|p| p.to_str().unwrap());
2873                 let exp_file: Option<&str> = $file;
2874                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2875                         exp_file, file);
2876             }
2877         );
2878
2879         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2880             {
2881                 let path = Path::new($path);
2882
2883                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2884                 let exp_stem: Option<&str> = $file_stem;
2885                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2886                         exp_stem, stem);
2887
2888                 let ext = path.extension().map(|p| p.to_str().unwrap());
2889                 let exp_ext: Option<&str> = $extension;
2890                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2891                         exp_ext, ext);
2892             }
2893         );
2894
2895         ($path:expr, iter: $iter:expr,
2896                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2897                      parent: $parent:expr, file_name: $file:expr,
2898                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2899             {
2900                 t!($path, iter: $iter);
2901                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2902                 t!($path, parent: $parent, file_name: $file);
2903                 t!($path, file_stem: $file_stem, extension: $extension);
2904             }
2905         );
2906     );
2907
2908     #[test]
2909     fn into() {
2910         use crate::borrow::Cow;
2911
2912         let static_path = Path::new("/home/foo");
2913         let static_cow_path: Cow<'static, Path> = static_path.into();
2914         let pathbuf = PathBuf::from("/home/foo");
2915
2916         {
2917             let path: &Path = &pathbuf;
2918             let borrowed_cow_path: Cow<Path> = path.into();
2919
2920             assert_eq!(static_cow_path, borrowed_cow_path);
2921         }
2922
2923         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2924
2925         assert_eq!(static_cow_path, owned_cow_path);
2926     }
2927
2928     #[test]
2929     #[cfg(unix)]
2930     pub fn test_decompositions_unix() {
2931         t!("",
2932            iter: [],
2933            has_root: false,
2934            is_absolute: false,
2935            parent: None,
2936            file_name: None,
2937            file_stem: None,
2938            extension: None
2939            );
2940
2941         t!("foo",
2942            iter: ["foo"],
2943            has_root: false,
2944            is_absolute: false,
2945            parent: Some(""),
2946            file_name: Some("foo"),
2947            file_stem: Some("foo"),
2948            extension: None
2949            );
2950
2951         t!("/",
2952            iter: ["/"],
2953            has_root: true,
2954            is_absolute: true,
2955            parent: None,
2956            file_name: None,
2957            file_stem: None,
2958            extension: None
2959            );
2960
2961         t!("/foo",
2962            iter: ["/", "foo"],
2963            has_root: true,
2964            is_absolute: true,
2965            parent: Some("/"),
2966            file_name: Some("foo"),
2967            file_stem: Some("foo"),
2968            extension: None
2969            );
2970
2971         t!("foo/",
2972            iter: ["foo"],
2973            has_root: false,
2974            is_absolute: false,
2975            parent: Some(""),
2976            file_name: Some("foo"),
2977            file_stem: Some("foo"),
2978            extension: None
2979            );
2980
2981         t!("/foo/",
2982            iter: ["/", "foo"],
2983            has_root: true,
2984            is_absolute: true,
2985            parent: Some("/"),
2986            file_name: Some("foo"),
2987            file_stem: Some("foo"),
2988            extension: None
2989            );
2990
2991         t!("foo/bar",
2992            iter: ["foo", "bar"],
2993            has_root: false,
2994            is_absolute: false,
2995            parent: Some("foo"),
2996            file_name: Some("bar"),
2997            file_stem: Some("bar"),
2998            extension: None
2999            );
3000
3001         t!("/foo/bar",
3002            iter: ["/", "foo", "bar"],
3003            has_root: true,
3004            is_absolute: true,
3005            parent: Some("/foo"),
3006            file_name: Some("bar"),
3007            file_stem: Some("bar"),
3008            extension: None
3009            );
3010
3011         t!("///foo///",
3012            iter: ["/", "foo"],
3013            has_root: true,
3014            is_absolute: true,
3015            parent: Some("/"),
3016            file_name: Some("foo"),
3017            file_stem: Some("foo"),
3018            extension: None
3019            );
3020
3021         t!("///foo///bar",
3022            iter: ["/", "foo", "bar"],
3023            has_root: true,
3024            is_absolute: true,
3025            parent: Some("///foo"),
3026            file_name: Some("bar"),
3027            file_stem: Some("bar"),
3028            extension: None
3029            );
3030
3031         t!("./.",
3032            iter: ["."],
3033            has_root: false,
3034            is_absolute: false,
3035            parent: Some(""),
3036            file_name: None,
3037            file_stem: None,
3038            extension: None
3039            );
3040
3041         t!("/..",
3042            iter: ["/", ".."],
3043            has_root: true,
3044            is_absolute: true,
3045            parent: Some("/"),
3046            file_name: None,
3047            file_stem: None,
3048            extension: None
3049            );
3050
3051         t!("../",
3052            iter: [".."],
3053            has_root: false,
3054            is_absolute: false,
3055            parent: Some(""),
3056            file_name: None,
3057            file_stem: None,
3058            extension: None
3059            );
3060
3061         t!("foo/.",
3062            iter: ["foo"],
3063            has_root: false,
3064            is_absolute: false,
3065            parent: Some(""),
3066            file_name: Some("foo"),
3067            file_stem: Some("foo"),
3068            extension: None
3069            );
3070
3071         t!("foo/..",
3072            iter: ["foo", ".."],
3073            has_root: false,
3074            is_absolute: false,
3075            parent: Some("foo"),
3076            file_name: None,
3077            file_stem: None,
3078            extension: None
3079            );
3080
3081         t!("foo/./",
3082            iter: ["foo"],
3083            has_root: false,
3084            is_absolute: false,
3085            parent: Some(""),
3086            file_name: Some("foo"),
3087            file_stem: Some("foo"),
3088            extension: None
3089            );
3090
3091         t!("foo/./bar",
3092            iter: ["foo", "bar"],
3093            has_root: false,
3094            is_absolute: false,
3095            parent: Some("foo"),
3096            file_name: Some("bar"),
3097            file_stem: Some("bar"),
3098            extension: None
3099            );
3100
3101         t!("foo/../",
3102            iter: ["foo", ".."],
3103            has_root: false,
3104            is_absolute: false,
3105            parent: Some("foo"),
3106            file_name: None,
3107            file_stem: None,
3108            extension: None
3109            );
3110
3111         t!("foo/../bar",
3112            iter: ["foo", "..", "bar"],
3113            has_root: false,
3114            is_absolute: false,
3115            parent: Some("foo/.."),
3116            file_name: Some("bar"),
3117            file_stem: Some("bar"),
3118            extension: None
3119            );
3120
3121         t!("./a",
3122            iter: [".", "a"],
3123            has_root: false,
3124            is_absolute: false,
3125            parent: Some("."),
3126            file_name: Some("a"),
3127            file_stem: Some("a"),
3128            extension: None
3129            );
3130
3131         t!(".",
3132            iter: ["."],
3133            has_root: false,
3134            is_absolute: false,
3135            parent: Some(""),
3136            file_name: None,
3137            file_stem: None,
3138            extension: None
3139            );
3140
3141         t!("./",
3142            iter: ["."],
3143            has_root: false,
3144            is_absolute: false,
3145            parent: Some(""),
3146            file_name: None,
3147            file_stem: None,
3148            extension: None
3149            );
3150
3151         t!("a/b",
3152            iter: ["a", "b"],
3153            has_root: false,
3154            is_absolute: false,
3155            parent: Some("a"),
3156            file_name: Some("b"),
3157            file_stem: Some("b"),
3158            extension: None
3159            );
3160
3161         t!("a//b",
3162            iter: ["a", "b"],
3163            has_root: false,
3164            is_absolute: false,
3165            parent: Some("a"),
3166            file_name: Some("b"),
3167            file_stem: Some("b"),
3168            extension: None
3169            );
3170
3171         t!("a/./b",
3172            iter: ["a", "b"],
3173            has_root: false,
3174            is_absolute: false,
3175            parent: Some("a"),
3176            file_name: Some("b"),
3177            file_stem: Some("b"),
3178            extension: None
3179            );
3180
3181         t!("a/b/c",
3182            iter: ["a", "b", "c"],
3183            has_root: false,
3184            is_absolute: false,
3185            parent: Some("a/b"),
3186            file_name: Some("c"),
3187            file_stem: Some("c"),
3188            extension: None
3189            );
3190
3191         t!(".foo",
3192            iter: [".foo"],
3193            has_root: false,
3194            is_absolute: false,
3195            parent: Some(""),
3196            file_name: Some(".foo"),
3197            file_stem: Some(".foo"),
3198            extension: None
3199            );
3200     }
3201
3202     #[test]
3203     #[cfg(windows)]
3204     pub fn test_decompositions_windows() {
3205         t!("",
3206            iter: [],
3207            has_root: false,
3208            is_absolute: false,
3209            parent: None,
3210            file_name: None,
3211            file_stem: None,
3212            extension: None
3213            );
3214
3215         t!("foo",
3216            iter: ["foo"],
3217            has_root: false,
3218            is_absolute: false,
3219            parent: Some(""),
3220            file_name: Some("foo"),
3221            file_stem: Some("foo"),
3222            extension: None
3223            );
3224
3225         t!("/",
3226            iter: ["\\"],
3227            has_root: true,
3228            is_absolute: false,
3229            parent: None,
3230            file_name: None,
3231            file_stem: None,
3232            extension: None
3233            );
3234
3235         t!("\\",
3236            iter: ["\\"],
3237            has_root: true,
3238            is_absolute: false,
3239            parent: None,
3240            file_name: None,
3241            file_stem: None,
3242            extension: None
3243            );
3244
3245         t!("c:",
3246            iter: ["c:"],
3247            has_root: false,
3248            is_absolute: false,
3249            parent: None,
3250            file_name: None,
3251            file_stem: None,
3252            extension: None
3253            );
3254
3255         t!("c:\\",
3256            iter: ["c:", "\\"],
3257            has_root: true,
3258            is_absolute: true,
3259            parent: None,
3260            file_name: None,
3261            file_stem: None,
3262            extension: None
3263            );
3264
3265         t!("c:/",
3266            iter: ["c:", "\\"],
3267            has_root: true,
3268            is_absolute: true,
3269            parent: None,
3270            file_name: None,
3271            file_stem: None,
3272            extension: None
3273            );
3274
3275         t!("/foo",
3276            iter: ["\\", "foo"],
3277            has_root: true,
3278            is_absolute: false,
3279            parent: Some("/"),
3280            file_name: Some("foo"),
3281            file_stem: Some("foo"),
3282            extension: None
3283            );
3284
3285         t!("foo/",
3286            iter: ["foo"],
3287            has_root: false,
3288            is_absolute: false,
3289            parent: Some(""),
3290            file_name: Some("foo"),
3291            file_stem: Some("foo"),
3292            extension: None
3293            );
3294
3295         t!("/foo/",
3296            iter: ["\\", "foo"],
3297            has_root: true,
3298            is_absolute: false,
3299            parent: Some("/"),
3300            file_name: Some("foo"),
3301            file_stem: Some("foo"),
3302            extension: None
3303            );
3304
3305         t!("foo/bar",
3306            iter: ["foo", "bar"],
3307            has_root: false,
3308            is_absolute: false,
3309            parent: Some("foo"),
3310            file_name: Some("bar"),
3311            file_stem: Some("bar"),
3312            extension: None
3313            );
3314
3315         t!("/foo/bar",
3316            iter: ["\\", "foo", "bar"],
3317            has_root: true,
3318            is_absolute: false,
3319            parent: Some("/foo"),
3320            file_name: Some("bar"),
3321            file_stem: Some("bar"),
3322            extension: None
3323            );
3324
3325         t!("///foo///",
3326            iter: ["\\", "foo"],
3327            has_root: true,
3328            is_absolute: false,
3329            parent: Some("/"),
3330            file_name: Some("foo"),
3331            file_stem: Some("foo"),
3332            extension: None
3333            );
3334
3335         t!("///foo///bar",
3336            iter: ["\\", "foo", "bar"],
3337            has_root: true,
3338            is_absolute: false,
3339            parent: Some("///foo"),
3340            file_name: Some("bar"),
3341            file_stem: Some("bar"),
3342            extension: None
3343            );
3344
3345         t!("./.",
3346            iter: ["."],
3347            has_root: false,
3348            is_absolute: false,
3349            parent: Some(""),
3350            file_name: None,
3351            file_stem: None,
3352            extension: None
3353            );
3354
3355         t!("/..",
3356            iter: ["\\", ".."],
3357            has_root: true,
3358            is_absolute: false,
3359            parent: Some("/"),
3360            file_name: None,
3361            file_stem: None,
3362            extension: None
3363            );
3364
3365         t!("../",
3366            iter: [".."],
3367            has_root: false,
3368            is_absolute: false,
3369            parent: Some(""),
3370            file_name: None,
3371            file_stem: None,
3372            extension: None
3373            );
3374
3375         t!("foo/.",
3376            iter: ["foo"],
3377            has_root: false,
3378            is_absolute: false,
3379            parent: Some(""),
3380            file_name: Some("foo"),
3381            file_stem: Some("foo"),
3382            extension: None
3383            );
3384
3385         t!("foo/..",
3386            iter: ["foo", ".."],
3387            has_root: false,
3388            is_absolute: false,
3389            parent: Some("foo"),
3390            file_name: None,
3391            file_stem: None,
3392            extension: None
3393            );
3394
3395         t!("foo/./",
3396            iter: ["foo"],
3397            has_root: false,
3398            is_absolute: false,
3399            parent: Some(""),
3400            file_name: Some("foo"),
3401            file_stem: Some("foo"),
3402            extension: None
3403            );
3404
3405         t!("foo/./bar",
3406            iter: ["foo", "bar"],
3407            has_root: false,
3408            is_absolute: false,
3409            parent: Some("foo"),
3410            file_name: Some("bar"),
3411            file_stem: Some("bar"),
3412            extension: None
3413            );
3414
3415         t!("foo/../",
3416            iter: ["foo", ".."],
3417            has_root: false,
3418            is_absolute: false,
3419            parent: Some("foo"),
3420            file_name: None,
3421            file_stem: None,
3422            extension: None
3423            );
3424
3425         t!("foo/../bar",
3426            iter: ["foo", "..", "bar"],
3427            has_root: false,
3428            is_absolute: false,
3429            parent: Some("foo/.."),
3430            file_name: Some("bar"),
3431            file_stem: Some("bar"),
3432            extension: None
3433            );
3434
3435         t!("./a",
3436            iter: [".", "a"],
3437            has_root: false,
3438            is_absolute: false,
3439            parent: Some("."),
3440            file_name: Some("a"),
3441            file_stem: Some("a"),
3442            extension: None
3443            );
3444
3445         t!(".",
3446            iter: ["."],
3447            has_root: false,
3448            is_absolute: false,
3449            parent: Some(""),
3450            file_name: None,
3451            file_stem: None,
3452            extension: None
3453            );
3454
3455         t!("./",
3456            iter: ["."],
3457            has_root: false,
3458            is_absolute: false,
3459            parent: Some(""),
3460            file_name: None,
3461            file_stem: None,
3462            extension: None
3463            );
3464
3465         t!("a/b",
3466            iter: ["a", "b"],
3467            has_root: false,
3468            is_absolute: false,
3469            parent: Some("a"),
3470            file_name: Some("b"),
3471            file_stem: Some("b"),
3472            extension: None
3473            );
3474
3475         t!("a//b",
3476            iter: ["a", "b"],
3477            has_root: false,
3478            is_absolute: false,
3479            parent: Some("a"),
3480            file_name: Some("b"),
3481            file_stem: Some("b"),
3482            extension: None
3483            );
3484
3485         t!("a/./b",
3486            iter: ["a", "b"],
3487            has_root: false,
3488            is_absolute: false,
3489            parent: Some("a"),
3490            file_name: Some("b"),
3491            file_stem: Some("b"),
3492            extension: None
3493            );
3494
3495         t!("a/b/c",
3496            iter: ["a", "b", "c"],
3497            has_root: false,
3498            is_absolute: false,
3499            parent: Some("a/b"),
3500            file_name: Some("c"),
3501            file_stem: Some("c"),
3502            extension: None);
3503
3504         t!("a\\b\\c",
3505            iter: ["a", "b", "c"],
3506            has_root: false,
3507            is_absolute: false,
3508            parent: Some("a\\b"),
3509            file_name: Some("c"),
3510            file_stem: Some("c"),
3511            extension: None
3512            );
3513
3514         t!("\\a",
3515            iter: ["\\", "a"],
3516            has_root: true,
3517            is_absolute: false,
3518            parent: Some("\\"),
3519            file_name: Some("a"),
3520            file_stem: Some("a"),
3521            extension: None
3522            );
3523
3524         t!("c:\\foo.txt",
3525            iter: ["c:", "\\", "foo.txt"],
3526            has_root: true,
3527            is_absolute: true,
3528            parent: Some("c:\\"),
3529            file_name: Some("foo.txt"),
3530            file_stem: Some("foo"),
3531            extension: Some("txt")
3532            );
3533
3534         t!("\\\\server\\share\\foo.txt",
3535            iter: ["\\\\server\\share", "\\", "foo.txt"],
3536            has_root: true,
3537            is_absolute: true,
3538            parent: Some("\\\\server\\share\\"),
3539            file_name: Some("foo.txt"),
3540            file_stem: Some("foo"),
3541            extension: Some("txt")
3542            );
3543
3544         t!("\\\\server\\share",
3545            iter: ["\\\\server\\share", "\\"],
3546            has_root: true,
3547            is_absolute: true,
3548            parent: None,
3549            file_name: None,
3550            file_stem: None,
3551            extension: None
3552            );
3553
3554         t!("\\\\server",
3555            iter: ["\\", "server"],
3556            has_root: true,
3557            is_absolute: false,
3558            parent: Some("\\"),
3559            file_name: Some("server"),
3560            file_stem: Some("server"),
3561            extension: None
3562            );
3563
3564         t!("\\\\?\\bar\\foo.txt",
3565            iter: ["\\\\?\\bar", "\\", "foo.txt"],
3566            has_root: true,
3567            is_absolute: true,
3568            parent: Some("\\\\?\\bar\\"),
3569            file_name: Some("foo.txt"),
3570            file_stem: Some("foo"),
3571            extension: Some("txt")
3572            );
3573
3574         t!("\\\\?\\bar",
3575            iter: ["\\\\?\\bar"],
3576            has_root: true,
3577            is_absolute: true,
3578            parent: None,
3579            file_name: None,
3580            file_stem: None,
3581            extension: None
3582            );
3583
3584         t!("\\\\?\\",
3585            iter: ["\\\\?\\"],
3586            has_root: true,
3587            is_absolute: true,
3588            parent: None,
3589            file_name: None,
3590            file_stem: None,
3591            extension: None
3592            );
3593
3594         t!("\\\\?\\UNC\\server\\share\\foo.txt",
3595            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3596            has_root: true,
3597            is_absolute: true,
3598            parent: Some("\\\\?\\UNC\\server\\share\\"),
3599            file_name: Some("foo.txt"),
3600            file_stem: Some("foo"),
3601            extension: Some("txt")
3602            );
3603
3604         t!("\\\\?\\UNC\\server",
3605            iter: ["\\\\?\\UNC\\server"],
3606            has_root: true,
3607            is_absolute: true,
3608            parent: None,
3609            file_name: None,
3610            file_stem: None,
3611            extension: None
3612            );
3613
3614         t!("\\\\?\\UNC\\",
3615            iter: ["\\\\?\\UNC\\"],
3616            has_root: true,
3617            is_absolute: true,
3618            parent: None,
3619            file_name: None,
3620            file_stem: None,
3621            extension: None
3622            );
3623
3624         t!("\\\\?\\C:\\foo.txt",
3625            iter: ["\\\\?\\C:", "\\", "foo.txt"],
3626            has_root: true,
3627            is_absolute: true,
3628            parent: Some("\\\\?\\C:\\"),
3629            file_name: Some("foo.txt"),
3630            file_stem: Some("foo"),
3631            extension: Some("txt")
3632            );
3633
3634
3635         t!("\\\\?\\C:\\",
3636            iter: ["\\\\?\\C:", "\\"],
3637            has_root: true,
3638            is_absolute: true,
3639            parent: None,
3640            file_name: None,
3641            file_stem: None,
3642            extension: None
3643            );
3644
3645
3646         t!("\\\\?\\C:",
3647            iter: ["\\\\?\\C:"],
3648            has_root: true,
3649            is_absolute: true,
3650            parent: None,
3651            file_name: None,
3652            file_stem: None,
3653            extension: None
3654            );
3655
3656
3657         t!("\\\\?\\foo/bar",
3658            iter: ["\\\\?\\foo/bar"],
3659            has_root: true,
3660            is_absolute: true,
3661            parent: None,
3662            file_name: None,
3663            file_stem: None,
3664            extension: None
3665            );
3666
3667
3668         t!("\\\\?\\C:/foo",
3669            iter: ["\\\\?\\C:/foo"],
3670            has_root: true,
3671            is_absolute: true,
3672            parent: None,
3673            file_name: None,
3674            file_stem: None,
3675            extension: None
3676            );
3677
3678
3679         t!("\\\\.\\foo\\bar",
3680            iter: ["\\\\.\\foo", "\\", "bar"],
3681            has_root: true,
3682            is_absolute: true,
3683            parent: Some("\\\\.\\foo\\"),
3684            file_name: Some("bar"),
3685            file_stem: Some("bar"),
3686            extension: None
3687            );
3688
3689
3690         t!("\\\\.\\foo",
3691            iter: ["\\\\.\\foo", "\\"],
3692            has_root: true,
3693            is_absolute: true,
3694            parent: None,
3695            file_name: None,
3696            file_stem: None,
3697            extension: None
3698            );
3699
3700
3701         t!("\\\\.\\foo/bar",
3702            iter: ["\\\\.\\foo/bar", "\\"],
3703            has_root: true,
3704            is_absolute: true,
3705            parent: None,
3706            file_name: None,
3707            file_stem: None,
3708            extension: None
3709            );
3710
3711
3712         t!("\\\\.\\foo\\bar/baz",
3713            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3714            has_root: true,
3715            is_absolute: true,
3716            parent: Some("\\\\.\\foo\\bar"),
3717            file_name: Some("baz"),
3718            file_stem: Some("baz"),
3719            extension: None
3720            );
3721
3722
3723         t!("\\\\.\\",
3724            iter: ["\\\\.\\", "\\"],
3725            has_root: true,
3726            is_absolute: true,
3727            parent: None,
3728            file_name: None,
3729            file_stem: None,
3730            extension: None
3731            );
3732
3733         t!("\\\\?\\a\\b\\",
3734            iter: ["\\\\?\\a", "\\", "b"],
3735            has_root: true,
3736            is_absolute: true,
3737            parent: Some("\\\\?\\a\\"),
3738            file_name: Some("b"),
3739            file_stem: Some("b"),
3740            extension: None
3741            );
3742     }
3743
3744     #[test]
3745     pub fn test_stem_ext() {
3746         t!("foo",
3747            file_stem: Some("foo"),
3748            extension: None
3749            );
3750
3751         t!("foo.",
3752            file_stem: Some("foo"),
3753            extension: Some("")
3754            );
3755
3756         t!(".foo",
3757            file_stem: Some(".foo"),
3758            extension: None
3759            );
3760
3761         t!("foo.txt",
3762            file_stem: Some("foo"),
3763            extension: Some("txt")
3764            );
3765
3766         t!("foo.bar.txt",
3767            file_stem: Some("foo.bar"),
3768            extension: Some("txt")
3769            );
3770
3771         t!("foo.bar.",
3772            file_stem: Some("foo.bar"),
3773            extension: Some("")
3774            );
3775
3776         t!(".",
3777            file_stem: None,
3778            extension: None
3779            );
3780
3781         t!("..",
3782            file_stem: None,
3783            extension: None
3784            );
3785
3786         t!("",
3787            file_stem: None,
3788            extension: None
3789            );
3790     }
3791
3792     #[test]
3793     pub fn test_push() {
3794         macro_rules! tp(
3795             ($path:expr, $push:expr, $expected:expr) => ( {
3796                 let mut actual = PathBuf::from($path);
3797                 actual.push($push);
3798                 assert!(actual.to_str() == Some($expected),
3799                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3800                         $push, $path, $expected, actual.to_str().unwrap());
3801             });
3802         );
3803
3804         if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3805             tp!("", "foo", "foo");
3806             tp!("foo", "bar", "foo/bar");
3807             tp!("foo/", "bar", "foo/bar");
3808             tp!("foo//", "bar", "foo//bar");
3809             tp!("foo/.", "bar", "foo/./bar");
3810             tp!("foo./.", "bar", "foo././bar");
3811             tp!("foo", "", "foo/");
3812             tp!("foo", ".", "foo/.");
3813             tp!("foo", "..", "foo/..");
3814             tp!("foo", "/", "/");
3815             tp!("/foo/bar", "/", "/");
3816             tp!("/foo/bar", "/baz", "/baz");
3817             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3818         } else {
3819             tp!("", "foo", "foo");
3820             tp!("foo", "bar", r"foo\bar");
3821             tp!("foo/", "bar", r"foo/bar");
3822             tp!(r"foo\", "bar", r"foo\bar");
3823             tp!("foo//", "bar", r"foo//bar");
3824             tp!(r"foo\\", "bar", r"foo\\bar");
3825             tp!("foo/.", "bar", r"foo/.\bar");
3826             tp!("foo./.", "bar", r"foo./.\bar");
3827             tp!(r"foo\.", "bar", r"foo\.\bar");
3828             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3829             tp!("foo", "", "foo\\");
3830             tp!("foo", ".", r"foo\.");
3831             tp!("foo", "..", r"foo\..");
3832             tp!("foo", "/", "/");
3833             tp!("foo", r"\", r"\");
3834             tp!("/foo/bar", "/", "/");
3835             tp!(r"\foo\bar", r"\", r"\");
3836             tp!("/foo/bar", "/baz", "/baz");
3837             tp!("/foo/bar", r"\baz", r"\baz");
3838             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3839             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3840
3841             tp!("c:\\", "windows", "c:\\windows");
3842             tp!("c:", "windows", "c:windows");
3843
3844             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3845             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3846             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3847             tp!("a\\b", "\\c\\d", "\\c\\d");
3848             tp!("a\\b", ".", "a\\b\\.");
3849             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3850             tp!("a\\b", "C:a.txt", "C:a.txt");
3851             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3852             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3853             tp!("C:\\a\\b\\c", "C:d", "C:d");
3854             tp!("C:a\\b\\c", "C:d", "C:d");
3855             tp!("C:", r"a\b\c", r"C:a\b\c");
3856             tp!("C:", r"..\a", r"C:..\a");
3857             tp!("\\\\server\\share\\foo",
3858                 "bar",
3859                 "\\\\server\\share\\foo\\bar");
3860             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3861             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3862             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3863             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3864             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3865             tp!("\\\\?\\UNC\\server\\share\\foo",
3866                 "bar",
3867                 "\\\\?\\UNC\\server\\share\\foo\\bar");
3868             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3869             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3870
3871             // Note: modified from old path API
3872             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3873
3874             tp!("C:\\a",
3875                 "\\\\?\\UNC\\server\\share",
3876                 "\\\\?\\UNC\\server\\share");
3877             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3878             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3879             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3880             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3881
3882             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3883         }
3884     }
3885
3886     #[test]
3887     pub fn test_pop() {
3888         macro_rules! tp(
3889             ($path:expr, $expected:expr, $output:expr) => ( {
3890                 let mut actual = PathBuf::from($path);
3891                 let output = actual.pop();
3892                 assert!(actual.to_str() == Some($expected) && output == $output,
3893                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3894                         $path, $expected, $output,
3895                         actual.to_str().unwrap(), output);
3896             });
3897         );
3898
3899         tp!("", "", false);
3900         tp!("/", "/", false);
3901         tp!("foo", "", true);
3902         tp!(".", "", true);
3903         tp!("/foo", "/", true);
3904         tp!("/foo/bar", "/foo", true);
3905         tp!("foo/bar", "foo", true);
3906         tp!("foo/.", "", true);
3907         tp!("foo//bar", "foo", true);
3908
3909         if cfg!(windows) {
3910             tp!("a\\b\\c", "a\\b", true);
3911             tp!("\\a", "\\", true);
3912             tp!("\\", "\\", false);
3913
3914             tp!("C:\\a\\b", "C:\\a", true);
3915             tp!("C:\\a", "C:\\", true);
3916             tp!("C:\\", "C:\\", false);
3917             tp!("C:a\\b", "C:a", true);
3918             tp!("C:a", "C:", true);
3919             tp!("C:", "C:", false);
3920             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3921             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3922             tp!("\\\\server\\share", "\\\\server\\share", false);
3923             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3924             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3925             tp!("\\\\?\\a", "\\\\?\\a", false);
3926             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3927             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3928             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3929             tp!("\\\\?\\UNC\\server\\share\\a\\b",
3930                 "\\\\?\\UNC\\server\\share\\a",
3931                 true);
3932             tp!("\\\\?\\UNC\\server\\share\\a",
3933                 "\\\\?\\UNC\\server\\share\\",
3934                 true);
3935             tp!("\\\\?\\UNC\\server\\share",
3936                 "\\\\?\\UNC\\server\\share",
3937                 false);
3938             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3939             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3940             tp!("\\\\.\\a", "\\\\.\\a", false);
3941
3942             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3943         }
3944     }
3945
3946     #[test]
3947     pub fn test_set_file_name() {
3948         macro_rules! tfn(
3949                 ($path:expr, $file:expr, $expected:expr) => ( {
3950                 let mut p = PathBuf::from($path);
3951                 p.set_file_name($file);
3952                 assert!(p.to_str() == Some($expected),
3953                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3954                         $path, $file, $expected,
3955                         p.to_str().unwrap());
3956             });
3957         );
3958
3959         tfn!("foo", "foo", "foo");
3960         tfn!("foo", "bar", "bar");
3961         tfn!("foo", "", "");
3962         tfn!("", "foo", "foo");
3963         if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3964             tfn!(".", "foo", "./foo");
3965             tfn!("foo/", "bar", "bar");
3966             tfn!("foo/.", "bar", "bar");
3967             tfn!("..", "foo", "../foo");
3968             tfn!("foo/..", "bar", "foo/../bar");
3969             tfn!("/", "foo", "/foo");
3970         } else {
3971             tfn!(".", "foo", r".\foo");
3972             tfn!(r"foo\", "bar", r"bar");
3973             tfn!(r"foo\.", "bar", r"bar");
3974             tfn!("..", "foo", r"..\foo");
3975             tfn!(r"foo\..", "bar", r"foo\..\bar");
3976             tfn!(r"\", "foo", r"\foo");
3977         }
3978     }
3979
3980     #[test]
3981     pub fn test_set_extension() {
3982         macro_rules! tfe(
3983                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3984                 let mut p = PathBuf::from($path);
3985                 let output = p.set_extension($ext);
3986                 assert!(p.to_str() == Some($expected) && output == $output,
3987                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3988                         $path, $ext, $expected, $output,
3989                         p.to_str().unwrap(), output);
3990             });
3991         );
3992
3993         tfe!("foo", "txt", "foo.txt", true);
3994         tfe!("foo.bar", "txt", "foo.txt", true);
3995         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3996         tfe!(".test", "txt", ".test.txt", true);
3997         tfe!("foo.txt", "", "foo", true);
3998         tfe!("foo", "", "foo", true);
3999         tfe!("", "foo", "", false);
4000         tfe!(".", "foo", ".", false);
4001         tfe!("foo/", "bar", "foo.bar", true);
4002         tfe!("foo/.", "bar", "foo.bar", true);
4003         tfe!("..", "foo", "..", false);
4004         tfe!("foo/..", "bar", "foo/..", false);
4005         tfe!("/", "foo", "/", false);
4006     }
4007
4008     #[test]
4009     fn test_eq_receivers() {
4010         use crate::borrow::Cow;
4011
4012         let borrowed: &Path = Path::new("foo/bar");
4013         let mut owned: PathBuf = PathBuf::new();
4014         owned.push("foo");
4015         owned.push("bar");
4016         let borrowed_cow: Cow<Path> = borrowed.into();
4017         let owned_cow: Cow<Path> = owned.clone().into();
4018
4019         macro_rules! t {
4020             ($($current:expr),+) => {
4021                 $(
4022                     assert_eq!($current, borrowed);
4023                     assert_eq!($current, owned);
4024                     assert_eq!($current, borrowed_cow);
4025                     assert_eq!($current, owned_cow);
4026                 )+
4027             }
4028         }
4029
4030         t!(borrowed, owned, borrowed_cow, owned_cow);
4031     }
4032
4033     #[test]
4034     pub fn test_compare() {
4035         use crate::hash::{Hash, Hasher};
4036         use crate::collections::hash_map::DefaultHasher;
4037
4038         fn hash<T: Hash>(t: T) -> u64 {
4039             let mut s = DefaultHasher::new();
4040             t.hash(&mut s);
4041             s.finish()
4042         }
4043
4044         macro_rules! tc(
4045             ($path1:expr, $path2:expr, eq: $eq:expr,
4046              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4047              relative_from: $relative_from:expr) => ({
4048                  let path1 = Path::new($path1);
4049                  let path2 = Path::new($path2);
4050
4051                  let eq = path1 == path2;
4052                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4053                          $path1, $path2, $eq, eq);
4054                  assert!($eq == (hash(path1) == hash(path2)),
4055                          "{:?} == {:?}, expected {:?}, got {} and {}",
4056                          $path1, $path2, $eq, hash(path1), hash(path2));
4057
4058                  let starts_with = path1.starts_with(path2);
4059                  assert!(starts_with == $starts_with,
4060                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4061                          $starts_with, starts_with);
4062
4063                  let ends_with = path1.ends_with(path2);
4064                  assert!(ends_with == $ends_with,
4065                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4066                          $ends_with, ends_with);
4067
4068                  let relative_from = path1.strip_prefix(path2)
4069                                           .map(|p| p.to_str().unwrap())
4070                                           .ok();
4071                  let exp: Option<&str> = $relative_from;
4072                  assert!(relative_from == exp,
4073                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4074                          $path1, $path2, exp, relative_from);
4075             });
4076         );
4077
4078         tc!("", "",
4079             eq: true,
4080             starts_with: true,
4081             ends_with: true,
4082             relative_from: Some("")
4083             );
4084
4085         tc!("foo", "",
4086             eq: false,
4087             starts_with: true,
4088             ends_with: true,
4089             relative_from: Some("foo")
4090             );
4091
4092         tc!("", "foo",
4093             eq: false,
4094             starts_with: false,
4095             ends_with: false,
4096             relative_from: None
4097             );
4098
4099         tc!("foo", "foo",
4100             eq: true,
4101             starts_with: true,
4102             ends_with: true,
4103             relative_from: Some("")
4104             );
4105
4106         tc!("foo/", "foo",
4107             eq: true,
4108             starts_with: true,
4109             ends_with: true,
4110             relative_from: Some("")
4111             );
4112
4113         tc!("foo/bar", "foo",
4114             eq: false,
4115             starts_with: true,
4116             ends_with: false,
4117             relative_from: Some("bar")
4118             );
4119
4120         tc!("foo/bar/baz", "foo/bar",
4121             eq: false,
4122             starts_with: true,
4123             ends_with: false,
4124             relative_from: Some("baz")
4125             );
4126
4127         tc!("foo/bar", "foo/bar/baz",
4128             eq: false,
4129             starts_with: false,
4130             ends_with: false,
4131             relative_from: None
4132             );
4133
4134         tc!("./foo/bar/", ".",
4135             eq: false,
4136             starts_with: true,
4137             ends_with: false,
4138             relative_from: Some("foo/bar")
4139             );
4140
4141         if cfg!(windows) {
4142             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4143                 r"c:\src\rust\cargo-test\test",
4144                 eq: false,
4145                 starts_with: true,
4146                 ends_with: false,
4147                 relative_from: Some("Cargo.toml")
4148                 );
4149
4150             tc!(r"c:\foo", r"C:\foo",
4151                 eq: true,
4152                 starts_with: true,
4153                 ends_with: true,
4154                 relative_from: Some("")
4155                 );
4156         }
4157     }
4158
4159     #[test]
4160     fn test_components_debug() {
4161         let path = Path::new("/tmp");
4162
4163         let mut components = path.components();
4164
4165         let expected = "Components([RootDir, Normal(\"tmp\")])";
4166         let actual = format!("{:?}", components);
4167         assert_eq!(expected, actual);
4168
4169         let _ = components.next().unwrap();
4170         let expected = "Components([Normal(\"tmp\")])";
4171         let actual = format!("{:?}", components);
4172         assert_eq!(expected, actual);
4173
4174         let _ = components.next().unwrap();
4175         let expected = "Components([])";
4176         let actual = format!("{:?}", components);
4177         assert_eq!(expected, actual);
4178     }
4179
4180     #[cfg(unix)]
4181     #[test]
4182     fn test_iter_debug() {
4183         let path = Path::new("/tmp");
4184
4185         let mut iter = path.iter();
4186
4187         let expected = "Iter([\"/\", \"tmp\"])";
4188         let actual = format!("{:?}", iter);
4189         assert_eq!(expected, actual);
4190
4191         let _ = iter.next().unwrap();
4192         let expected = "Iter([\"tmp\"])";
4193         let actual = format!("{:?}", iter);
4194         assert_eq!(expected, actual);
4195
4196         let _ = iter.next().unwrap();
4197         let expected = "Iter([])";
4198         let actual = format!("{:?}", iter);
4199         assert_eq!(expected, actual);
4200     }
4201
4202     #[test]
4203     fn into_boxed() {
4204         let orig: &str = "some/sort/of/path";
4205         let path = Path::new(orig);
4206         let boxed: Box<Path> = Box::from(path);
4207         let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4208         assert_eq!(path, &*boxed);
4209         assert_eq!(&*boxed, &*path_buf);
4210         assert_eq!(&*path_buf, path);
4211     }
4212
4213     #[test]
4214     fn test_clone_into() {
4215         let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4216         let path = Path::new("short");
4217         path.clone_into(&mut path_buf);
4218         assert_eq!(path, path_buf);
4219         assert!(path_buf.into_os_string().capacity() >= 15);
4220     }
4221
4222     #[test]
4223     fn display_format_flags() {
4224         assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4225         assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4226     }
4227
4228     #[test]
4229     fn into_rc() {
4230         let orig = "hello/world";
4231         let path = Path::new(orig);
4232         let rc: Rc<Path> = Rc::from(path);
4233         let arc: Arc<Path> = Arc::from(path);
4234
4235         assert_eq!(&*rc, path);
4236         assert_eq!(&*arc, path);
4237
4238         let rc2: Rc<Path> = Rc::from(path.to_owned());
4239         let arc2: Arc<Path> = Arc::from(path.to_owned());
4240
4241         assert_eq!(&*rc2, path);
4242         assert_eq!(&*arc2, path);
4243     }
4244 }