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.
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.
11 //! Cross-platform path manipulation.
13 //! This module provides two types, `PathBuf` and `Path` (akin to `String` and
14 //! `str`), for working with paths abstractly. These types are thin wrappers
15 //! around `OsString` and `OsStr` respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
20 //! Path manipulation involves both parsing components from slices and building
23 //! To parse a path, you can create a `Path` slice from a `str`
24 //! slice and start asking questions:
27 //! use std::path::Path;
29 //! let path = Path::new("/tmp/foo/bar.txt");
30 //! let file = path.file_name();
31 //! let extension = path.extension();
32 //! let parent_dir = path.parent();
35 //! To build or modify paths, use `PathBuf`:
38 //! use std::path::PathBuf;
40 //! let mut path = PathBuf::new("c:\\");
41 //! path.push("windows");
42 //! path.push("system32");
43 //! path.set_extension("dll");
46 //! ## Path components and normalization
48 //! The path APIs are built around the notion of "components", which roughly
49 //! correspond to the substrings between path separators (`/` and, on Windows,
50 //! `\`). The APIs for path parsing are largely specified in terms of the path's
51 //! components, so it's important to clearly understand how those are determined.
53 //! A path can always be reconstructed into an equivalent path by putting
54 //! together its components via `push`. Syntactically, the paths may differ by
55 //! the normalization described below.
57 //! ### Component types
59 //! Components come in several types:
61 //! * Normal components are the default: standard references to files or
62 //! directories. The path `a/b` has two normal components, `a` and `b`.
64 //! * Current directory components represent the `.` character. For example,
65 //! `a/.` has a normal component `a` and a current directory component.
67 //! * The root directory component represents a separator that designates
68 //! starting from root. For example, `/a/b` has a root directory component
69 //! followed by normal components `a` and `b`.
71 //! On Windows, two additional component types come into play:
73 //! * Prefix components, of which there is a large variety. For example, `C:`
74 //! and `\\server\share` are prefixes. The path `C:windows` has a prefix
75 //! component `C:` and a normal component `windows`; the path `C:\windows` has a
76 //! prefix component `C:`, a root directory component, and a normal component
79 //! * Empty components, a special case for so-called "verbatim" paths where very
80 //! little normalization is allowed. For example, `\\?\C:\` has a "verbatim"
81 //! prefix `\\?\C:`, a root component, and an empty component (as a way of
82 //! representing the trailing `\`. Such a trailing `\` is in fact the only
83 //! situation in which an empty component is produced.
87 //! Aside from splitting on the separator(s), there is a small amount of
90 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
93 //! * Paths ending in a separator are treated as if they has a current directory
94 //! component at the end (or, in verbatim paths, an empty component). For
95 //! example, while `a/b` has components `a` and `b`, the paths `a/b/` and
96 //! `a/b/.` both have components `a`, `b`, and `.` (current directory). The
97 //! reason for this normalization is that `a/b` and `a/b/` are treated
98 //! differently in some contexts, but `a/b/` and `a/b/.` are always treated
101 //! No other normalization takes place by default. In particular, `a/./b/` and
102 //! `a/b` are treated distinctly in terms of components, as are `a/c` and
103 //! `a/b/../c`. Further normalization is possible to build on top of the
104 //! components APIs, and will be included in this library very soon.
106 #![unstable(feature = "path")]
108 use core::prelude::*;
111 use borrow::BorrowFrom;
115 use ops::{self, Deref};
116 use string::CowString;
120 use ffi::{OsStr, OsString, AsOsStr};
122 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
124 ////////////////////////////////////////////////////////////////////////////////
126 ////////////////////////////////////////////////////////////////////////////////
128 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
129 // taking advantage of the fact that OsStr always encodes ASCII characters
130 // as-is. Eventually, this transmutation should be replaced by direct uses of
131 // OsStr APIs for parsing, but it will take a while for those to become
134 ////////////////////////////////////////////////////////////////////////////////
135 // Platform-specific definitions
136 ////////////////////////////////////////////////////////////////////////////////
138 // The following modules give the most basic tools for parsing paths on various
139 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
144 use core::prelude::*;
148 pub fn is_sep_byte(b: u8) -> bool {
153 pub fn is_verbatim_sep(b: u8) -> bool {
157 pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
161 pub const MAIN_SEP_STR: &'static str = "/";
162 pub const MAIN_SEP: char = '/';
167 use core::prelude::*;
170 use char::CharExt as UnicodeCharExt;
171 use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
175 pub fn is_sep_byte(b: u8) -> bool {
176 b == b'/' || b == b'\\'
180 pub fn is_verbatim_sep(b: u8) -> bool {
184 pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
185 use super::Prefix::*;
187 // The unsafety here stems from converting between &OsStr and &[u8]
188 // and back. This is safe to do because (1) we only look at ASCII
189 // contents of the encoding and (2) new &OsStr values are produced
190 // only from ASCII-bounded slices of existing &OsStr values.
191 let mut path = os_str_as_u8_slice(path);
193 if path.starts_with(br"\\") {
196 if path.starts_with(br"?\") {
199 if path.starts_with(br"UNC\") {
200 // \\?\UNC\server\share
202 let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
203 Some((server, share)) => (u8_slice_as_os_str(server),
204 u8_slice_as_os_str(share)),
205 None => (u8_slice_as_os_str(path),
206 u8_slice_as_os_str(&[])),
208 return Some(VerbatimUNC(server, share));
211 let idx = path.position_elem(&b'\\');
212 if idx == Some(2) && path[1] == b':' {
214 if c.is_ascii() && (c as char).is_alphabetic() {
216 return Some(VerbatimDisk(c.to_ascii_uppercase()));
219 let slice = &path[.. idx.unwrap_or(path.len())];
220 return Some(Verbatim(u8_slice_as_os_str(slice)));
222 } else if path.starts_with(b".\\") {
225 let slice = &path[.. path.position_elem(&b'\\').unwrap_or(path.len())];
226 return Some(DeviceNS(u8_slice_as_os_str(slice)));
228 match parse_two_comps(path, is_sep_byte) {
229 Some((server, share)) if server.len() > 0 && share.len() > 0 => {
231 return Some(UNC(u8_slice_as_os_str(server),
232 u8_slice_as_os_str(share)));
236 } else if path.len() > 1 && path[1] == b':' {
239 if c.is_ascii() && (c as char).is_alphabetic() {
240 return Some(Disk(c.to_ascii_uppercase()));
246 fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
247 let first = match path.iter().position(|x| f(*x)) {
249 Some(x) => &path[.. x]
251 path = &path[(first.len()+1)..];
252 let idx = path.iter().position(|x| f(*x));
253 let second = &path[.. idx.unwrap_or(path.len())];
254 Some((first, second))
258 pub const MAIN_SEP_STR: &'static str = "\\";
259 pub const MAIN_SEP: char = '\\';
262 ////////////////////////////////////////////////////////////////////////////////
264 ////////////////////////////////////////////////////////////////////////////////
266 /// Path prefixes (Windows only).
268 /// Windows uses a variety of path styles, including references to drive
269 /// volumes (like `C:`), network shared (like `\\server\share`) and
270 /// others. In addition, some path prefixes are "verbatim", in which case
271 /// `/` is *not* treated as a separator and essentially no normalization is
273 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
274 pub enum Prefix<'a> {
275 /// Prefix `\\?\`, together with the given component immediately following it.
278 /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
279 VerbatimUNC(&'a OsStr, &'a OsStr),
281 /// Prefix like `\\?\C:\`, for the given drive letter
284 /// Prefix `\\.\`, together with the given component immediately following it.
287 /// Prefix `\\server\share`, with the given "server" and "share" components.
288 UNC(&'a OsStr, &'a OsStr),
290 /// Prefix `C:` for the given disk drive.
294 impl<'a> Prefix<'a> {
296 fn len(&self) -> usize {
298 fn os_str_len(s: &OsStr) -> usize {
299 os_str_as_u8_slice(s).len()
302 Verbatim(x) => 4 + os_str_len(x),
303 VerbatimUNC(x,y) => 8 + os_str_len(x) +
304 if os_str_len(y) > 0 { 1 + os_str_len(y) }
306 VerbatimDisk(_) => 6,
307 UNC(x,y) => 2 + os_str_len(x) +
308 if os_str_len(y) > 0 { 1 + os_str_len(y) }
310 DeviceNS(x) => 4 + os_str_len(x),
316 /// Determine if the prefix is verbatim, i.e. begins `\\?\`.
318 pub fn is_verbatim(&self) -> bool {
321 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
327 fn is_drive(&self) -> bool {
329 Prefix::Disk(_) => true,
335 fn has_implicit_root(&self) -> bool {
340 ////////////////////////////////////////////////////////////////////////////////
341 // Exposed parsing helpers
342 ////////////////////////////////////////////////////////////////////////////////
344 /// Determine whether the character is one of the permitted path
345 /// separators for the current platform.
346 pub fn is_separator(c: char) -> bool {
348 c.is_ascii() && is_sep_byte(c as u8)
351 /// The primary sperator for the current platform
352 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
354 ////////////////////////////////////////////////////////////////////////////////
356 ////////////////////////////////////////////////////////////////////////////////
358 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
359 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
360 // `iter` after having exhausted `prefix`.
361 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
362 I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
365 let mut iter_next = iter.clone();
366 match (iter_next.next(), prefix.next()) {
367 (Some(x), Some(y)) => {
368 if x != y { return None }
370 (Some(_), None) => return Some(iter),
371 (None, None) => return Some(iter),
372 (None, Some(_)) => return None,
378 // See note at the top of this module to understand why these are used:
379 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
380 unsafe { mem::transmute(s) }
382 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
386 ////////////////////////////////////////////////////////////////////////////////
387 // Cross-platform parsing
388 ////////////////////////////////////////////////////////////////////////////////
390 /// Says whether the path ends in a separator character and therefore needs to
391 /// be treated as if it ended with an additional `.`
392 fn has_suffix(s: &[u8], prefix: Option<Prefix>) -> bool {
393 let (prefix_len, verbatim) = if let Some(p) = prefix {
394 (p.len(), p.is_verbatim())
395 } else { (0, false) };
396 if prefix_len > 0 && prefix_len == s.len() && !verbatim { return true; }
397 let mut splits = s[prefix_len..].split(|b| is_sep_byte(*b));
398 let last = splits.next_back().unwrap();
399 let more = splits.next_back().is_some();
403 /// Says whether the first byte after the prefix is a separator.
404 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
405 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
406 path.len() > 0 && is_sep_byte(path[0])
409 fn parse_single_component(comp: &[u8]) -> Option<Component> {
411 b"." => Some(Component::CurDir),
412 b".." => Some(Component::ParentDir),
414 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) }))
418 // basic workhorse for splitting stem and extension
419 #[allow(unused_unsafe)] // FIXME
420 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
422 if os_str_as_u8_slice(file) == b".." { return (Some(file), None) }
424 // The unsafety here stems from converting between &OsStr and &[u8]
425 // and back. This is safe to do because (1) we only look at ASCII
426 // contents of the encoding and (2) new &OsStr values are produced
427 // only from ASCII-bounded slices of existing &OsStr values.
429 let mut iter = os_str_as_u8_slice(file).rsplitn(1, |b| *b == b'.');
430 let after = iter.next();
431 let before = iter.next();
432 if before == Some(b"") {
435 (before.map(|s| u8_slice_as_os_str(s)),
436 after.map(|s| u8_slice_as_os_str(s)))
441 ////////////////////////////////////////////////////////////////////////////////
442 // The core iterators
443 ////////////////////////////////////////////////////////////////////////////////
445 /// Component parsing works by a double-ended state machine; the cursors at the
446 /// front and back of the path each keep track of what parts of the path have
447 /// been consumed so far.
449 /// Going front to back, a path is made up of a prefix, a root component, a body
450 /// (of normal components), and a suffix/emptycomponent (normalized `.` or ``
451 /// for a path ending with the separator)
452 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
456 Body = 2, // foo/bar/baz
461 /// A single component of a path.
463 /// See the module documentation for an in-depth explanation of components and
464 /// their role in the API.
465 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
466 pub enum Component<'a> {
467 /// A Windows path prefix, e.g. `C:` or `\server\share`.
469 /// Does not occur on Unix.
471 /// The prefix as an unparsed `OsStr` slice.
474 /// The parsed prefix data.
478 /// An empty component. Only used on Windows for the last component of
479 /// verbatim paths ending with a separator (e.g. the last component of
480 /// `\\?\C:\windows\` but not `\\?\C:\windows` or `C:\windows`).
483 /// The root directory component, appears after any prefix and before anything else
486 /// A reference to the current directory, i.e. `.`
489 /// A reference to the parent directory, i.e. `..`
492 /// A normal component, i.e. `a` and `b` in `a/b`
496 impl<'a> Component<'a> {
497 /// Extract the underlying `OsStr` slice
498 pub fn as_os_str(self) -> &'a OsStr {
500 Component::Prefix { raw, .. } => &raw,
501 Component::Empty => OsStr::from_str(""),
502 Component::RootDir => OsStr::from_str(MAIN_SEP_STR),
503 Component::CurDir => OsStr::from_str("."),
504 Component::ParentDir => OsStr::from_str(".."),
505 Component::Normal(path) => path,
510 /// The core iterator giving the components of a path.
512 /// See the module documentation for an in-depth explanation of components and
513 /// their role in the API.
515 pub struct Components<'a> {
516 // The path left to parse components from
519 // The prefix as it was originally parsed, if any
520 prefix: Option<Prefix<'a>>,
522 // true if path *physically* has a root separator; for most Windows
523 // prefixes, it may have a "logical" rootseparator for the purposes of
524 // normalization, e.g. \\server\share == \\server\share\.
525 has_physical_root: bool,
527 // The iterator is double-ended, and these two states keep track of what has
528 // been produced from either end
533 /// An iterator over the components of a path, as `OsStr` slices.
535 pub struct Iter<'a> {
536 inner: Components<'a>
539 impl<'a> Components<'a> {
540 // how long is the prefix, if any?
542 fn prefix_len(&self) -> usize {
543 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
547 fn prefix_verbatim(&self) -> bool {
548 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
551 /// how much of the prefix is left from the point of view of iteration?
553 fn prefix_remaining(&self) -> usize {
554 if self.front == State::Prefix { self.prefix_len() }
558 fn prefix_and_root(&self) -> usize {
559 let root = if self.front <= State::Root && self.has_physical_root { 1 } else { 0 };
560 self.prefix_remaining() + root
563 // is the iteration complete?
565 fn finished(&self) -> bool {
566 self.front == State::Done || self.back == State::Done || self.front > self.back
570 fn is_sep_byte(&self, b: u8) -> bool {
571 if self.prefix_verbatim() {
578 /// Extract a slice corresponding to the portion of the path remaining for iteration.
579 pub fn as_path(&self) -> &'a Path {
580 let mut comps = self.clone();
581 if comps.front == State::Body { comps.trim_left(); }
582 if comps.back == State::Body { comps.trim_right(); }
583 if comps.path.is_empty() && comps.front < comps.back && comps.back == State::Suffix {
586 unsafe { Path::from_u8_slice(comps.path) }
590 /// Is the *original* path rooted?
591 fn has_root(&self) -> bool {
592 if self.has_physical_root { return true }
593 if let Some(p) = self.prefix {
594 if p.has_implicit_root() { return true }
599 // parse a component from the left, saying how many bytes to consume to
600 // remove the component
601 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
602 debug_assert!(self.front == State::Body);
603 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
604 None => (0, self.path),
605 Some(i) => (1, &self.path[.. i]),
607 (comp.len() + extra, parse_single_component(comp))
610 // parse a component from the right, saying how many bytes to consume to
611 // remove the component
612 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
613 debug_assert!(self.back == State::Body);
614 let start = self.prefix_and_root();
615 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
616 None => (0, &self.path[start ..]),
617 Some(i) => (1, &self.path[start + i + 1 ..]),
619 (comp.len() + extra, parse_single_component(comp))
622 // trim away repeated separators (i.e. emtpy components) on the left
623 fn trim_left(&mut self) {
624 while !self.path.is_empty() {
625 let (size, comp) = self.parse_next_component();
629 self.path = &self.path[size ..];
634 // trim away repeated separators (i.e. emtpy components) on the right
635 fn trim_right(&mut self) {
636 while self.path.len() > self.prefix_and_root() {
637 let (size, comp) = self.parse_next_component_back();
641 self.path = &self.path[.. self.path.len() - size];
646 /// Examine the next component without consuming it.
647 pub fn peek(&self) -> Option<Component<'a>> {
653 /// Extract a slice corresponding to the portion of the path remaining for iteration.
654 pub fn as_path(&self) -> &'a Path {
659 impl<'a> Iterator for Iter<'a> {
660 type Item = &'a OsStr;
662 fn next(&mut self) -> Option<&'a OsStr> {
663 self.inner.next().map(Component::as_os_str)
667 impl<'a> DoubleEndedIterator for Iter<'a> {
668 fn next_back(&mut self) -> Option<&'a OsStr> {
669 self.inner.next_back().map(Component::as_os_str)
673 impl<'a> Iterator for Components<'a> {
674 type Item = Component<'a>;
676 fn next(&mut self) -> Option<Component<'a>> {
677 while !self.finished() {
679 State::Prefix if self.prefix_len() > 0 => {
680 self.front = State::Root;
681 debug_assert!(self.prefix_len() <= self.path.len());
682 let raw = &self.path[.. self.prefix_len()];
683 self.path = &self.path[self.prefix_len() .. ];
684 return Some(Component::Prefix {
685 raw: unsafe { u8_slice_as_os_str(raw) },
686 parsed: self.prefix.unwrap()
690 self.front = State::Root;
693 self.front = State::Body;
694 if self.has_physical_root {
695 debug_assert!(self.path.len() > 0);
696 self.path = &self.path[1..];
697 return Some(Component::RootDir)
698 } else if let Some(p) = self.prefix {
699 if p.has_implicit_root() && !p.is_verbatim() {
700 return Some(Component::RootDir)
704 State::Body if !self.path.is_empty() => {
705 let (size, comp) = self.parse_next_component();
706 self.path = &self.path[size ..];
707 if comp.is_some() { return comp }
710 self.front = State::Suffix;
713 self.front = State::Done;
714 if self.prefix_verbatim() {
715 return Some(Component::Empty)
717 return Some(Component::CurDir)
720 State::Done => unreachable!()
727 impl<'a> DoubleEndedIterator for Components<'a> {
728 fn next_back(&mut self) -> Option<Component<'a>> {
729 while !self.finished() {
732 self.back = State::Body;
733 if self.prefix_verbatim() {
734 return Some(Component::Empty)
736 return Some(Component::CurDir)
739 State::Body if self.path.len() > self.prefix_and_root() => {
740 let (size, comp) = self.parse_next_component_back();
741 self.path = &self.path[.. self.path.len() - size];
742 if comp.is_some() { return comp }
745 self.back = State::Root;
748 self.back = State::Prefix;
749 if self.has_physical_root {
750 self.path = &self.path[.. self.path.len() - 1];
751 return Some(Component::RootDir)
752 } else if let Some(p) = self.prefix {
753 if p.has_implicit_root() && !p.is_verbatim() {
754 return Some(Component::RootDir)
758 State::Prefix if self.prefix_len() > 0 => {
759 self.back = State::Done;
760 return Some(Component::Prefix {
761 raw: unsafe { u8_slice_as_os_str(self.path) },
762 parsed: self.prefix.unwrap()
766 self.back = State::Done;
769 State::Done => unreachable!()
776 fn optional_path(path: &Path) -> Option<&Path> {
777 if path.as_u8_slice().is_empty() { None } else { Some(path) }
780 impl<'a> cmp::PartialEq for Components<'a> {
781 fn eq(&self, other: &Components<'a>) -> bool {
782 iter::order::eq(self.clone(), other.clone())
786 impl<'a> cmp::Eq for Components<'a> {}
788 impl<'a> cmp::PartialOrd for Components<'a> {
789 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
790 iter::order::partial_cmp(self.clone(), other.clone())
794 impl<'a> cmp::Ord for Components<'a> {
795 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
796 iter::order::cmp(self.clone(), other.clone())
800 ////////////////////////////////////////////////////////////////////////////////
801 // Basic types and traits
802 ////////////////////////////////////////////////////////////////////////////////
804 /// An owned, mutable path (akin to `String`).
806 /// This type provides methods like `push` and `set_extension` that mutate the
807 /// path in place. It also implements `Deref` to `Path`, meaning that all
808 /// methods on `Path` slices are available on `PathBuf` values as well.
810 /// More details about the overall approach can be found in
811 /// the module documentation.
816 /// use std::path::PathBuf;
818 /// let mut path = PathBuf::new("c:\\");
819 /// path.push("windows");
820 /// path.push("system32");
821 /// path.set_extension("dll");
823 #[derive(Clone, Hash)]
829 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
830 unsafe { mem::transmute(self) }
833 /// Allocate a `PathBuf` with initial contents given by the
835 pub fn new<S: ?Sized + AsOsStr>(s: &S) -> PathBuf {
836 PathBuf { inner: s.as_os_str().to_os_string() }
839 /// Extend `self` with `path`.
841 /// If `path` is absolute, it replaces the current path.
845 /// * if `path` has a root but no prefix (e.g. `\windows`), it
846 /// replaces everything except for the prefix (if any) of `self`.
847 /// * if `path` has a prefix but no root, it replaces `self.
848 pub fn push<P: ?Sized>(&mut self, path: &P) where P: AsPath {
849 // in general, a separator is needed if the rightmost byte is not a separator
850 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
852 // in the special case of `C:` on Windows, do *not* add a separator
854 let comps = self.components();
855 if comps.prefix_len() > 0 &&
856 comps.prefix_len() == comps.path.len() &&
857 comps.prefix.unwrap().is_drive()
863 let path = path.as_path();
865 // absolute `path` replaces `self`
866 if path.is_absolute() || path.prefix().is_some() {
867 self.as_mut_vec().truncate(0);
869 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
870 } else if path.has_root() {
871 let prefix_len = self.components().prefix_remaining();
872 self.as_mut_vec().truncate(prefix_len);
874 // `path` is a pure relative path
876 self.inner.push_os_str(OsStr::from_str(MAIN_SEP_STR));
879 self.inner.push_os_str(path.as_os_str());
882 /// Truncate `self` to `self.parent()`.
884 /// Returns `false` and does nothing if `self.parent()` is `None`.
885 /// Otherwise, returns `true`.
886 pub fn pop(&mut self) -> bool {
887 match self.parent().map(|p| p.as_u8_slice().len()) {
889 self.as_mut_vec().truncate(len);
896 /// Updates `self.file_name()` to `file_name`.
898 /// If `self.file_name()` was `None`, this is equivalent to pushing
904 /// use std::path::{Path, PathBuf};
906 /// let mut buf = PathBuf::new("/foo/");
907 /// assert!(buf.file_name() == None);
908 /// buf.set_file_name("bar");
909 /// assert!(buf == PathBuf::new("/foo/bar"));
910 /// assert!(buf.file_name().is_some());
911 /// buf.set_file_name("baz.txt");
912 /// assert!(buf == PathBuf::new("/foo/baz.txt"));
914 pub fn set_file_name<S: ?Sized>(&mut self, file_name: &S) where S: AsOsStr {
915 if self.file_name().is_some() && !self.pop() {
916 // Given that there is a file name, this is reachable only for
917 // Windows paths like c:file or paths like `foo`, but not `c:\` or
919 let prefix_len = self.components().prefix_remaining();
920 self.as_mut_vec().truncate(prefix_len);
922 self.push(file_name.as_os_str());
925 /// Updates `self.extension()` to `extension`.
927 /// If `self.file_name()` is `None`, does nothing and returns `false`.
929 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
930 /// is added; otherwise it is replaced.
931 pub fn set_extension<S: ?Sized + AsOsStr>(&mut self, extension: &S) -> bool {
932 if self.file_name().is_none() { return false; }
934 let mut stem = match self.file_stem() {
935 Some(stem) => stem.to_os_string(),
936 None => OsString::from_str(""),
939 let extension = extension.as_os_str();
940 if os_str_as_u8_slice(extension).len() > 0 {
941 stem.push_os_str(OsStr::from_str("."));
942 stem.push_os_str(extension.as_os_str());
944 self.set_file_name(&stem);
949 /// Consume the `PathBuf`, yielding its internal `OsString` storage
950 pub fn into_os_string(self) -> OsString {
955 impl<'a, P: ?Sized + 'a> iter::FromIterator<&'a P> for PathBuf where P: AsPath {
956 fn from_iter<I: Iterator<Item = &'a P>>(iter: I) -> PathBuf {
957 let mut buf = PathBuf::new("");
963 impl<'a, P: ?Sized + 'a> iter::Extend<&'a P> for PathBuf where P: AsPath {
964 fn extend<I: Iterator<Item = &'a P>>(&mut self, iter: I) {
971 impl fmt::Debug for PathBuf {
972 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
973 fmt::Debug::fmt(&**self, formatter)
977 impl ops::Deref for PathBuf {
980 fn deref(&self) -> &Path {
981 unsafe { mem::transmute(&self.inner[]) }
985 impl BorrowFrom<PathBuf> for Path {
986 fn borrow_from(owned: &PathBuf) -> &Path {
991 impl cmp::PartialEq for PathBuf {
992 fn eq(&self, other: &PathBuf) -> bool {
993 self.components() == other.components()
997 impl cmp::Eq for PathBuf {}
999 impl cmp::PartialOrd for PathBuf {
1000 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1001 self.components().partial_cmp(&other.components())
1005 impl cmp::Ord for PathBuf {
1006 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1007 self.components().cmp(&other.components())
1011 impl AsOsStr for PathBuf {
1012 fn as_os_str(&self) -> &OsStr {
1017 /// A slice of a path (akin to `str`).
1019 /// This type supports a number of operations for inspecting a path, including
1020 /// breaking the path into its components (separated by `/` or `\`, depending on
1021 /// the platform), extracting the file name, determining whether the path is
1022 /// absolute, and so on. More details about the overall approach can be found in
1023 /// the module documentation.
1025 /// This is an *unsized* type, meaning that it must always be used with behind a
1026 /// pointer like `&` or `Box`.
1031 /// use std::path::Path;
1033 /// let path = Path::new("/tmp/foo/bar.txt");
1034 /// let file = path.file_name();
1035 /// let extension = path.extension();
1036 /// let parent_dir = path.parent();
1045 // The following (private!) function allows construction of a path from a u8
1046 // slice, which is only safe when it is known to follow the OsStr encoding.
1047 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1050 // The following (private!) function reveals the byte encoding used for OsStr.
1051 fn as_u8_slice(&self) -> &[u8] {
1052 unsafe { mem::transmute(self) }
1055 /// Directly wrap a string slice as a `Path` slice.
1057 /// This is a cost-free conversion.
1058 pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path {
1059 unsafe { mem::transmute(s.as_os_str()) }
1062 /// Yield a `&str` slice if the `Path` is valid unicode.
1064 /// This conversion may entail doing a check for UTF-8 validity.
1065 pub fn to_str(&self) -> Option<&str> {
1069 /// Convert a `Path` to a `CowString`.
1071 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1072 pub fn to_string_lossy(&self) -> CowString {
1073 self.inner.to_string_lossy()
1076 /// Convert a `Path` to an owned `PathBuf`.
1077 pub fn to_path_buf(&self) -> PathBuf {
1081 /// A path is *absolute* if it is independent of the current directory.
1083 /// * On Unix, a path is absolute if it starts with the root, so
1084 /// `is_absolute` and `has_root` are equivalent.
1086 /// * On Windows, a path is absolute if it has a prefix and starts with the
1087 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1088 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1089 pub fn is_absolute(&self) -> bool {
1091 (cfg!(unix) || self.prefix().is_some())
1094 /// A path is *relative* if it is not absolute.
1095 pub fn is_relative(&self) -> bool {
1099 /// Returns the *prefix* of a path, if any.
1101 /// Prefixes are relevant only for Windows paths, and consist of volumes
1102 /// like `C:`, UNC prefixes like `\\server`, and others described in more
1103 /// detail in `std::os::windows::PathExt`.
1104 pub fn prefix(&self) -> Option<&Path> {
1105 let iter = self.components();
1106 optional_path(unsafe {
1107 Path::from_u8_slice(
1108 &self.as_u8_slice()[.. iter.prefix_remaining()])
1112 /// A path has a root if the body of the path begins with the directory separator.
1114 /// * On Unix, a path has a root if it begins with `/`.
1116 /// * On Windows, a path has a root if it:
1117 /// * has no prefix and begins with a separator, e.g. `\\windows`
1118 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1119 /// * has any non-disk prefix, e.g. `\\server\share`
1120 pub fn has_root(&self) -> bool {
1121 self.components().has_root()
1124 /// The path without its final component.
1126 /// Does nothing, returning `None` if the path consists of just a prefix
1127 /// and/or root directory reference.
1132 /// use std::path::Path;
1134 /// let path = Path::new("/foo/bar");
1135 /// let foo = path.parent().unwrap();
1136 /// assert!(foo == Path::new("/foo"));
1137 /// let root = foo.parent().unwrap();
1138 /// assert!(root == Path::new("/"));
1139 /// assert!(root.parent() == None);
1141 pub fn parent(&self) -> Option<&Path> {
1142 let mut comps = self.components();
1143 let comp = comps.next_back();
1144 let rest = optional_path(comps.as_path());
1146 match (comp, comps.next_back()) {
1147 (Some(Component::CurDir), Some(Component::RootDir)) => None,
1148 (Some(Component::CurDir), Some(Component::Prefix { .. })) => None,
1149 (Some(Component::Empty), Some(Component::RootDir)) => None,
1150 (Some(Component::Empty), Some(Component::Prefix { .. })) => None,
1151 (Some(Component::Prefix { .. }), None) => None,
1152 (Some(Component::RootDir), Some(Component::Prefix { .. })) => None,
1157 /// The final component of the path, if it is a normal file.
1159 /// If the path terminates in `.`, `..`, or consists solely or a root of
1160 /// prefix, `file` will return `None`.
1161 pub fn file_name(&self) -> Option<&OsStr> {
1162 self.components().next_back().and_then(|p| match p {
1163 Component::Normal(p) => Some(p.as_os_str()),
1168 /// Returns a path that, when joined onto `base`, yields `self`.
1169 pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where
1172 iter_after(self.components(), base.as_path().components()).map(|c| c.as_path())
1175 /// Determines whether `base` is a prefix of `self`.
1176 pub fn starts_with<P: ?Sized>(&self, base: &P) -> bool where P: AsPath {
1177 iter_after(self.components(), base.as_path().components()).is_some()
1180 /// Determines whether `base` is a suffix of `self`.
1181 pub fn ends_with<P: ?Sized>(&self, child: &P) -> bool where P: AsPath {
1182 iter_after(self.components().rev(), child.as_path().components().rev()).is_some()
1185 /// Extract the stem (non-extension) portion of `self.file()`.
1189 /// * None, if there is no file name;
1190 /// * The entire file name if there is no embedded `.`;
1191 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1192 /// * Otherwise, the portion of the file name before the final `.`
1193 pub fn file_stem(&self) -> Option<&OsStr> {
1194 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1197 /// Extract the extension of `self.file()`, if possible.
1199 /// The extension is:
1201 /// * None, if there is no file name;
1202 /// * None, if there is no embedded `.`;
1203 /// * None, if the file name begins with `.` and has no other `.`s within;
1204 /// * Otherwise, the portion of the file name after the final `.`
1205 pub fn extension(&self) -> Option<&OsStr> {
1206 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1209 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1211 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1212 pub fn join<P: ?Sized>(&self, path: &P) -> PathBuf where P: AsPath {
1213 let mut buf = self.to_path_buf();
1218 /// Creates an owned `PathBuf` like `self` but with the given file name.
1220 /// See `PathBuf::set_file_name` for more details.
1221 pub fn with_file_name<S: ?Sized>(&self, file_name: &S) -> PathBuf where S: AsOsStr {
1222 let mut buf = self.to_path_buf();
1223 buf.set_file_name(file_name);
1227 /// Creates an owned `PathBuf` like `self` but with the given extension.
1229 /// See `PathBuf::set_extension` for more details.
1230 pub fn with_extension<S: ?Sized>(&self, extension: &S) -> PathBuf where S: AsOsStr {
1231 let mut buf = self.to_path_buf();
1232 buf.set_extension(extension);
1236 /// Produce an iterator over the components of the path.
1237 pub fn components(&self) -> Components {
1238 let prefix = parse_prefix(self.as_os_str());
1240 path: self.as_u8_slice(),
1242 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1243 front: State::Prefix,
1244 back: if has_suffix(self.as_u8_slice(), prefix) { State::Suffix }
1245 else { State::Body },
1249 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1250 pub fn iter(&self) -> Iter {
1251 Iter { inner: self.components() }
1254 /// Returns an object that implements `Display` for safely printing paths
1255 /// that may contain non-Unicode data.
1256 pub fn display(&self) -> Display {
1257 Display { path: self }
1261 impl AsOsStr for Path {
1262 fn as_os_str(&self) -> &OsStr {
1267 impl fmt::Debug for Path {
1268 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1269 self.inner.fmt(formatter)
1273 /// Helper struct for safely printing paths with `format!()` and `{}`
1274 pub struct Display<'a> {
1278 impl<'a> fmt::Debug for Display<'a> {
1279 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1280 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1284 impl<'a> fmt::Display for Display<'a> {
1285 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1286 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1290 impl cmp::PartialEq for Path {
1291 fn eq(&self, other: &Path) -> bool {
1292 iter::order::eq(self.components(), other.components())
1296 impl cmp::Eq for Path {}
1298 impl cmp::PartialOrd for Path {
1299 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1300 self.components().partial_cmp(&other.components())
1304 impl cmp::Ord for Path {
1305 fn cmp(&self, other: &Path) -> cmp::Ordering {
1306 self.components().cmp(&other.components())
1310 /// Freely convertible to a `Path`.
1312 /// Convert to a `Path`.
1313 fn as_path(&self) -> &Path;
1316 impl<T: AsOsStr + ?Sized> AsPath for T {
1317 fn as_path(&self) -> &Path { Path::new(self.as_os_str()) }
1324 use core::prelude::*;
1325 use string::{ToString, String};
1329 ($path:expr, iter: $iter:expr) => (
1331 let path = Path::new($path);
1333 // Forward iteration
1334 let comps = path.iter()
1335 .map(|p| p.to_string_lossy().into_owned())
1336 .collect::<Vec<String>>();
1337 let exp: &[&str] = &$iter;
1338 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
1339 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
1342 // Reverse iteration
1343 let comps = Path::new($path).iter().rev()
1344 .map(|p| p.to_string_lossy().into_owned())
1345 .collect::<Vec<String>>();
1346 let exps = exps.into_iter().rev().collect::<Vec<String>>();
1347 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
1352 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
1354 let path = Path::new($path);
1356 let act_root = path.has_root();
1357 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
1358 $has_root, act_root);
1360 let act_abs = path.is_absolute();
1361 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
1362 $is_absolute, act_abs);
1366 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
1368 let path = Path::new($path);
1370 let parent = path.parent().map(|p| p.to_str().unwrap());
1371 let exp_parent: Option<&str> = $parent;
1372 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
1373 exp_parent, parent);
1375 let file = path.file_name().map(|p| p.to_str().unwrap());
1376 let exp_file: Option<&str> = $file;
1377 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
1382 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
1384 let path = Path::new($path);
1386 let stem = path.file_stem().map(|p| p.to_str().unwrap());
1387 let exp_stem: Option<&str> = $file_stem;
1388 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
1391 let ext = path.extension().map(|p| p.to_str().unwrap());
1392 let exp_ext: Option<&str> = $extension;
1393 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
1398 ($path:expr, iter: $iter:expr,
1399 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
1400 parent: $parent:expr, file_name: $file:expr,
1401 file_stem: $file_stem:expr, extension: $extension:expr) => (
1403 t!($path, iter: $iter);
1404 t!($path, has_root: $has_root, is_absolute: $is_absolute);
1405 t!($path, parent: $parent, file_name: $file);
1406 t!($path, file_stem: $file_stem, extension: $extension);
1413 pub fn test_decompositions_unix() {
1429 file_name: Some("foo"),
1430 file_stem: Some("foo"),
1449 file_name: Some("foo"),
1450 file_stem: Some("foo"),
1458 parent: Some("foo"),
1465 iter: ["/", "foo", "."],
1468 parent: Some("/foo"),
1475 iter: ["foo", "bar"],
1478 parent: Some("foo"),
1479 file_name: Some("bar"),
1480 file_stem: Some("bar"),
1485 iter: ["/", "foo", "bar"],
1488 parent: Some("/foo"),
1489 file_name: Some("bar"),
1490 file_stem: Some("bar"),
1495 iter: ["/", "foo", "."],
1498 parent: Some("///foo"),
1505 iter: ["/", "foo", "bar"],
1508 parent: Some("///foo"),
1509 file_name: Some("bar"),
1510 file_stem: Some("bar"),
1558 parent: Some("foo"),
1565 iter: ["foo", ".."],
1568 parent: Some("foo"),
1575 iter: ["foo", ".", "."],
1578 parent: Some("foo/."),
1585 iter: ["foo", ".", "bar"],
1588 parent: Some("foo/."),
1589 file_name: Some("bar"),
1590 file_stem: Some("bar"),
1595 iter: ["foo", "..", "."],
1598 parent: Some("foo/.."),
1605 iter: ["foo", "..", "bar"],
1608 parent: Some("foo/.."),
1609 file_name: Some("bar"),
1610 file_stem: Some("bar"),
1619 file_name: Some("a"),
1620 file_stem: Some("a"),
1649 file_name: Some("b"),
1650 file_stem: Some("b"),
1659 file_name: Some("b"),
1660 file_stem: Some("b"),
1665 iter: ["a", ".", "b"],
1668 parent: Some("a/."),
1669 file_name: Some("b"),
1670 file_stem: Some("b"),
1675 iter: ["a", "b", "c"],
1678 parent: Some("a/b"),
1679 file_name: Some("c"),
1680 file_stem: Some("c"),
1687 pub fn test_decompositions_windows() {
1703 file_name: Some("foo"),
1704 file_stem: Some("foo"),
1739 iter: ["c:", "\\", "."],
1749 iter: ["c:", "\\", "."],
1759 iter: ["c:", "\\", "."],
1769 iter: ["\\", "foo"],
1773 file_name: Some("foo"),
1774 file_stem: Some("foo"),
1782 parent: Some("foo"),
1789 iter: ["\\", "foo", "."],
1792 parent: Some("/foo"),
1799 iter: ["foo", "bar"],
1802 parent: Some("foo"),
1803 file_name: Some("bar"),
1804 file_stem: Some("bar"),
1809 iter: ["\\", "foo", "bar"],
1812 parent: Some("/foo"),
1813 file_name: Some("bar"),
1814 file_stem: Some("bar"),
1819 iter: ["\\", "foo", "."],
1822 parent: Some("///foo"),
1829 iter: ["\\", "foo", "bar"],
1832 parent: Some("///foo"),
1833 file_name: Some("bar"),
1834 file_stem: Some("bar"),
1882 parent: Some("foo"),
1889 iter: ["foo", ".."],
1892 parent: Some("foo"),
1899 iter: ["foo", ".", "."],
1902 parent: Some("foo/."),
1909 iter: ["foo", ".", "bar"],
1912 parent: Some("foo/."),
1913 file_name: Some("bar"),
1914 file_stem: Some("bar"),
1919 iter: ["foo", "..", "."],
1922 parent: Some("foo/.."),
1929 iter: ["foo", "..", "bar"],
1932 parent: Some("foo/.."),
1933 file_name: Some("bar"),
1934 file_stem: Some("bar"),
1943 file_name: Some("a"),
1944 file_stem: Some("a"),
1973 file_name: Some("b"),
1974 file_stem: Some("b"),
1983 file_name: Some("b"),
1984 file_stem: Some("b"),
1989 iter: ["a", ".", "b"],
1992 parent: Some("a/."),
1993 file_name: Some("b"),
1994 file_stem: Some("b"),
1999 iter: ["a", "b", "c"],
2002 parent: Some("a/b"),
2003 file_name: Some("c"),
2004 file_stem: Some("c"),
2008 iter: ["a", "b", "c"],
2011 parent: Some("a\\b"),
2012 file_name: Some("c"),
2013 file_stem: Some("c"),
2022 file_name: Some("a"),
2023 file_stem: Some("a"),
2028 iter: ["c:", "\\", "foo.txt"],
2031 parent: Some("c:\\"),
2032 file_name: Some("foo.txt"),
2033 file_stem: Some("foo"),
2034 extension: Some("txt")
2037 t!("\\\\server\\share\\foo.txt",
2038 iter: ["\\\\server\\share", "\\", "foo.txt"],
2041 parent: Some("\\\\server\\share\\"),
2042 file_name: Some("foo.txt"),
2043 file_stem: Some("foo"),
2044 extension: Some("txt")
2047 t!("\\\\server\\share",
2048 iter: ["\\\\server\\share", "\\", "."],
2058 iter: ["\\", "server"],
2062 file_name: Some("server"),
2063 file_stem: Some("server"),
2067 t!("\\\\?\\bar\\foo.txt",
2068 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2071 parent: Some("\\\\?\\bar\\"),
2072 file_name: Some("foo.txt"),
2073 file_stem: Some("foo"),
2074 extension: Some("txt")
2078 iter: ["\\\\?\\bar"],
2097 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2098 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2101 parent: Some("\\\\?\\UNC\\server\\share\\"),
2102 file_name: Some("foo.txt"),
2103 file_stem: Some("foo"),
2104 extension: Some("txt")
2107 t!("\\\\?\\UNC\\server",
2108 iter: ["\\\\?\\UNC\\server"],
2118 iter: ["\\\\?\\UNC\\"],
2127 t!("\\\\?\\C:\\foo.txt",
2128 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2131 parent: Some("\\\\?\\C:\\"),
2132 file_name: Some("foo.txt"),
2133 file_stem: Some("foo"),
2134 extension: Some("txt")
2139 iter: ["\\\\?\\C:", "\\", ""],
2150 iter: ["\\\\?\\C:"],
2160 t!("\\\\?\\foo/bar",
2161 iter: ["\\\\?\\foo/bar"],
2172 iter: ["\\\\?\\C:/foo"],
2182 t!("\\\\.\\foo\\bar",
2183 iter: ["\\\\.\\foo", "\\", "bar"],
2186 parent: Some("\\\\.\\foo\\"),
2187 file_name: Some("bar"),
2188 file_stem: Some("bar"),
2194 iter: ["\\\\.\\foo", "\\", "."],
2204 t!("\\\\.\\foo/bar",
2205 iter: ["\\\\.\\foo/bar", "\\", "."],
2215 t!("\\\\.\\foo\\bar/baz",
2216 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2219 parent: Some("\\\\.\\foo\\bar"),
2220 file_name: Some("baz"),
2221 file_stem: Some("baz"),
2227 iter: ["\\\\.\\", "\\", "."],
2237 iter: ["\\\\?\\a", "\\", "b", ""],
2240 parent: Some("\\\\?\\a\\b"),
2248 pub fn test_stem_ext() {
2250 file_stem: Some("foo"),
2255 file_stem: Some("foo"),
2260 file_stem: Some(".foo"),
2265 file_stem: Some("foo"),
2266 extension: Some("txt")
2270 file_stem: Some("foo.bar"),
2271 extension: Some("txt")
2275 file_stem: Some("foo.bar"),
2296 pub fn test_push() {
2298 ($path:expr, $push:expr, $expected:expr) => ( {
2299 let mut actual = PathBuf::new($path);
2301 assert!(actual.to_str() == Some($expected),
2302 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
2303 $push, $path, $expected, actual.to_str().unwrap());
2308 tp!("", "foo", "foo");
2309 tp!("foo", "bar", "foo/bar");
2310 tp!("foo/", "bar", "foo/bar");
2311 tp!("foo//", "bar", "foo//bar");
2312 tp!("foo/.", "bar", "foo/./bar");
2313 tp!("foo./.", "bar", "foo././bar");
2314 tp!("foo", "", "foo/");
2315 tp!("foo", ".", "foo/.");
2316 tp!("foo", "..", "foo/..");
2317 tp!("foo", "/", "/");
2318 tp!("/foo/bar", "/", "/");
2319 tp!("/foo/bar", "/baz", "/baz");
2320 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
2322 tp!("", "foo", "foo");
2323 tp!("foo", "bar", r"foo\bar");
2324 tp!("foo/", "bar", r"foo/bar");
2325 tp!(r"foo\", "bar", r"foo\bar");
2326 tp!("foo//", "bar", r"foo//bar");
2327 tp!(r"foo\\", "bar", r"foo\\bar");
2328 tp!("foo/.", "bar", r"foo/.\bar");
2329 tp!("foo./.", "bar", r"foo./.\bar");
2330 tp!(r"foo\.", "bar", r"foo\.\bar");
2331 tp!(r"foo.\.", "bar", r"foo.\.\bar");
2332 tp!("foo", "", "foo\\");
2333 tp!("foo", ".", r"foo\.");
2334 tp!("foo", "..", r"foo\..");
2335 tp!("foo", "/", "/");
2336 tp!("foo", r"\", r"\");
2337 tp!("/foo/bar", "/", "/");
2338 tp!(r"\foo\bar", r"\", r"\");
2339 tp!("/foo/bar", "/baz", "/baz");
2340 tp!("/foo/bar", r"\baz", r"\baz");
2341 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
2342 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
2344 tp!("c:\\", "windows", "c:\\windows");
2345 tp!("c:", "windows", "c:windows");
2347 tp!("a\\b\\c", "d", "a\\b\\c\\d");
2348 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
2349 tp!("a\\b", "c\\d", "a\\b\\c\\d");
2350 tp!("a\\b", "\\c\\d", "\\c\\d");
2351 tp!("a\\b", ".", "a\\b\\.");
2352 tp!("a\\b", "..\\c", "a\\b\\..\\c");
2353 tp!("a\\b", "C:a.txt", "C:a.txt");
2354 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
2355 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
2356 tp!("C:\\a\\b\\c", "C:d", "C:d");
2357 tp!("C:a\\b\\c", "C:d", "C:d");
2358 tp!("C:", r"a\b\c", r"C:a\b\c");
2359 tp!("C:", r"..\a", r"C:..\a");
2360 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
2361 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
2362 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
2363 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
2364 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
2365 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
2366 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
2367 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
2368 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
2370 // Note: modified from old path API
2371 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
2373 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
2374 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
2375 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
2376 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
2377 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
2379 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
2386 ($path:expr, $expected:expr, $output:expr) => ( {
2387 let mut actual = PathBuf::new($path);
2388 let output = actual.pop();
2389 assert!(actual.to_str() == Some($expected) && output == $output,
2390 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2391 $path, $expected, $output,
2392 actual.to_str().unwrap(), output);
2397 tp!("/", "/", false);
2398 tp!("foo", "foo", false);
2399 tp!(".", ".", false);
2400 tp!("/foo", "/", true);
2401 tp!("/foo/bar", "/foo", true);
2402 tp!("foo/bar", "foo", true);
2403 tp!("foo/.", "foo", true);
2404 tp!("foo//bar", "foo", true);
2407 tp!("a\\b\\c", "a\\b", true);
2408 tp!("\\a", "\\", true);
2409 tp!("\\", "\\", false);
2411 tp!("C:\\a\\b", "C:\\a", true);
2412 tp!("C:\\a", "C:\\", true);
2413 tp!("C:\\", "C:\\", false);
2414 tp!("C:a\\b", "C:a", true);
2415 tp!("C:a", "C:", true);
2416 tp!("C:", "C:", false);
2417 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
2418 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
2419 tp!("\\\\server\\share", "\\\\server\\share", false);
2420 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
2421 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
2422 tp!("\\\\?\\a", "\\\\?\\a", false);
2423 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
2424 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
2425 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
2426 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
2427 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
2428 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
2429 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
2430 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
2431 tp!("\\\\.\\a", "\\\\.\\a", false);
2433 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\b", true);
2438 pub fn test_set_file_name() {
2440 ($path:expr, $file:expr, $expected:expr) => ( {
2441 let mut p = PathBuf::new($path);
2442 p.set_file_name($file);
2443 assert!(p.to_str() == Some($expected),
2444 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
2445 $path, $file, $expected,
2446 p.to_str().unwrap());
2450 tfn!("foo", "foo", "foo");
2451 tfn!("foo", "bar", "bar");
2452 tfn!("foo", "", "");
2453 tfn!("", "foo", "foo");
2455 tfn!(".", "foo", "./foo");
2456 tfn!("foo/", "bar", "foo/bar");
2457 tfn!("foo/.", "bar", "foo/./bar");
2458 tfn!("..", "foo", "../foo");
2459 tfn!("foo/..", "bar", "foo/../bar");
2460 tfn!("/", "foo", "/foo");
2462 tfn!(".", "foo", r".\foo");
2463 tfn!(r"foo\", "bar", r"foo\bar");
2464 tfn!(r"foo\.", "bar", r"foo\.\bar");
2465 tfn!("..", "foo", r"..\foo");
2466 tfn!(r"foo\..", "bar", r"foo\..\bar");
2467 tfn!(r"\", "foo", r"\foo");
2472 pub fn test_set_extension() {
2474 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
2475 let mut p = PathBuf::new($path);
2476 let output = p.set_extension($ext);
2477 assert!(p.to_str() == Some($expected) && output == $output,
2478 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2479 $path, $ext, $expected, $output,
2480 p.to_str().unwrap(), output);
2484 tfe!("foo", "txt", "foo.txt", true);
2485 tfe!("foo.bar", "txt", "foo.txt", true);
2486 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
2487 tfe!(".test", "txt", ".test.txt", true);
2488 tfe!("foo.txt", "", "foo", true);
2489 tfe!("foo", "", "foo", true);
2490 tfe!("", "foo", "", false);
2491 tfe!(".", "foo", ".", false);
2492 tfe!("foo/", "bar", "foo/", false);
2493 tfe!("foo/.", "bar", "foo/.", false);
2494 tfe!("..", "foo", "..", false);
2495 tfe!("foo/..", "bar", "foo/..", false);
2496 tfe!("/", "foo", "/", false);
2500 pub fn test_compare() {
2502 ($path1:expr, $path2:expr, eq: $eq:expr,
2503 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
2504 relative_from: $relative_from:expr) => ({
2505 let path1 = Path::new($path1);
2506 let path2 = Path::new($path2);
2508 let eq = path1 == path2;
2509 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
2510 $path1, $path2, $eq, eq);
2512 let starts_with = path1.starts_with(path2);
2513 assert!(starts_with == $starts_with,
2514 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2515 $starts_with, starts_with);
2517 let ends_with = path1.ends_with(path2);
2518 assert!(ends_with == $ends_with,
2519 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2520 $ends_with, ends_with);
2522 let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
2523 let exp: Option<&str> = $relative_from;
2524 assert!(relative_from == exp,
2525 "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
2526 exp, relative_from);
2534 relative_from: Some("")
2541 relative_from: Some("foo")
2555 relative_from: Some("")
2562 relative_from: Some(".")
2565 tc!("foo/bar", "foo",
2569 relative_from: Some("bar")
2572 tc!("foo/bar/baz", "foo/bar",
2576 relative_from: Some("baz")
2579 tc!("foo/bar", "foo/bar/baz",
2586 tc!("./foo/bar/", ".",
2590 relative_from: Some("foo/bar/")