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