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