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