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