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