1 //! Cross-platform path manipulation.
3 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
4 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
5 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
6 //! on strings according to the local platform's path syntax.
8 //! Paths can be parsed into [`Component`]s by iterating over the structure
9 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
10 //! correspond to the substrings between path separators (`/` or `\`). You can
11 //! reconstruct an equivalent path from components with the [`push`] method on
12 //! [`PathBuf`]; note that the paths may differ syntactically by the
13 //! normalization described in the documentation for the [`components`] method.
17 //! Path manipulation includes both parsing components from slices and building
20 //! To parse a path, you can create a [`Path`] slice from a [`str`]
21 //! slice and start asking questions:
24 //! use std::path::Path;
25 //! use std::ffi::OsStr;
27 //! let path = Path::new("/tmp/foo/bar.txt");
29 //! let parent = path.parent();
30 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
32 //! let file_stem = path.file_stem();
33 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
35 //! let extension = path.extension();
36 //! assert_eq!(extension, Some(OsStr::new("txt")));
39 //! To build or modify paths, use [`PathBuf`]:
42 //! use std::path::PathBuf;
44 //! // This way works...
45 //! let mut path = PathBuf::from("c:\\");
47 //! path.push("windows");
48 //! path.push("system32");
50 //! path.set_extension("dll");
52 //! // ... but push is best used if you don't know everything up
53 //! // front. If you do, this way is better:
54 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
57 //! [`Component`]: ../../std/path/enum.Component.html
58 //! [`components`]: ../../std/path/struct.Path.html#method.components
59 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
60 //! [`Path`]: ../../std/path/struct.Path.html
61 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
62 //! [`String`]: ../../std/string/struct.String.html
64 //! [`str`]: ../../std/primitive.str.html
65 //! [`OsString`]: ../../std/ffi/struct.OsString.html
66 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
68 #![stable(feature = "rust1", since = "1.0.0")]
70 use borrow::{Borrow, Cow};
75 use hash::{Hash, Hasher};
77 use iter::{self, FusedIterator};
78 use ops::{self, Deref};
81 use string::ParseError;
84 use ffi::{OsStr, OsString};
86 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
88 ////////////////////////////////////////////////////////////////////////////////
90 ////////////////////////////////////////////////////////////////////////////////
92 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
93 // taking advantage of the fact that OsStr always encodes ASCII characters
94 // as-is. Eventually, this transmutation should be replaced by direct uses of
95 // OsStr APIs for parsing, but it will take a while for those to become
98 ////////////////////////////////////////////////////////////////////////////////
100 ////////////////////////////////////////////////////////////////////////////////
102 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
104 /// Windows uses a variety of path prefix styles, including references to drive
105 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
106 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
107 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
108 /// no normalization is performed.
113 /// use std::path::{Component, Path, Prefix};
114 /// use std::path::Prefix::*;
115 /// use std::ffi::OsStr;
117 /// fn get_path_prefix(s: &str) -> Prefix {
118 /// let path = Path::new(s);
119 /// match path.components().next().unwrap() {
120 /// Component::Prefix(prefix_component) => prefix_component.kind(),
125 /// # if cfg!(windows) {
126 /// assert_eq!(Verbatim(OsStr::new("pictures")),
127 /// get_path_prefix(r"\\?\pictures\kittens"));
128 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
129 /// get_path_prefix(r"\\?\UNC\server\share"));
130 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
131 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
132 /// get_path_prefix(r"\\.\BrainInterface"));
133 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
134 /// get_path_prefix(r"\\server\share"));
135 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
138 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
139 #[stable(feature = "rust1", since = "1.0.0")]
140 pub enum Prefix<'a> {
141 /// Verbatim prefix, e.g., `\\?\cat_pics`.
143 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
145 #[stable(feature = "rust1", since = "1.0.0")]
146 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
148 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
149 /// e.g., `\\?\UNC\server\share`.
151 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
152 /// server's hostname and a share name.
153 #[stable(feature = "rust1", since = "1.0.0")]
155 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
156 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
159 /// Verbatim disk prefix, e.g., `\\?\C:\`.
161 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
162 /// drive letter and `:\`.
163 #[stable(feature = "rust1", since = "1.0.0")]
164 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
166 /// Device namespace prefix, e.g., `\\.\COM42`.
168 /// Device namespace prefixes consist of `\\.\` immediately followed by the
170 #[stable(feature = "rust1", since = "1.0.0")]
171 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
173 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
174 /// `\\server\share`.
176 /// UNC prefixes consist of the server's hostname and a share name.
177 #[stable(feature = "rust1", since = "1.0.0")]
179 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
180 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
183 /// Prefix `C:` for the given disk drive.
184 #[stable(feature = "rust1", since = "1.0.0")]
185 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
188 impl<'a> Prefix<'a> {
190 fn len(&self) -> usize {
192 fn os_str_len(s: &OsStr) -> usize {
193 os_str_as_u8_slice(s).len()
196 Verbatim(x) => 4 + os_str_len(x),
197 VerbatimUNC(x, y) => {
199 if os_str_len(y) > 0 {
205 VerbatimDisk(_) => 6,
208 if os_str_len(y) > 0 {
214 DeviceNS(x) => 4 + os_str_len(x),
220 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
225 /// use std::path::Prefix::*;
226 /// use std::ffi::OsStr;
228 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
229 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
230 /// assert!(VerbatimDisk(b'C').is_verbatim());
231 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
232 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
233 /// assert!(!Disk(b'C').is_verbatim());
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn is_verbatim(&self) -> bool {
240 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
246 fn is_drive(&self) -> bool {
248 Prefix::Disk(_) => true,
254 fn has_implicit_root(&self) -> bool {
259 ////////////////////////////////////////////////////////////////////////////////
260 // Exposed parsing helpers
261 ////////////////////////////////////////////////////////////////////////////////
263 /// Determines whether the character is one of the permitted path
264 /// separators for the current platform.
271 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
272 /// assert!(!path::is_separator('❤'));
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn is_separator(c: char) -> bool {
276 c.is_ascii() && is_sep_byte(c as u8)
279 /// The primary separator of path components for the current platform.
281 /// For example, `/` on Unix and `\` on Windows.
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
285 ////////////////////////////////////////////////////////////////////////////////
287 ////////////////////////////////////////////////////////////////////////////////
289 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
290 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
291 // `iter` after having exhausted `prefix`.
292 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
293 where I: Iterator<Item = Component<'a>> + Clone,
294 J: Iterator<Item = Component<'b>>,
297 let mut iter_next = iter.clone();
298 match (iter_next.next(), prefix.next()) {
299 (Some(ref x), Some(ref y)) if x == y => (),
300 (Some(_), Some(_)) => return None,
301 (Some(_), None) => return Some(iter),
302 (None, None) => return Some(iter),
303 (None, Some(_)) => return None,
309 // See note at the top of this module to understand why these are used:
310 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
311 unsafe { &*(s as *const OsStr as *const [u8]) }
313 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
314 &*(s as *const [u8] as *const OsStr)
317 // Detect scheme on Redox
318 fn has_redox_scheme(s: &[u8]) -> bool {
319 cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
322 ////////////////////////////////////////////////////////////////////////////////
323 // Cross-platform, iterator-independent parsing
324 ////////////////////////////////////////////////////////////////////////////////
326 /// Says whether the first byte after the prefix is a separator.
327 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
328 let path = if let Some(p) = prefix {
333 !path.is_empty() && is_sep_byte(path[0])
336 // basic workhorse for splitting stem and extension
337 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
339 if os_str_as_u8_slice(file) == b".." {
340 return (Some(file), None);
343 // The unsafety here stems from converting between &OsStr and &[u8]
344 // and back. This is safe to do because (1) we only look at ASCII
345 // contents of the encoding and (2) new &OsStr values are produced
346 // only from ASCII-bounded slices of existing &OsStr values.
348 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
349 let after = iter.next();
350 let before = iter.next();
351 if before == Some(b"") {
354 (before.map(|s| u8_slice_as_os_str(s)),
355 after.map(|s| u8_slice_as_os_str(s)))
360 ////////////////////////////////////////////////////////////////////////////////
361 // The core iterators
362 ////////////////////////////////////////////////////////////////////////////////
364 /// Component parsing works by a double-ended state machine; the cursors at the
365 /// front and back of the path each keep track of what parts of the path have
366 /// been consumed so far.
368 /// Going front to back, a path is made up of a prefix, a starting
369 /// directory component, and a body (of normal components)
370 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
373 StartDir = 1, // / or . or nothing
374 Body = 2, // foo/bar/baz
378 /// A structure wrapping a Windows path prefix as well as its unparsed string
381 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
382 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
383 /// returned by [`as_os_str`].
385 /// Instances of this `struct` can be obtained by matching against the
386 /// [`Prefix` variant] on [`Component`].
388 /// Does not occur on Unix.
393 /// # if cfg!(windows) {
394 /// use std::path::{Component, Path, Prefix};
395 /// use std::ffi::OsStr;
397 /// let path = Path::new(r"c:\you\later\");
398 /// match path.components().next().unwrap() {
399 /// Component::Prefix(prefix_component) => {
400 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
401 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
403 /// _ => unreachable!(),
408 /// [`as_os_str`]: #method.as_os_str
409 /// [`Component`]: enum.Component.html
410 /// [`kind`]: #method.kind
411 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
412 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
413 /// [`Prefix`]: enum.Prefix.html
414 #[stable(feature = "rust1", since = "1.0.0")]
415 #[derive(Copy, Clone, Eq, Debug)]
416 pub struct PrefixComponent<'a> {
417 /// The prefix as an unparsed `OsStr` slice.
420 /// The parsed prefix data.
424 impl<'a> PrefixComponent<'a> {
425 /// Returns the parsed prefix data.
427 /// See [`Prefix`]'s documentation for more information on the different
428 /// kinds of prefixes.
430 /// [`Prefix`]: enum.Prefix.html
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn kind(&self) -> Prefix<'a> {
436 /// Returns the raw [`OsStr`] slice for this prefix.
438 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn as_os_str(&self) -> &'a OsStr {
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
447 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
448 cmp::PartialEq::eq(&self.parsed, &other.parsed)
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
454 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
455 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl cmp::Ord for PrefixComponent<'_> {
461 fn cmp(&self, other: &Self) -> cmp::Ordering {
462 cmp::Ord::cmp(&self.parsed, &other.parsed)
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl Hash for PrefixComponent<'_> {
468 fn hash<H: Hasher>(&self, h: &mut H) {
473 /// A single component of a path.
475 /// A `Component` roughly corresponds to a substring between path separators
478 /// This `enum` is created by iterating over [`Components`], which in turn is
479 /// created by the [`components`][`Path::components`] method on [`Path`].
484 /// use std::path::{Component, Path};
486 /// let path = Path::new("/tmp/foo/bar.txt");
487 /// let components = path.components().collect::<Vec<_>>();
488 /// assert_eq!(&components, &[
489 /// Component::RootDir,
490 /// Component::Normal("tmp".as_ref()),
491 /// Component::Normal("foo".as_ref()),
492 /// Component::Normal("bar.txt".as_ref()),
496 /// [`Components`]: struct.Components.html
497 /// [`Path`]: struct.Path.html
498 /// [`Path::components`]: struct.Path.html#method.components
499 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub enum Component<'a> {
502 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
504 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
507 /// Does not occur on Unix.
509 /// [`Prefix`]: enum.Prefix.html
510 #[stable(feature = "rust1", since = "1.0.0")]
512 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
515 /// The root directory component, appears after any prefix and before anything else.
517 /// It represents a separator that designates that a path starts from root.
518 #[stable(feature = "rust1", since = "1.0.0")]
521 /// A reference to the current directory, i.e., `.`.
522 #[stable(feature = "rust1", since = "1.0.0")]
525 /// A reference to the parent directory, i.e., `..`.
526 #[stable(feature = "rust1", since = "1.0.0")]
529 /// A normal component, e.g., `a` and `b` in `a/b`.
531 /// This variant is the most common one, it represents references to files
533 #[stable(feature = "rust1", since = "1.0.0")]
534 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
537 impl<'a> Component<'a> {
538 /// Extracts the underlying [`OsStr`] slice.
543 /// use std::path::Path;
545 /// let path = Path::new("./tmp/foo/bar.txt");
546 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
547 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
550 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn as_os_str(self) -> &'a OsStr {
554 Component::Prefix(p) => p.as_os_str(),
555 Component::RootDir => OsStr::new(MAIN_SEP_STR),
556 Component::CurDir => OsStr::new("."),
557 Component::ParentDir => OsStr::new(".."),
558 Component::Normal(path) => path,
563 #[stable(feature = "rust1", since = "1.0.0")]
564 impl AsRef<OsStr> for Component<'_> {
565 fn as_ref(&self) -> &OsStr {
570 #[stable(feature = "path_component_asref", since = "1.25.0")]
571 impl AsRef<Path> for Component<'_> {
572 fn as_ref(&self) -> &Path {
573 self.as_os_str().as_ref()
577 /// An iterator over the [`Component`]s of a [`Path`].
579 /// This `struct` is created by the [`components`] method on [`Path`].
580 /// See its documentation for more.
585 /// use std::path::Path;
587 /// let path = Path::new("/tmp/foo/bar.txt");
589 /// for component in path.components() {
590 /// println!("{:?}", component);
594 /// [`Component`]: enum.Component.html
595 /// [`components`]: struct.Path.html#method.components
596 /// [`Path`]: struct.Path.html
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub struct Components<'a> {
600 // The path left to parse components from
603 // The prefix as it was originally parsed, if any
604 prefix: Option<Prefix<'a>>,
606 // true if path *physically* has a root separator; for most Windows
607 // prefixes, it may have a "logical" rootseparator for the purposes of
608 // normalization, e.g., \\server\share == \\server\share\.
609 has_physical_root: bool,
611 // The iterator is double-ended, and these two states keep track of what has
612 // been produced from either end
617 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
619 /// This `struct` is created by the [`iter`] method on [`Path`].
620 /// See its documentation for more.
622 /// [`Component`]: enum.Component.html
623 /// [`iter`]: struct.Path.html#method.iter
624 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
625 /// [`Path`]: struct.Path.html
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub struct Iter<'a> {
629 inner: Components<'a>,
632 #[stable(feature = "path_components_debug", since = "1.13.0")]
633 impl fmt::Debug for Components<'_> {
634 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
635 struct DebugHelper<'a>(&'a Path);
637 impl fmt::Debug for DebugHelper<'_> {
638 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
640 .entries(self.0.components())
645 f.debug_tuple("Components")
646 .field(&DebugHelper(self.as_path()))
651 impl<'a> Components<'a> {
652 // how long is the prefix, if any?
654 fn prefix_len(&self) -> usize {
655 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
659 fn prefix_verbatim(&self) -> bool {
660 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
663 /// how much of the prefix is left from the point of view of iteration?
665 fn prefix_remaining(&self) -> usize {
666 if self.front == State::Prefix {
673 // Given the iteration so far, how much of the pre-State::Body path is left?
675 fn len_before_body(&self) -> usize {
676 let root = if self.front <= State::StartDir && self.has_physical_root {
681 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
686 self.prefix_remaining() + root + cur_dir
689 // is the iteration complete?
691 fn finished(&self) -> bool {
692 self.front == State::Done || self.back == State::Done || self.front > self.back
696 fn is_sep_byte(&self, b: u8) -> bool {
697 if self.prefix_verbatim() {
704 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
709 /// use std::path::Path;
711 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
712 /// components.next();
713 /// components.next();
715 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
717 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn as_path(&self) -> &'a Path {
719 let mut comps = self.clone();
720 if comps.front == State::Body {
723 if comps.back == State::Body {
726 unsafe { Path::from_u8_slice(comps.path) }
729 /// Is the *original* path rooted?
730 fn has_root(&self) -> bool {
731 if self.has_physical_root {
734 if let Some(p) = self.prefix {
735 if p.has_implicit_root() {
742 /// Should the normalized path include a leading . ?
743 fn include_cur_dir(&self) -> bool {
747 let mut iter = self.path[self.prefix_len()..].iter();
748 match (iter.next(), iter.next()) {
749 (Some(&b'.'), None) => true,
750 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
755 // parse a given byte sequence into the corresponding path component
756 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
758 b"." if self.prefix_verbatim() => Some(Component::CurDir),
759 b"." => None, // . components are normalized away, except at
760 // the beginning of a path, which is treated
761 // separately via `include_cur_dir`
762 b".." => Some(Component::ParentDir),
764 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
768 // parse a component from the left, saying how many bytes to consume to
769 // remove the component
770 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
771 debug_assert!(self.front == State::Body);
772 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
773 None => (0, self.path),
774 Some(i) => (1, &self.path[..i]),
776 (comp.len() + extra, self.parse_single_component(comp))
779 // parse a component from the right, saying how many bytes to consume to
780 // remove the component
781 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
782 debug_assert!(self.back == State::Body);
783 let start = self.len_before_body();
784 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
785 None => (0, &self.path[start..]),
786 Some(i) => (1, &self.path[start + i + 1..]),
788 (comp.len() + extra, self.parse_single_component(comp))
791 // trim away repeated separators (i.e., empty components) on the left
792 fn trim_left(&mut self) {
793 while !self.path.is_empty() {
794 let (size, comp) = self.parse_next_component();
798 self.path = &self.path[size..];
803 // trim away repeated separators (i.e., empty components) on the right
804 fn trim_right(&mut self) {
805 while self.path.len() > self.len_before_body() {
806 let (size, comp) = self.parse_next_component_back();
810 self.path = &self.path[..self.path.len() - size];
816 #[stable(feature = "rust1", since = "1.0.0")]
817 impl AsRef<Path> for Components<'_> {
818 fn as_ref(&self) -> &Path {
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl AsRef<OsStr> for Components<'_> {
825 fn as_ref(&self) -> &OsStr {
826 self.as_path().as_os_str()
830 #[stable(feature = "path_iter_debug", since = "1.13.0")]
831 impl fmt::Debug for Iter<'_> {
832 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
833 struct DebugHelper<'a>(&'a Path);
835 impl fmt::Debug for DebugHelper<'_> {
836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
838 .entries(self.0.iter())
843 f.debug_tuple("Iter")
844 .field(&DebugHelper(self.as_path()))
850 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
855 /// use std::path::Path;
857 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
861 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
863 #[stable(feature = "rust1", since = "1.0.0")]
864 pub fn as_path(&self) -> &'a Path {
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl AsRef<Path> for Iter<'_> {
871 fn as_ref(&self) -> &Path {
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl AsRef<OsStr> for Iter<'_> {
878 fn as_ref(&self) -> &OsStr {
879 self.as_path().as_os_str()
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a> Iterator for Iter<'a> {
885 type Item = &'a OsStr;
887 fn next(&mut self) -> Option<&'a OsStr> {
888 self.inner.next().map(Component::as_os_str)
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<'a> DoubleEndedIterator for Iter<'a> {
894 fn next_back(&mut self) -> Option<&'a OsStr> {
895 self.inner.next_back().map(Component::as_os_str)
899 #[stable(feature = "fused", since = "1.26.0")]
900 impl FusedIterator for Iter<'_> {}
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a> Iterator for Components<'a> {
904 type Item = Component<'a>;
906 fn next(&mut self) -> Option<Component<'a>> {
907 while !self.finished() {
909 State::Prefix if self.prefix_len() > 0 => {
910 self.front = State::StartDir;
911 debug_assert!(self.prefix_len() <= self.path.len());
912 let raw = &self.path[..self.prefix_len()];
913 self.path = &self.path[self.prefix_len()..];
914 return Some(Component::Prefix(PrefixComponent {
915 raw: unsafe { u8_slice_as_os_str(raw) },
916 parsed: self.prefix.unwrap(),
920 self.front = State::StartDir;
923 self.front = State::Body;
924 if self.has_physical_root {
925 debug_assert!(!self.path.is_empty());
926 self.path = &self.path[1..];
927 return Some(Component::RootDir);
928 } else if let Some(p) = self.prefix {
929 if p.has_implicit_root() && !p.is_verbatim() {
930 return Some(Component::RootDir);
932 } else if self.include_cur_dir() {
933 debug_assert!(!self.path.is_empty());
934 self.path = &self.path[1..];
935 return Some(Component::CurDir);
938 State::Body if !self.path.is_empty() => {
939 let (size, comp) = self.parse_next_component();
940 self.path = &self.path[size..];
946 self.front = State::Done;
948 State::Done => unreachable!(),
955 #[stable(feature = "rust1", since = "1.0.0")]
956 impl<'a> DoubleEndedIterator for Components<'a> {
957 fn next_back(&mut self) -> Option<Component<'a>> {
958 while !self.finished() {
960 State::Body if self.path.len() > self.len_before_body() => {
961 let (size, comp) = self.parse_next_component_back();
962 self.path = &self.path[..self.path.len() - size];
968 self.back = State::StartDir;
971 self.back = State::Prefix;
972 if self.has_physical_root {
973 self.path = &self.path[..self.path.len() - 1];
974 return Some(Component::RootDir);
975 } else if let Some(p) = self.prefix {
976 if p.has_implicit_root() && !p.is_verbatim() {
977 return Some(Component::RootDir);
979 } else if self.include_cur_dir() {
980 self.path = &self.path[..self.path.len() - 1];
981 return Some(Component::CurDir);
984 State::Prefix if self.prefix_len() > 0 => {
985 self.back = State::Done;
986 return Some(Component::Prefix(PrefixComponent {
987 raw: unsafe { u8_slice_as_os_str(self.path) },
988 parsed: self.prefix.unwrap(),
992 self.back = State::Done;
995 State::Done => unreachable!(),
1002 #[stable(feature = "fused", since = "1.26.0")]
1003 impl FusedIterator for Components<'_> {}
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 impl<'a> cmp::PartialEq for Components<'a> {
1007 fn eq(&self, other: &Components<'a>) -> bool {
1008 Iterator::eq(self.clone(), other.clone())
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl cmp::Eq for Components<'_> {}
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<'a> cmp::PartialOrd for Components<'a> {
1017 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1018 Iterator::partial_cmp(self.clone(), other.clone())
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl cmp::Ord for Components<'_> {
1024 fn cmp(&self, other: &Self) -> cmp::Ordering {
1025 Iterator::cmp(self.clone(), other.clone())
1029 /// An iterator over [`Path`] and its ancestors.
1031 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1032 /// See its documentation for more.
1037 /// use std::path::Path;
1039 /// let path = Path::new("/foo/bar");
1041 /// for ancestor in path.ancestors() {
1042 /// println!("{}", ancestor.display());
1046 /// [`ancestors`]: struct.Path.html#method.ancestors
1047 /// [`Path`]: struct.Path.html
1048 #[derive(Copy, Clone, Debug)]
1049 #[stable(feature = "path_ancestors", since = "1.28.0")]
1050 pub struct Ancestors<'a> {
1051 next: Option<&'a Path>,
1054 #[stable(feature = "path_ancestors", since = "1.28.0")]
1055 impl<'a> Iterator for Ancestors<'a> {
1056 type Item = &'a Path;
1058 fn next(&mut self) -> Option<Self::Item> {
1059 let next = self.next;
1060 self.next = next.and_then(Path::parent);
1065 #[stable(feature = "path_ancestors", since = "1.28.0")]
1066 impl FusedIterator for Ancestors<'_> {}
1068 ////////////////////////////////////////////////////////////////////////////////
1069 // Basic types and traits
1070 ////////////////////////////////////////////////////////////////////////////////
1072 /// An owned, mutable path (akin to [`String`]).
1074 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1075 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1076 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1078 /// [`String`]: ../string/struct.String.html
1079 /// [`Path`]: struct.Path.html
1080 /// [`push`]: struct.PathBuf.html#method.push
1081 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1082 /// [`Deref`]: ../ops/trait.Deref.html
1084 /// More details about the overall approach can be found in
1085 /// the [module documentation](index.html).
1089 /// You can use [`push`] to build up a `PathBuf` from
1093 /// use std::path::PathBuf;
1095 /// let mut path = PathBuf::new();
1097 /// path.push(r"C:\");
1098 /// path.push("windows");
1099 /// path.push("system32");
1101 /// path.set_extension("dll");
1104 /// However, [`push`] is best used for dynamic situations. This is a better way
1105 /// to do this when you know all of the components ahead of time:
1108 /// use std::path::PathBuf;
1110 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1113 /// We can still do better than this! Since these are all strings, we can use
1117 /// use std::path::PathBuf;
1119 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1122 /// Which method works best depends on what kind of situation you're in.
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 pub struct PathBuf {
1130 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1131 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1134 /// Allocates an empty `PathBuf`.
1139 /// use std::path::PathBuf;
1141 /// let path = PathBuf::new();
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub fn new() -> PathBuf {
1145 PathBuf { inner: OsString::new() }
1148 /// Creates a new `PathBuf` with a given capacity used to create the
1149 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1154 /// #![feature(path_buf_capacity)]
1155 /// use std::path::PathBuf;
1157 /// let mut path = PathBuf::with_capacity(10);
1158 /// let capacity = path.capacity();
1160 /// // This push is done without reallocating
1161 /// path.push(r"C:\");
1163 /// assert_eq!(capacity, path.capacity());
1166 /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1167 /// [`OsString`]: ../ffi/struct.OsString.html
1168 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1169 pub fn with_capacity(capacity: usize) -> PathBuf {
1171 inner: OsString::with_capacity(capacity)
1175 /// Coerces to a [`Path`] slice.
1177 /// [`Path`]: struct.Path.html
1182 /// use std::path::{Path, PathBuf};
1184 /// let p = PathBuf::from("/test");
1185 /// assert_eq!(Path::new("/test"), p.as_path());
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 pub fn as_path(&self) -> &Path {
1192 /// Extends `self` with `path`.
1194 /// If `path` is absolute, it replaces the current path.
1198 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1199 /// replaces everything except for the prefix (if any) of `self`.
1200 /// * if `path` has a prefix but no root, it replaces `self`.
1204 /// Pushing a relative path extends the existing path:
1207 /// use std::path::PathBuf;
1209 /// let mut path = PathBuf::from("/tmp");
1210 /// path.push("file.bk");
1211 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1214 /// Pushing an absolute path replaces the existing path:
1217 /// use std::path::PathBuf;
1219 /// let mut path = PathBuf::from("/tmp");
1220 /// path.push("/etc");
1221 /// assert_eq!(path, PathBuf::from("/etc"));
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1225 self._push(path.as_ref())
1228 fn _push(&mut self, path: &Path) {
1229 // in general, a separator is needed if the rightmost byte is not a separator
1230 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1232 // in the special case of `C:` on Windows, do *not* add a separator
1234 let comps = self.components();
1235 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1236 comps.prefix.unwrap().is_drive() {
1241 // absolute `path` replaces `self`
1242 if path.is_absolute() || path.prefix().is_some() {
1243 self.as_mut_vec().truncate(0);
1245 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1246 } else if path.has_root() {
1247 let prefix_len = self.components().prefix_remaining();
1248 self.as_mut_vec().truncate(prefix_len);
1250 // `path` is a pure relative path
1251 } else if need_sep {
1252 self.inner.push(MAIN_SEP_STR);
1255 self.inner.push(path);
1258 /// Truncates `self` to [`self.parent`].
1260 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1261 /// Otherwise, returns `true`.
1263 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1264 /// [`self.parent`]: struct.PathBuf.html#method.parent
1269 /// use std::path::{Path, PathBuf};
1271 /// let mut p = PathBuf::from("/test/test.rs");
1274 /// assert_eq!(Path::new("/test"), p);
1276 /// assert_eq!(Path::new("/"), p);
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub fn pop(&mut self) -> bool {
1280 match self.parent().map(|p| p.as_u8_slice().len()) {
1282 self.as_mut_vec().truncate(len);
1289 /// Updates [`self.file_name`] to `file_name`.
1291 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1294 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1295 /// `file_name`. The new path will be a sibling of the original path.
1296 /// (That is, it will have the same parent.)
1298 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1299 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1300 /// [`pop`]: struct.PathBuf.html#method.pop
1305 /// use std::path::PathBuf;
1307 /// let mut buf = PathBuf::from("/");
1308 /// assert!(buf.file_name() == None);
1309 /// buf.set_file_name("bar");
1310 /// assert!(buf == PathBuf::from("/bar"));
1311 /// assert!(buf.file_name().is_some());
1312 /// buf.set_file_name("baz.txt");
1313 /// assert!(buf == PathBuf::from("/baz.txt"));
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1317 self._set_file_name(file_name.as_ref())
1320 fn _set_file_name(&mut self, file_name: &OsStr) {
1321 if self.file_name().is_some() {
1322 let popped = self.pop();
1323 debug_assert!(popped);
1325 self.push(file_name);
1328 /// Updates [`self.extension`] to `extension`.
1330 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1331 /// returns `true` and updates the extension otherwise.
1333 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1336 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1337 /// [`self.extension`]: struct.PathBuf.html#method.extension
1338 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1343 /// use std::path::{Path, PathBuf};
1345 /// let mut p = PathBuf::from("/feel/the");
1347 /// p.set_extension("force");
1348 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1350 /// p.set_extension("dark_side");
1351 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1355 self._set_extension(extension.as_ref())
1358 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1359 if self.file_name().is_none() {
1363 let mut stem = match self.file_stem() {
1364 Some(stem) => stem.to_os_string(),
1365 None => OsString::new(),
1368 if !os_str_as_u8_slice(extension).is_empty() {
1370 stem.push(extension);
1372 self.set_file_name(&stem);
1377 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1379 /// [`OsString`]: ../ffi/struct.OsString.html
1384 /// use std::path::PathBuf;
1386 /// let p = PathBuf::from("/the/head");
1387 /// let os_str = p.into_os_string();
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 pub fn into_os_string(self) -> OsString {
1394 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1396 /// [`Box`]: ../../std/boxed/struct.Box.html
1397 /// [`Path`]: struct.Path.html
1398 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1399 pub fn into_boxed_path(self) -> Box<Path> {
1400 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1401 unsafe { Box::from_raw(rw) }
1404 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1406 /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1407 /// [`OsString`]: ../ffi/struct.OsString.html
1408 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1409 pub fn capacity(&self) -> usize {
1410 self.inner.capacity()
1413 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1415 /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1416 /// [`OsString`]: ../ffi/struct.OsString.html
1417 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1418 pub fn clear(&mut self) {
1422 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1424 /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1425 /// [`OsString`]: ../ffi/struct.OsString.html
1426 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1427 pub fn reserve(&mut self, additional: usize) {
1428 self.inner.reserve(additional)
1431 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1433 /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1434 /// [`OsString`]: ../ffi/struct.OsString.html
1435 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1436 pub fn reserve_exact(&mut self, additional: usize) {
1437 self.inner.reserve_exact(additional)
1440 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1442 /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1443 /// [`OsString`]: ../ffi/struct.OsString.html
1444 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1445 pub fn shrink_to_fit(&mut self) {
1446 self.inner.shrink_to_fit()
1449 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1451 /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1452 /// [`OsString`]: ../ffi/struct.OsString.html
1453 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1454 pub fn shrink_to(&mut self, min_capacity: usize) {
1455 self.inner.shrink_to(min_capacity)
1459 #[stable(feature = "box_from_path", since = "1.17.0")]
1460 impl<'a> From<&'a Path> for Box<Path> {
1461 fn from(path: &'a Path) -> Box<Path> {
1462 let boxed: Box<OsStr> = path.inner.into();
1463 let rw = Box::into_raw(boxed) as *mut Path;
1464 unsafe { Box::from_raw(rw) }
1468 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1469 impl From<Box<Path>> for PathBuf {
1470 /// Converts a `Box<Path>` into a `PathBuf`
1472 /// This conversion does not allocate or copy memory.
1473 fn from(boxed: Box<Path>) -> PathBuf {
1474 boxed.into_path_buf()
1478 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1479 impl From<PathBuf> for Box<Path> {
1480 /// Converts a `PathBuf` into a `Box<Path>`
1482 /// This conversion currently should not allocate memory,
1483 /// but this behavior is not guaranteed on all platforms or in all future versions.
1484 fn from(p: PathBuf) -> Box<Path> {
1489 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1490 impl Clone for Box<Path> {
1492 fn clone(&self) -> Self {
1493 self.to_path_buf().into_boxed_path()
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1499 fn from(s: &'a T) -> PathBuf {
1500 PathBuf::from(s.as_ref().to_os_string())
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl From<OsString> for PathBuf {
1506 /// Converts a `OsString` into a `PathBuf`
1508 /// This conversion does not allocate or copy memory.
1509 fn from(s: OsString) -> PathBuf {
1510 PathBuf { inner: s }
1514 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1515 impl From<PathBuf> for OsString {
1516 /// Converts a `PathBuf` into a `OsString`
1518 /// This conversion does not allocate or copy memory.
1519 fn from(path_buf : PathBuf) -> OsString {
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl From<String> for PathBuf {
1526 /// Converts a `String` into a `PathBuf`
1528 /// This conversion does not allocate or copy memory.
1529 fn from(s: String) -> PathBuf {
1530 PathBuf::from(OsString::from(s))
1534 #[stable(feature = "path_from_str", since = "1.32.0")]
1535 impl FromStr for PathBuf {
1536 type Err = ParseError;
1538 fn from_str(s: &str) -> Result<Self, Self::Err> {
1539 Ok(PathBuf::from(s))
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1545 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1546 let mut buf = PathBuf::new();
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1554 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1556 self.push(p.as_ref())
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl fmt::Debug for PathBuf {
1563 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1564 fmt::Debug::fmt(&**self, formatter)
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl ops::Deref for PathBuf {
1572 fn deref(&self) -> &Path {
1573 Path::new(&self.inner)
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl Borrow<Path> for PathBuf {
1579 fn borrow(&self) -> &Path {
1584 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1585 impl Default for PathBuf {
1586 fn default() -> Self {
1591 #[stable(feature = "cow_from_path", since = "1.6.0")]
1592 impl<'a> From<&'a Path> for Cow<'a, Path> {
1594 fn from(s: &'a Path) -> Cow<'a, Path> {
1599 #[stable(feature = "cow_from_path", since = "1.6.0")]
1600 impl<'a> From<PathBuf> for Cow<'a, Path> {
1602 fn from(s: PathBuf) -> Cow<'a, Path> {
1607 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1608 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1610 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1611 Cow::Borrowed(p.as_path())
1615 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1616 impl<'a> From<Cow<'a, Path>> for PathBuf {
1618 fn from(p: Cow<'a, Path>) -> Self {
1623 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1624 impl From<PathBuf> for Arc<Path> {
1625 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1627 fn from(s: PathBuf) -> Arc<Path> {
1628 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1629 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1633 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1634 impl<'a> From<&'a Path> for Arc<Path> {
1635 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1637 fn from(s: &Path) -> Arc<Path> {
1638 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1639 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1643 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1644 impl From<PathBuf> for Rc<Path> {
1645 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1647 fn from(s: PathBuf) -> Rc<Path> {
1648 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1649 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1653 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1654 impl<'a> From<&'a Path> for Rc<Path> {
1655 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1657 fn from(s: &Path) -> Rc<Path> {
1658 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1659 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 impl ToOwned for Path {
1665 type Owned = PathBuf;
1666 fn to_owned(&self) -> PathBuf {
1669 fn clone_into(&self, target: &mut PathBuf) {
1670 self.inner.clone_into(&mut target.inner);
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl cmp::PartialEq for PathBuf {
1676 fn eq(&self, other: &PathBuf) -> bool {
1677 self.components() == other.components()
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl Hash for PathBuf {
1683 fn hash<H: Hasher>(&self, h: &mut H) {
1684 self.as_path().hash(h)
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl cmp::Eq for PathBuf {}
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl cmp::PartialOrd for PathBuf {
1693 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1694 self.components().partial_cmp(other.components())
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl cmp::Ord for PathBuf {
1700 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1701 self.components().cmp(other.components())
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl AsRef<OsStr> for PathBuf {
1707 fn as_ref(&self) -> &OsStr {
1712 /// A slice of a path (akin to [`str`]).
1714 /// This type supports a number of operations for inspecting a path, including
1715 /// breaking the path into its components (separated by `/` on Unix and by either
1716 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1717 /// is absolute, and so on.
1719 /// This is an *unsized* type, meaning that it must always be used behind a
1720 /// pointer like `&` or [`Box`]. For an owned version of this type,
1721 /// see [`PathBuf`].
1723 /// [`str`]: ../primitive.str.html
1724 /// [`Box`]: ../boxed/struct.Box.html
1725 /// [`PathBuf`]: struct.PathBuf.html
1727 /// More details about the overall approach can be found in
1728 /// the [module documentation](index.html).
1733 /// use std::path::Path;
1734 /// use std::ffi::OsStr;
1736 /// // Note: this example does work on Windows
1737 /// let path = Path::new("./foo/bar.txt");
1739 /// let parent = path.parent();
1740 /// assert_eq!(parent, Some(Path::new("./foo")));
1742 /// let file_stem = path.file_stem();
1743 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1745 /// let extension = path.extension();
1746 /// assert_eq!(extension, Some(OsStr::new("txt")));
1748 #[stable(feature = "rust1", since = "1.0.0")]
1753 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1756 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1757 /// See its documentation for more.
1759 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1760 /// [`Path`]: struct.Path.html
1761 #[derive(Debug, Clone, PartialEq, Eq)]
1762 #[stable(since = "1.7.0", feature = "strip_prefix")]
1763 pub struct StripPrefixError(());
1766 // The following (private!) function allows construction of a path from a u8
1767 // slice, which is only safe when it is known to follow the OsStr encoding.
1768 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1769 Path::new(u8_slice_as_os_str(s))
1771 // The following (private!) function reveals the byte encoding used for OsStr.
1772 fn as_u8_slice(&self) -> &[u8] {
1773 os_str_as_u8_slice(&self.inner)
1776 /// Directly wraps a string slice as a `Path` slice.
1778 /// This is a cost-free conversion.
1783 /// use std::path::Path;
1785 /// Path::new("foo.txt");
1788 /// You can create `Path`s from `String`s, or even other `Path`s:
1791 /// use std::path::Path;
1793 /// let string = String::from("foo.txt");
1794 /// let from_string = Path::new(&string);
1795 /// let from_path = Path::new(&from_string);
1796 /// assert_eq!(from_string, from_path);
1798 #[stable(feature = "rust1", since = "1.0.0")]
1799 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1800 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1803 /// Yields the underlying [`OsStr`] slice.
1805 /// [`OsStr`]: ../ffi/struct.OsStr.html
1810 /// use std::path::Path;
1812 /// let os_str = Path::new("foo.txt").as_os_str();
1813 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 pub fn as_os_str(&self) -> &OsStr {
1820 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1822 /// This conversion may entail doing a check for UTF-8 validity.
1824 /// [`&str`]: ../primitive.str.html
1829 /// use std::path::Path;
1831 /// let path = Path::new("foo.txt");
1832 /// assert_eq!(path.to_str(), Some("foo.txt"));
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 pub fn to_str(&self) -> Option<&str> {
1839 /// Converts a `Path` to a [`Cow<str>`].
1841 /// Any non-Unicode sequences are replaced with
1842 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1844 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1845 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1849 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1852 /// use std::path::Path;
1854 /// let path = Path::new("foo.txt");
1855 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1858 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1859 /// have returned `"fo�.txt"`.
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 pub fn to_string_lossy(&self) -> Cow<str> {
1862 self.inner.to_string_lossy()
1865 /// Converts a `Path` to an owned [`PathBuf`].
1867 /// [`PathBuf`]: struct.PathBuf.html
1872 /// use std::path::Path;
1874 /// let path_buf = Path::new("foo.txt").to_path_buf();
1875 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1877 #[rustc_conversion_suggestion]
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 pub fn to_path_buf(&self) -> PathBuf {
1880 PathBuf::from(self.inner.to_os_string())
1883 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1884 /// the current directory.
1886 /// * On Unix, a path is absolute if it starts with the root, so
1887 /// `is_absolute` and [`has_root`] are equivalent.
1889 /// * On Windows, a path is absolute if it has a prefix and starts with the
1890 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1895 /// use std::path::Path;
1897 /// assert!(!Path::new("foo.txt").is_absolute());
1900 /// [`has_root`]: #method.has_root
1901 #[stable(feature = "rust1", since = "1.0.0")]
1902 #[allow(deprecated)]
1903 pub fn is_absolute(&self) -> bool {
1904 if cfg!(target_os = "redox") {
1905 // FIXME: Allow Redox prefixes
1906 self.has_root() || has_redox_scheme(self.as_u8_slice())
1908 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1912 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1914 /// See [`is_absolute`]'s documentation for more details.
1919 /// use std::path::Path;
1921 /// assert!(Path::new("foo.txt").is_relative());
1924 /// [`is_absolute`]: #method.is_absolute
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 pub fn is_relative(&self) -> bool {
1930 fn prefix(&self) -> Option<Prefix> {
1931 self.components().prefix
1934 /// Returns `true` if the `Path` has a root.
1936 /// * On Unix, a path has a root if it begins with `/`.
1938 /// * On Windows, a path has a root if it:
1939 /// * has no prefix and begins with a separator, e.g., `\windows`
1940 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1941 /// * has any non-disk prefix, e.g., `\\server\share`
1946 /// use std::path::Path;
1948 /// assert!(Path::new("/etc/passwd").has_root());
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 pub fn has_root(&self) -> bool {
1952 self.components().has_root()
1955 /// Returns the `Path` without its final component, if there is one.
1957 /// Returns [`None`] if the path terminates in a root or prefix.
1959 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1964 /// use std::path::Path;
1966 /// let path = Path::new("/foo/bar");
1967 /// let parent = path.parent().unwrap();
1968 /// assert_eq!(parent, Path::new("/foo"));
1970 /// let grand_parent = parent.parent().unwrap();
1971 /// assert_eq!(grand_parent, Path::new("/"));
1972 /// assert_eq!(grand_parent.parent(), None);
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 pub fn parent(&self) -> Option<&Path> {
1976 let mut comps = self.components();
1977 let comp = comps.next_back();
1980 Component::Normal(_) |
1982 Component::ParentDir => Some(comps.as_path()),
1988 /// Produces an iterator over `Path` and its ancestors.
1990 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1991 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1992 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1993 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1999 /// use std::path::Path;
2001 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2002 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2003 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2004 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2005 /// assert_eq!(ancestors.next(), None);
2008 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2009 /// [`parent`]: struct.Path.html#method.parent
2010 #[stable(feature = "path_ancestors", since = "1.28.0")]
2011 pub fn ancestors(&self) -> Ancestors {
2017 /// Returns the final component of the `Path`, if there is one.
2019 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2020 /// is the directory name.
2022 /// Returns [`None`] if the path terminates in `..`.
2024 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2029 /// use std::path::Path;
2030 /// use std::ffi::OsStr;
2032 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2033 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2034 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2035 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2036 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2037 /// assert_eq!(None, Path::new("/").file_name());
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 pub fn file_name(&self) -> Option<&OsStr> {
2041 self.components().next_back().and_then(|p| {
2043 Component::Normal(p) => Some(p.as_ref()),
2049 /// Returns a path that, when joined onto `base`, yields `self`.
2053 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2054 /// returns `false`), returns [`Err`].
2056 /// [`starts_with`]: #method.starts_with
2057 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2062 /// use std::path::{Path, PathBuf};
2064 /// let path = Path::new("/test/haha/foo.txt");
2066 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2067 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2068 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2069 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2070 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2071 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2072 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2074 /// let prefix = PathBuf::from("/test/");
2075 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2077 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2078 pub fn strip_prefix<P>(&self, base: P)
2079 -> Result<&Path, StripPrefixError>
2080 where P: AsRef<Path>
2082 self._strip_prefix(base.as_ref())
2085 fn _strip_prefix(&self, base: &Path)
2086 -> Result<&Path, StripPrefixError> {
2087 iter_after(self.components(), base.components())
2088 .map(|c| c.as_path())
2089 .ok_or(StripPrefixError(()))
2092 /// Determines whether `base` is a prefix of `self`.
2094 /// Only considers whole path components to match.
2099 /// use std::path::Path;
2101 /// let path = Path::new("/etc/passwd");
2103 /// assert!(path.starts_with("/etc"));
2104 /// assert!(path.starts_with("/etc/"));
2105 /// assert!(path.starts_with("/etc/passwd"));
2106 /// assert!(path.starts_with("/etc/passwd/"));
2108 /// assert!(!path.starts_with("/e"));
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2112 self._starts_with(base.as_ref())
2115 fn _starts_with(&self, base: &Path) -> bool {
2116 iter_after(self.components(), base.components()).is_some()
2119 /// Determines whether `child` is a suffix of `self`.
2121 /// Only considers whole path components to match.
2126 /// use std::path::Path;
2128 /// let path = Path::new("/etc/passwd");
2130 /// assert!(path.ends_with("passwd"));
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2134 self._ends_with(child.as_ref())
2137 fn _ends_with(&self, child: &Path) -> bool {
2138 iter_after(self.components().rev(), child.components().rev()).is_some()
2141 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2143 /// [`self.file_name`]: struct.Path.html#method.file_name
2147 /// * [`None`], if there is no file name;
2148 /// * The entire file name if there is no embedded `.`;
2149 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2150 /// * Otherwise, the portion of the file name before the final `.`
2152 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2157 /// use std::path::Path;
2159 /// let path = Path::new("foo.rs");
2161 /// assert_eq!("foo", path.file_stem().unwrap());
2163 #[stable(feature = "rust1", since = "1.0.0")]
2164 pub fn file_stem(&self) -> Option<&OsStr> {
2165 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2168 /// Extracts the extension of [`self.file_name`], if possible.
2170 /// The extension is:
2172 /// * [`None`], if there is no file name;
2173 /// * [`None`], if there is no embedded `.`;
2174 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2175 /// * Otherwise, the portion of the file name after the final `.`
2177 /// [`self.file_name`]: struct.Path.html#method.file_name
2178 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2183 /// use std::path::Path;
2185 /// let path = Path::new("foo.rs");
2187 /// assert_eq!("rs", path.extension().unwrap());
2189 #[stable(feature = "rust1", since = "1.0.0")]
2190 pub fn extension(&self) -> Option<&OsStr> {
2191 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2194 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2196 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2198 /// [`PathBuf`]: struct.PathBuf.html
2199 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2204 /// use std::path::{Path, PathBuf};
2206 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2210 self._join(path.as_ref())
2213 fn _join(&self, path: &Path) -> PathBuf {
2214 let mut buf = self.to_path_buf();
2219 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2221 /// See [`PathBuf::set_file_name`] for more details.
2223 /// [`PathBuf`]: struct.PathBuf.html
2224 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2229 /// use std::path::{Path, PathBuf};
2231 /// let path = Path::new("/tmp/foo.txt");
2232 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2234 /// let path = Path::new("/tmp");
2235 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2239 self._with_file_name(file_name.as_ref())
2242 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2243 let mut buf = self.to_path_buf();
2244 buf.set_file_name(file_name);
2248 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2250 /// See [`PathBuf::set_extension`] for more details.
2252 /// [`PathBuf`]: struct.PathBuf.html
2253 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2258 /// use std::path::{Path, PathBuf};
2260 /// let path = Path::new("foo.rs");
2261 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2263 #[stable(feature = "rust1", since = "1.0.0")]
2264 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2265 self._with_extension(extension.as_ref())
2268 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2269 let mut buf = self.to_path_buf();
2270 buf.set_extension(extension);
2274 /// Produces an iterator over the [`Component`]s of the path.
2276 /// When parsing the path, there is a small amount of normalization:
2278 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2279 /// `a` and `b` as components.
2281 /// * Occurrences of `.` are normalized away, except if they are at the
2282 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2283 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2284 /// an additional [`CurDir`] component.
2286 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2288 /// Note that no other normalization takes place; in particular, `a/c`
2289 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2290 /// is a symbolic link (so its parent isn't `a`).
2295 /// use std::path::{Path, Component};
2296 /// use std::ffi::OsStr;
2298 /// let mut components = Path::new("/tmp/foo.txt").components();
2300 /// assert_eq!(components.next(), Some(Component::RootDir));
2301 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2302 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2303 /// assert_eq!(components.next(), None)
2306 /// [`Component`]: enum.Component.html
2307 /// [`CurDir`]: enum.Component.html#variant.CurDir
2308 #[stable(feature = "rust1", since = "1.0.0")]
2309 pub fn components(&self) -> Components {
2310 let prefix = parse_prefix(self.as_os_str());
2312 path: self.as_u8_slice(),
2314 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2315 has_redox_scheme(self.as_u8_slice()),
2316 front: State::Prefix,
2321 /// Produces an iterator over the path's components viewed as [`OsStr`]
2324 /// For more information about the particulars of how the path is separated
2325 /// into components, see [`components`].
2327 /// [`components`]: #method.components
2328 /// [`OsStr`]: ../ffi/struct.OsStr.html
2333 /// use std::path::{self, Path};
2334 /// use std::ffi::OsStr;
2336 /// let mut it = Path::new("/tmp/foo.txt").iter();
2337 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2338 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2339 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2340 /// assert_eq!(it.next(), None)
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 pub fn iter(&self) -> Iter {
2344 Iter { inner: self.components() }
2347 /// Returns an object that implements [`Display`] for safely printing paths
2348 /// that may contain non-Unicode data.
2350 /// [`Display`]: ../fmt/trait.Display.html
2355 /// use std::path::Path;
2357 /// let path = Path::new("/tmp/foo.rs");
2359 /// println!("{}", path.display());
2361 #[stable(feature = "rust1", since = "1.0.0")]
2362 pub fn display(&self) -> Display {
2363 Display { path: self }
2366 /// Queries the file system to get information about a file, directory, etc.
2368 /// This function will traverse symbolic links to query information about the
2369 /// destination file.
2371 /// This is an alias to [`fs::metadata`].
2373 /// [`fs::metadata`]: ../fs/fn.metadata.html
2378 /// use std::path::Path;
2380 /// let path = Path::new("/Minas/tirith");
2381 /// let metadata = path.metadata().expect("metadata call failed");
2382 /// println!("{:?}", metadata.file_type());
2384 #[stable(feature = "path_ext", since = "1.5.0")]
2385 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2389 /// Queries the metadata about a file without following symlinks.
2391 /// This is an alias to [`fs::symlink_metadata`].
2393 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2398 /// use std::path::Path;
2400 /// let path = Path::new("/Minas/tirith");
2401 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2402 /// println!("{:?}", metadata.file_type());
2404 #[stable(feature = "path_ext", since = "1.5.0")]
2405 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2406 fs::symlink_metadata(self)
2409 /// Returns the canonical, absolute form of the path with all intermediate
2410 /// components normalized and symbolic links resolved.
2412 /// This is an alias to [`fs::canonicalize`].
2414 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2419 /// use std::path::{Path, PathBuf};
2421 /// let path = Path::new("/foo/test/../test/bar.rs");
2422 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2424 #[stable(feature = "path_ext", since = "1.5.0")]
2425 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2426 fs::canonicalize(self)
2429 /// Reads a symbolic link, returning the file that the link points to.
2431 /// This is an alias to [`fs::read_link`].
2433 /// [`fs::read_link`]: ../fs/fn.read_link.html
2438 /// use std::path::Path;
2440 /// let path = Path::new("/laputa/sky_castle.rs");
2441 /// let path_link = path.read_link().expect("read_link call failed");
2443 #[stable(feature = "path_ext", since = "1.5.0")]
2444 pub fn read_link(&self) -> io::Result<PathBuf> {
2448 /// Returns an iterator over the entries within a directory.
2450 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2451 /// errors may be encountered after an iterator is initially constructed.
2453 /// This is an alias to [`fs::read_dir`].
2455 /// [`io::Result`]: ../io/type.Result.html
2456 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2457 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2462 /// use std::path::Path;
2464 /// let path = Path::new("/laputa");
2465 /// for entry in path.read_dir().expect("read_dir call failed") {
2466 /// if let Ok(entry) = entry {
2467 /// println!("{:?}", entry.path());
2471 #[stable(feature = "path_ext", since = "1.5.0")]
2472 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2476 /// Returns `true` if the path points at an existing entity.
2478 /// This function will traverse symbolic links to query information about the
2479 /// destination file. In case of broken symbolic links this will return `false`.
2481 /// If you cannot access the directory containing the file, e.g., because of a
2482 /// permission error, this will return `false`.
2487 /// use std::path::Path;
2488 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2493 /// This is a convenience function that coerces errors to false. If you want to
2494 /// check errors, call [fs::metadata].
2496 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2497 #[stable(feature = "path_ext", since = "1.5.0")]
2498 pub fn exists(&self) -> bool {
2499 fs::metadata(self).is_ok()
2502 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2504 /// This function will traverse symbolic links to query information about the
2505 /// destination file. In case of broken symbolic links this will return `false`.
2507 /// If you cannot access the directory containing the file, e.g., because of a
2508 /// permission error, this will return `false`.
2513 /// use std::path::Path;
2514 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2515 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2520 /// This is a convenience function that coerces errors to false. If you want to
2521 /// check errors, call [fs::metadata] and handle its Result. Then call
2522 /// [fs::Metadata::is_file] if it was Ok.
2524 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2525 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2526 #[stable(feature = "path_ext", since = "1.5.0")]
2527 pub fn is_file(&self) -> bool {
2528 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2531 /// Returns `true` if the path exists on disk and is pointing at a directory.
2533 /// This function will traverse symbolic links to query information about the
2534 /// destination file. In case of broken symbolic links this will return `false`.
2536 /// If you cannot access the directory containing the file, e.g., because of a
2537 /// permission error, this will return `false`.
2542 /// use std::path::Path;
2543 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2544 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2549 /// This is a convenience function that coerces errors to false. If you want to
2550 /// check errors, call [fs::metadata] and handle its Result. Then call
2551 /// [fs::Metadata::is_dir] if it was Ok.
2553 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2554 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2555 #[stable(feature = "path_ext", since = "1.5.0")]
2556 pub fn is_dir(&self) -> bool {
2557 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2560 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2563 /// [`Box`]: ../../std/boxed/struct.Box.html
2564 /// [`PathBuf`]: struct.PathBuf.html
2565 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2566 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2567 let rw = Box::into_raw(self) as *mut OsStr;
2568 let inner = unsafe { Box::from_raw(rw) };
2569 PathBuf { inner: OsString::from(inner) }
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 impl AsRef<OsStr> for Path {
2575 fn as_ref(&self) -> &OsStr {
2580 #[stable(feature = "rust1", since = "1.0.0")]
2581 impl fmt::Debug for Path {
2582 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2583 fmt::Debug::fmt(&self.inner, formatter)
2587 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2589 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2590 /// [`Display`] trait in a way that mitigates that. It is created by the
2591 /// [`display`][`Path::display`] method on [`Path`].
2596 /// use std::path::Path;
2598 /// let path = Path::new("/tmp/foo.rs");
2600 /// println!("{}", path.display());
2603 /// [`Display`]: ../../std/fmt/trait.Display.html
2604 /// [`format!`]: ../../std/macro.format.html
2605 /// [`Path`]: struct.Path.html
2606 /// [`Path::display`]: struct.Path.html#method.display
2607 #[stable(feature = "rust1", since = "1.0.0")]
2608 pub struct Display<'a> {
2612 #[stable(feature = "rust1", since = "1.0.0")]
2613 impl fmt::Debug for Display<'_> {
2614 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2615 fmt::Debug::fmt(&self.path, f)
2619 #[stable(feature = "rust1", since = "1.0.0")]
2620 impl fmt::Display for Display<'_> {
2621 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2622 self.path.inner.display(f)
2626 #[stable(feature = "rust1", since = "1.0.0")]
2627 impl cmp::PartialEq for Path {
2628 fn eq(&self, other: &Path) -> bool {
2629 self.components().eq(other.components())
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl Hash for Path {
2635 fn hash<H: Hasher>(&self, h: &mut H) {
2636 for component in self.components() {
2642 #[stable(feature = "rust1", since = "1.0.0")]
2643 impl cmp::Eq for Path {}
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 impl cmp::PartialOrd for Path {
2647 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2648 self.components().partial_cmp(other.components())
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 impl cmp::Ord for Path {
2654 fn cmp(&self, other: &Path) -> cmp::Ordering {
2655 self.components().cmp(other.components())
2659 #[stable(feature = "rust1", since = "1.0.0")]
2660 impl AsRef<Path> for Path {
2661 fn as_ref(&self) -> &Path {
2666 #[stable(feature = "rust1", since = "1.0.0")]
2667 impl AsRef<Path> for OsStr {
2668 fn as_ref(&self) -> &Path {
2673 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2674 impl AsRef<Path> for Cow<'_, OsStr> {
2675 fn as_ref(&self) -> &Path {
2680 #[stable(feature = "rust1", since = "1.0.0")]
2681 impl AsRef<Path> for OsString {
2682 fn as_ref(&self) -> &Path {
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 impl AsRef<Path> for str {
2689 fn as_ref(&self) -> &Path {
2694 #[stable(feature = "rust1", since = "1.0.0")]
2695 impl AsRef<Path> for String {
2696 fn as_ref(&self) -> &Path {
2701 #[stable(feature = "rust1", since = "1.0.0")]
2702 impl AsRef<Path> for PathBuf {
2703 fn as_ref(&self) -> &Path {
2708 #[stable(feature = "path_into_iter", since = "1.6.0")]
2709 impl<'a> IntoIterator for &'a PathBuf {
2710 type Item = &'a OsStr;
2711 type IntoIter = Iter<'a>;
2712 fn into_iter(self) -> Iter<'a> { self.iter() }
2715 #[stable(feature = "path_into_iter", since = "1.6.0")]
2716 impl<'a> IntoIterator for &'a Path {
2717 type Item = &'a OsStr;
2718 type IntoIter = Iter<'a>;
2719 fn into_iter(self) -> Iter<'a> { self.iter() }
2722 macro_rules! impl_cmp {
2723 ($lhs:ty, $rhs: ty) => {
2724 #[stable(feature = "partialeq_path", since = "1.6.0")]
2725 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2727 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2730 #[stable(feature = "partialeq_path", since = "1.6.0")]
2731 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2733 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2736 #[stable(feature = "cmp_path", since = "1.8.0")]
2737 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2739 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2740 <Path as PartialOrd>::partial_cmp(self, other)
2744 #[stable(feature = "cmp_path", since = "1.8.0")]
2745 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2747 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2748 <Path as PartialOrd>::partial_cmp(self, other)
2754 impl_cmp!(PathBuf, Path);
2755 impl_cmp!(PathBuf, &'a Path);
2756 impl_cmp!(Cow<'a, Path>, Path);
2757 impl_cmp!(Cow<'a, Path>, &'b Path);
2758 impl_cmp!(Cow<'a, Path>, PathBuf);
2760 macro_rules! impl_cmp_os_str {
2761 ($lhs:ty, $rhs: ty) => {
2762 #[stable(feature = "cmp_path", since = "1.8.0")]
2763 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2765 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2768 #[stable(feature = "cmp_path", since = "1.8.0")]
2769 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2771 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2774 #[stable(feature = "cmp_path", since = "1.8.0")]
2775 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2777 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2778 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2782 #[stable(feature = "cmp_path", since = "1.8.0")]
2783 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2785 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2786 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2792 impl_cmp_os_str!(PathBuf, OsStr);
2793 impl_cmp_os_str!(PathBuf, &'a OsStr);
2794 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2795 impl_cmp_os_str!(PathBuf, OsString);
2796 impl_cmp_os_str!(Path, OsStr);
2797 impl_cmp_os_str!(Path, &'a OsStr);
2798 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2799 impl_cmp_os_str!(Path, OsString);
2800 impl_cmp_os_str!(&'a Path, OsStr);
2801 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2802 impl_cmp_os_str!(&'a Path, OsString);
2803 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2804 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2805 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2807 #[stable(since = "1.7.0", feature = "strip_prefix")]
2808 impl fmt::Display for StripPrefixError {
2809 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2810 self.description().fmt(f)
2814 #[stable(since = "1.7.0", feature = "strip_prefix")]
2815 impl Error for StripPrefixError {
2816 fn description(&self) -> &str { "prefix not found" }
2827 ($path:expr, iter: $iter:expr) => (
2829 let path = Path::new($path);
2831 // Forward iteration
2832 let comps = path.iter()
2833 .map(|p| p.to_string_lossy().into_owned())
2834 .collect::<Vec<String>>();
2835 let exp: &[&str] = &$iter;
2836 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2837 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2840 // Reverse iteration
2841 let comps = Path::new($path).iter().rev()
2842 .map(|p| p.to_string_lossy().into_owned())
2843 .collect::<Vec<String>>();
2844 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2845 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2850 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2852 let path = Path::new($path);
2854 let act_root = path.has_root();
2855 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2856 $has_root, act_root);
2858 let act_abs = path.is_absolute();
2859 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2860 $is_absolute, act_abs);
2864 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2866 let path = Path::new($path);
2868 let parent = path.parent().map(|p| p.to_str().unwrap());
2869 let exp_parent: Option<&str> = $parent;
2870 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2871 exp_parent, parent);
2873 let file = path.file_name().map(|p| p.to_str().unwrap());
2874 let exp_file: Option<&str> = $file;
2875 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2880 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2882 let path = Path::new($path);
2884 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2885 let exp_stem: Option<&str> = $file_stem;
2886 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2889 let ext = path.extension().map(|p| p.to_str().unwrap());
2890 let exp_ext: Option<&str> = $extension;
2891 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2896 ($path:expr, iter: $iter:expr,
2897 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2898 parent: $parent:expr, file_name: $file:expr,
2899 file_stem: $file_stem:expr, extension: $extension:expr) => (
2901 t!($path, iter: $iter);
2902 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2903 t!($path, parent: $parent, file_name: $file);
2904 t!($path, file_stem: $file_stem, extension: $extension);
2913 let static_path = Path::new("/home/foo");
2914 let static_cow_path: Cow<'static, Path> = static_path.into();
2915 let pathbuf = PathBuf::from("/home/foo");
2918 let path: &Path = &pathbuf;
2919 let borrowed_cow_path: Cow<Path> = path.into();
2921 assert_eq!(static_cow_path, borrowed_cow_path);
2924 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2926 assert_eq!(static_cow_path, owned_cow_path);
2931 pub fn test_decompositions_unix() {
2947 file_name: Some("foo"),
2948 file_stem: Some("foo"),
2967 file_name: Some("foo"),
2968 file_stem: Some("foo"),
2977 file_name: Some("foo"),
2978 file_stem: Some("foo"),
2987 file_name: Some("foo"),
2988 file_stem: Some("foo"),
2993 iter: ["foo", "bar"],
2996 parent: Some("foo"),
2997 file_name: Some("bar"),
2998 file_stem: Some("bar"),
3003 iter: ["/", "foo", "bar"],
3006 parent: Some("/foo"),
3007 file_name: Some("bar"),
3008 file_stem: Some("bar"),
3017 file_name: Some("foo"),
3018 file_stem: Some("foo"),
3023 iter: ["/", "foo", "bar"],
3026 parent: Some("///foo"),
3027 file_name: Some("bar"),
3028 file_stem: Some("bar"),
3067 file_name: Some("foo"),
3068 file_stem: Some("foo"),
3073 iter: ["foo", ".."],
3076 parent: Some("foo"),
3087 file_name: Some("foo"),
3088 file_stem: Some("foo"),
3093 iter: ["foo", "bar"],
3096 parent: Some("foo"),
3097 file_name: Some("bar"),
3098 file_stem: Some("bar"),
3103 iter: ["foo", ".."],
3106 parent: Some("foo"),
3113 iter: ["foo", "..", "bar"],
3116 parent: Some("foo/.."),
3117 file_name: Some("bar"),
3118 file_stem: Some("bar"),
3127 file_name: Some("a"),
3128 file_stem: Some("a"),
3157 file_name: Some("b"),
3158 file_stem: Some("b"),
3167 file_name: Some("b"),
3168 file_stem: Some("b"),
3177 file_name: Some("b"),
3178 file_stem: Some("b"),
3183 iter: ["a", "b", "c"],
3186 parent: Some("a/b"),
3187 file_name: Some("c"),
3188 file_stem: Some("c"),
3197 file_name: Some(".foo"),
3198 file_stem: Some(".foo"),
3205 pub fn test_decompositions_windows() {
3221 file_name: Some("foo"),
3222 file_stem: Some("foo"),
3277 iter: ["\\", "foo"],
3281 file_name: Some("foo"),
3282 file_stem: Some("foo"),
3291 file_name: Some("foo"),
3292 file_stem: Some("foo"),
3297 iter: ["\\", "foo"],
3301 file_name: Some("foo"),
3302 file_stem: Some("foo"),
3307 iter: ["foo", "bar"],
3310 parent: Some("foo"),
3311 file_name: Some("bar"),
3312 file_stem: Some("bar"),
3317 iter: ["\\", "foo", "bar"],
3320 parent: Some("/foo"),
3321 file_name: Some("bar"),
3322 file_stem: Some("bar"),
3327 iter: ["\\", "foo"],
3331 file_name: Some("foo"),
3332 file_stem: Some("foo"),
3337 iter: ["\\", "foo", "bar"],
3340 parent: Some("///foo"),
3341 file_name: Some("bar"),
3342 file_stem: Some("bar"),
3381 file_name: Some("foo"),
3382 file_stem: Some("foo"),
3387 iter: ["foo", ".."],
3390 parent: Some("foo"),
3401 file_name: Some("foo"),
3402 file_stem: Some("foo"),
3407 iter: ["foo", "bar"],
3410 parent: Some("foo"),
3411 file_name: Some("bar"),
3412 file_stem: Some("bar"),
3417 iter: ["foo", ".."],
3420 parent: Some("foo"),
3427 iter: ["foo", "..", "bar"],
3430 parent: Some("foo/.."),
3431 file_name: Some("bar"),
3432 file_stem: Some("bar"),
3441 file_name: Some("a"),
3442 file_stem: Some("a"),
3471 file_name: Some("b"),
3472 file_stem: Some("b"),
3481 file_name: Some("b"),
3482 file_stem: Some("b"),
3491 file_name: Some("b"),
3492 file_stem: Some("b"),
3497 iter: ["a", "b", "c"],
3500 parent: Some("a/b"),
3501 file_name: Some("c"),
3502 file_stem: Some("c"),
3506 iter: ["a", "b", "c"],
3509 parent: Some("a\\b"),
3510 file_name: Some("c"),
3511 file_stem: Some("c"),
3520 file_name: Some("a"),
3521 file_stem: Some("a"),
3526 iter: ["c:", "\\", "foo.txt"],
3529 parent: Some("c:\\"),
3530 file_name: Some("foo.txt"),
3531 file_stem: Some("foo"),
3532 extension: Some("txt")
3535 t!("\\\\server\\share\\foo.txt",
3536 iter: ["\\\\server\\share", "\\", "foo.txt"],
3539 parent: Some("\\\\server\\share\\"),
3540 file_name: Some("foo.txt"),
3541 file_stem: Some("foo"),
3542 extension: Some("txt")
3545 t!("\\\\server\\share",
3546 iter: ["\\\\server\\share", "\\"],
3556 iter: ["\\", "server"],
3560 file_name: Some("server"),
3561 file_stem: Some("server"),
3565 t!("\\\\?\\bar\\foo.txt",
3566 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3569 parent: Some("\\\\?\\bar\\"),
3570 file_name: Some("foo.txt"),
3571 file_stem: Some("foo"),
3572 extension: Some("txt")
3576 iter: ["\\\\?\\bar"],
3595 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3596 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3599 parent: Some("\\\\?\\UNC\\server\\share\\"),
3600 file_name: Some("foo.txt"),
3601 file_stem: Some("foo"),
3602 extension: Some("txt")
3605 t!("\\\\?\\UNC\\server",
3606 iter: ["\\\\?\\UNC\\server"],
3616 iter: ["\\\\?\\UNC\\"],
3625 t!("\\\\?\\C:\\foo.txt",
3626 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3629 parent: Some("\\\\?\\C:\\"),
3630 file_name: Some("foo.txt"),
3631 file_stem: Some("foo"),
3632 extension: Some("txt")
3637 iter: ["\\\\?\\C:", "\\"],
3648 iter: ["\\\\?\\C:"],
3658 t!("\\\\?\\foo/bar",
3659 iter: ["\\\\?\\foo/bar"],
3670 iter: ["\\\\?\\C:/foo"],
3680 t!("\\\\.\\foo\\bar",
3681 iter: ["\\\\.\\foo", "\\", "bar"],
3684 parent: Some("\\\\.\\foo\\"),
3685 file_name: Some("bar"),
3686 file_stem: Some("bar"),
3692 iter: ["\\\\.\\foo", "\\"],
3702 t!("\\\\.\\foo/bar",
3703 iter: ["\\\\.\\foo/bar", "\\"],
3713 t!("\\\\.\\foo\\bar/baz",
3714 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3717 parent: Some("\\\\.\\foo\\bar"),
3718 file_name: Some("baz"),
3719 file_stem: Some("baz"),
3725 iter: ["\\\\.\\", "\\"],
3735 iter: ["\\\\?\\a", "\\", "b"],
3738 parent: Some("\\\\?\\a\\"),
3739 file_name: Some("b"),
3740 file_stem: Some("b"),
3746 pub fn test_stem_ext() {
3748 file_stem: Some("foo"),
3753 file_stem: Some("foo"),
3758 file_stem: Some(".foo"),
3763 file_stem: Some("foo"),
3764 extension: Some("txt")
3768 file_stem: Some("foo.bar"),
3769 extension: Some("txt")
3773 file_stem: Some("foo.bar"),
3794 pub fn test_push() {
3796 ($path:expr, $push:expr, $expected:expr) => ( {
3797 let mut actual = PathBuf::from($path);
3799 assert!(actual.to_str() == Some($expected),
3800 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3801 $push, $path, $expected, actual.to_str().unwrap());
3806 tp!("", "foo", "foo");
3807 tp!("foo", "bar", "foo/bar");
3808 tp!("foo/", "bar", "foo/bar");
3809 tp!("foo//", "bar", "foo//bar");
3810 tp!("foo/.", "bar", "foo/./bar");
3811 tp!("foo./.", "bar", "foo././bar");
3812 tp!("foo", "", "foo/");
3813 tp!("foo", ".", "foo/.");
3814 tp!("foo", "..", "foo/..");
3815 tp!("foo", "/", "/");
3816 tp!("/foo/bar", "/", "/");
3817 tp!("/foo/bar", "/baz", "/baz");
3818 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3820 tp!("", "foo", "foo");
3821 tp!("foo", "bar", r"foo\bar");
3822 tp!("foo/", "bar", r"foo/bar");
3823 tp!(r"foo\", "bar", r"foo\bar");
3824 tp!("foo//", "bar", r"foo//bar");
3825 tp!(r"foo\\", "bar", r"foo\\bar");
3826 tp!("foo/.", "bar", r"foo/.\bar");
3827 tp!("foo./.", "bar", r"foo./.\bar");
3828 tp!(r"foo\.", "bar", r"foo\.\bar");
3829 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3830 tp!("foo", "", "foo\\");
3831 tp!("foo", ".", r"foo\.");
3832 tp!("foo", "..", r"foo\..");
3833 tp!("foo", "/", "/");
3834 tp!("foo", r"\", r"\");
3835 tp!("/foo/bar", "/", "/");
3836 tp!(r"\foo\bar", r"\", r"\");
3837 tp!("/foo/bar", "/baz", "/baz");
3838 tp!("/foo/bar", r"\baz", r"\baz");
3839 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3840 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3842 tp!("c:\\", "windows", "c:\\windows");
3843 tp!("c:", "windows", "c:windows");
3845 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3846 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3847 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3848 tp!("a\\b", "\\c\\d", "\\c\\d");
3849 tp!("a\\b", ".", "a\\b\\.");
3850 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3851 tp!("a\\b", "C:a.txt", "C:a.txt");
3852 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3853 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3854 tp!("C:\\a\\b\\c", "C:d", "C:d");
3855 tp!("C:a\\b\\c", "C:d", "C:d");
3856 tp!("C:", r"a\b\c", r"C:a\b\c");
3857 tp!("C:", r"..\a", r"C:..\a");
3858 tp!("\\\\server\\share\\foo",
3860 "\\\\server\\share\\foo\\bar");
3861 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3862 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3863 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3864 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3865 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3866 tp!("\\\\?\\UNC\\server\\share\\foo",
3868 "\\\\?\\UNC\\server\\share\\foo\\bar");
3869 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3870 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3872 // Note: modified from old path API
3873 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3876 "\\\\?\\UNC\\server\\share",
3877 "\\\\?\\UNC\\server\\share");
3878 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3879 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3880 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3881 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3883 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3890 ($path:expr, $expected:expr, $output:expr) => ( {
3891 let mut actual = PathBuf::from($path);
3892 let output = actual.pop();
3893 assert!(actual.to_str() == Some($expected) && output == $output,
3894 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3895 $path, $expected, $output,
3896 actual.to_str().unwrap(), output);
3901 tp!("/", "/", false);
3902 tp!("foo", "", true);
3904 tp!("/foo", "/", true);
3905 tp!("/foo/bar", "/foo", true);
3906 tp!("foo/bar", "foo", true);
3907 tp!("foo/.", "", true);
3908 tp!("foo//bar", "foo", true);
3911 tp!("a\\b\\c", "a\\b", true);
3912 tp!("\\a", "\\", true);
3913 tp!("\\", "\\", false);
3915 tp!("C:\\a\\b", "C:\\a", true);
3916 tp!("C:\\a", "C:\\", true);
3917 tp!("C:\\", "C:\\", false);
3918 tp!("C:a\\b", "C:a", true);
3919 tp!("C:a", "C:", true);
3920 tp!("C:", "C:", false);
3921 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3922 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3923 tp!("\\\\server\\share", "\\\\server\\share", false);
3924 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3925 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3926 tp!("\\\\?\\a", "\\\\?\\a", false);
3927 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3928 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3929 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3930 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3931 "\\\\?\\UNC\\server\\share\\a",
3933 tp!("\\\\?\\UNC\\server\\share\\a",
3934 "\\\\?\\UNC\\server\\share\\",
3936 tp!("\\\\?\\UNC\\server\\share",
3937 "\\\\?\\UNC\\server\\share",
3939 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3940 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3941 tp!("\\\\.\\a", "\\\\.\\a", false);
3943 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3948 pub fn test_set_file_name() {
3950 ($path:expr, $file:expr, $expected:expr) => ( {
3951 let mut p = PathBuf::from($path);
3952 p.set_file_name($file);
3953 assert!(p.to_str() == Some($expected),
3954 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3955 $path, $file, $expected,
3956 p.to_str().unwrap());
3960 tfn!("foo", "foo", "foo");
3961 tfn!("foo", "bar", "bar");
3962 tfn!("foo", "", "");
3963 tfn!("", "foo", "foo");
3965 tfn!(".", "foo", "./foo");
3966 tfn!("foo/", "bar", "bar");
3967 tfn!("foo/.", "bar", "bar");
3968 tfn!("..", "foo", "../foo");
3969 tfn!("foo/..", "bar", "foo/../bar");
3970 tfn!("/", "foo", "/foo");
3972 tfn!(".", "foo", r".\foo");
3973 tfn!(r"foo\", "bar", r"bar");
3974 tfn!(r"foo\.", "bar", r"bar");
3975 tfn!("..", "foo", r"..\foo");
3976 tfn!(r"foo\..", "bar", r"foo\..\bar");
3977 tfn!(r"\", "foo", r"\foo");
3982 pub fn test_set_extension() {
3984 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3985 let mut p = PathBuf::from($path);
3986 let output = p.set_extension($ext);
3987 assert!(p.to_str() == Some($expected) && output == $output,
3988 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3989 $path, $ext, $expected, $output,
3990 p.to_str().unwrap(), output);
3994 tfe!("foo", "txt", "foo.txt", true);
3995 tfe!("foo.bar", "txt", "foo.txt", true);
3996 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3997 tfe!(".test", "txt", ".test.txt", true);
3998 tfe!("foo.txt", "", "foo", true);
3999 tfe!("foo", "", "foo", true);
4000 tfe!("", "foo", "", false);
4001 tfe!(".", "foo", ".", false);
4002 tfe!("foo/", "bar", "foo.bar", true);
4003 tfe!("foo/.", "bar", "foo.bar", true);
4004 tfe!("..", "foo", "..", false);
4005 tfe!("foo/..", "bar", "foo/..", false);
4006 tfe!("/", "foo", "/", false);
4010 fn test_eq_receivers() {
4013 let borrowed: &Path = Path::new("foo/bar");
4014 let mut owned: PathBuf = PathBuf::new();
4017 let borrowed_cow: Cow<Path> = borrowed.into();
4018 let owned_cow: Cow<Path> = owned.clone().into();
4021 ($($current:expr),+) => {
4023 assert_eq!($current, borrowed);
4024 assert_eq!($current, owned);
4025 assert_eq!($current, borrowed_cow);
4026 assert_eq!($current, owned_cow);
4031 t!(borrowed, owned, borrowed_cow, owned_cow);
4035 pub fn test_compare() {
4036 use hash::{Hash, Hasher};
4037 use collections::hash_map::DefaultHasher;
4039 fn hash<T: Hash>(t: T) -> u64 {
4040 let mut s = DefaultHasher::new();
4046 ($path1:expr, $path2:expr, eq: $eq:expr,
4047 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4048 relative_from: $relative_from:expr) => ({
4049 let path1 = Path::new($path1);
4050 let path2 = Path::new($path2);
4052 let eq = path1 == path2;
4053 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4054 $path1, $path2, $eq, eq);
4055 assert!($eq == (hash(path1) == hash(path2)),
4056 "{:?} == {:?}, expected {:?}, got {} and {}",
4057 $path1, $path2, $eq, hash(path1), hash(path2));
4059 let starts_with = path1.starts_with(path2);
4060 assert!(starts_with == $starts_with,
4061 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4062 $starts_with, starts_with);
4064 let ends_with = path1.ends_with(path2);
4065 assert!(ends_with == $ends_with,
4066 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4067 $ends_with, ends_with);
4069 let relative_from = path1.strip_prefix(path2)
4070 .map(|p| p.to_str().unwrap())
4072 let exp: Option<&str> = $relative_from;
4073 assert!(relative_from == exp,
4074 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4075 $path1, $path2, exp, relative_from);
4083 relative_from: Some("")
4090 relative_from: Some("foo")
4104 relative_from: Some("")
4111 relative_from: Some("")
4114 tc!("foo/bar", "foo",
4118 relative_from: Some("bar")
4121 tc!("foo/bar/baz", "foo/bar",
4125 relative_from: Some("baz")
4128 tc!("foo/bar", "foo/bar/baz",
4135 tc!("./foo/bar/", ".",
4139 relative_from: Some("foo/bar")
4143 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4144 r"c:\src\rust\cargo-test\test",
4148 relative_from: Some("Cargo.toml")
4151 tc!(r"c:\foo", r"C:\foo",
4155 relative_from: Some("")
4161 fn test_components_debug() {
4162 let path = Path::new("/tmp");
4164 let mut components = path.components();
4166 let expected = "Components([RootDir, Normal(\"tmp\")])";
4167 let actual = format!("{:?}", components);
4168 assert_eq!(expected, actual);
4170 let _ = components.next().unwrap();
4171 let expected = "Components([Normal(\"tmp\")])";
4172 let actual = format!("{:?}", components);
4173 assert_eq!(expected, actual);
4175 let _ = components.next().unwrap();
4176 let expected = "Components([])";
4177 let actual = format!("{:?}", components);
4178 assert_eq!(expected, actual);
4183 fn test_iter_debug() {
4184 let path = Path::new("/tmp");
4186 let mut iter = path.iter();
4188 let expected = "Iter([\"/\", \"tmp\"])";
4189 let actual = format!("{:?}", iter);
4190 assert_eq!(expected, actual);
4192 let _ = iter.next().unwrap();
4193 let expected = "Iter([\"tmp\"])";
4194 let actual = format!("{:?}", iter);
4195 assert_eq!(expected, actual);
4197 let _ = iter.next().unwrap();
4198 let expected = "Iter([])";
4199 let actual = format!("{:?}", iter);
4200 assert_eq!(expected, actual);
4205 let orig: &str = "some/sort/of/path";
4206 let path = Path::new(orig);
4207 let boxed: Box<Path> = Box::from(path);
4208 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4209 assert_eq!(path, &*boxed);
4210 assert_eq!(&*boxed, &*path_buf);
4211 assert_eq!(&*path_buf, path);
4215 fn test_clone_into() {
4216 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4217 let path = Path::new("short");
4218 path.clone_into(&mut path_buf);
4219 assert_eq!(path, path_buf);
4220 assert!(path_buf.into_os_string().capacity() >= 15);
4224 fn display_format_flags() {
4225 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4226 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4231 let orig = "hello/world";
4232 let path = Path::new(orig);
4233 let rc: Rc<Path> = Rc::from(path);
4234 let arc: Arc<Path> = Arc::from(path);
4236 assert_eq!(&*rc, path);
4237 assert_eq!(&*arc, path);
4239 let rc2: Rc<Path> = Rc::from(path.to_owned());
4240 let arc2: Arc<Path> = Arc::from(path.to_owned());
4242 assert_eq!(&*rc2, path);
4243 assert_eq!(&*arc2, path);