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