//! Cross-platform path manipulation.
//!
-//! This module provides two types, `PathBuf` and `Path` (akin to `String` and
-//! `str`), for working with paths abstractly. These types are thin wrappers
-//! around `OsString` and `OsStr` respectively, meaning that they work directly
+//! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
+//! and [`str`]), for working with paths abstractly. These types are thin wrappers
+//! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
//! on strings according to the local platform's path syntax.
//!
+//! Paths can be parsed into [`Component`]s by iterating over the structure
+//! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
+//! correspond to the substrings between path separators (`/` or `\`). You can
+//! reconstruct an equivalent path from components with the [`push`] method on
+//! [`PathBuf`]; note that the paths may differ syntactically by the
+//! normalization described in the documentation for the [`components`] method.
+//!
//! ## Simple usage
//!
//! Path manipulation includes both parsing components from slices and building
//! new owned paths.
//!
-//! To parse a path, you can create a `Path` slice from a `str`
+//! To parse a path, you can create a [`Path`] slice from a [`str`]
//! slice and start asking questions:
//!
-//! ```rust
+//! ```
//! use std::path::Path;
+//! use std::ffi::OsStr;
//!
//! let path = Path::new("/tmp/foo/bar.txt");
-//! let file = path.file_name();
+//!
+//! let parent = path.parent();
+//! assert_eq!(parent, Some(Path::new("/tmp/foo")));
+//!
+//! let file_stem = path.file_stem();
+//! assert_eq!(file_stem, Some(OsStr::new("bar")));
+//!
//! let extension = path.extension();
-//! let parent_dir = path.parent();
+//! assert_eq!(extension, Some(OsStr::new("txt")));
//! ```
//!
-//! To build or modify paths, use `PathBuf`:
+//! To build or modify paths, use [`PathBuf`]:
//!
-//! ```rust
+//! ```
//! use std::path::PathBuf;
//!
+//! // This way works...
//! let mut path = PathBuf::from("c:\\");
+//!
//! path.push("windows");
//! path.push("system32");
-//! path.set_extension("dll");
-//! ```
-//!
-//! ## Path components and normalization
-//!
-//! The path APIs are built around the notion of "components", which roughly
-//! correspond to the substrings between path separators (`/` and, on Windows,
-//! `\`). The APIs for path parsing are largely specified in terms of the path's
-//! components, so it's important to clearly understand how those are
-//! determined.
-//!
-//! A path can always be reconstructed into an *equivalent* path by
-//! putting together its components via `push`. Syntactically, the
-//! paths may differ by the normalization described below.
-//!
-//! ### Component types
-//!
-//! Components come in several types:
-//!
-//! * Normal components are the default: standard references to files or
-//! directories. The path `a/b` has two normal components, `a` and `b`.
//!
-//! * Current directory components represent the `.` character. For example,
-//! `./a` has a current directory component and a normal component `a`.
-//!
-//! * The root directory component represents a separator that designates
-//! starting from root. For example, `/a/b` has a root directory component
-//! followed by normal components `a` and `b`.
-//!
-//! On Windows, an additional component type comes into play:
-//!
-//! * Prefix components, of which there is a large variety. For example, `C:`
-//! and `\\server\share` are prefixes. The path `C:windows` has a prefix
-//! component `C:` and a normal component `windows`; the path `C:\windows` has a
-//! prefix component `C:`, a root directory component, and a normal component
-//! `windows`.
-//!
-//! ### Normalization
-//!
-//! Aside from splitting on the separator(s), there is a small amount of
-//! "normalization":
+//! path.set_extension("dll");
//!
-//! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
-//! and `b`.
+//! // ... but push is best used if you don't know everything up
+//! // front. If you do, this way is better:
+//! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
+//! ```
//!
-//! * Occurrences of `.` are normalized away, *except* if they are at
-//! the beginning of the path (in which case they are often meaningful
-//! in terms of path searching). So, for example, `a/./b`, `a/b/`,
-//! `/a/b/.` and `a/b` all have components `a` and `b`, but `./a/b`
-//! has a leading current directory component.
+//! [`Component`]: ../../std/path/enum.Component.html
+//! [`components`]: ../../std/path/struct.Path.html#method.components
+//! [`PathBuf`]: ../../std/path/struct.PathBuf.html
+//! [`Path`]: ../../std/path/struct.Path.html
+//! [`push`]: ../../std/path/struct.PathBuf.html#method.push
+//! [`String`]: ../../std/string/struct.String.html
//!
-//! No other normalization takes place by default. In particular,
-//! `a/c` and `a/b/../c` are distinct, to account for the possibility
-//! that `b` is a symbolic link (so its parent isn't `a`). Further
-//! normalization is possible to build on top of the components APIs,
-//! and will be included in this library in the near future.
+//! [`str`]: ../../std/primitive.str.html
+//! [`OsString`]: ../../std/ffi/struct.OsString.html
+//! [`OsStr`]: ../../std/ffi/struct.OsStr.html
#![stable(feature = "rust1", since = "1.0.0")]
-use ascii::*;
-#[allow(deprecated)]
-use borrow::{Borrow, IntoCow, ToOwned, Cow};
+use borrow::{Borrow, Cow};
use cmp;
use error::Error;
use fmt;
use fs;
use hash::{Hash, Hasher};
use io;
-use iter;
-use mem;
+use iter::{self, FusedIterator};
use ops::{self, Deref};
-use string::String;
-use vec::Vec;
use ffi::{OsStr, OsString};
-use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
+use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
////////////////////////////////////////////////////////////////////////////////
// GENERAL NOTES
// OsStr APIs for parsing, but it will take a while for those to become
// available.
-////////////////////////////////////////////////////////////////////////////////
-// Platform-specific definitions
-////////////////////////////////////////////////////////////////////////////////
-
-// The following modules give the most basic tools for parsing paths on various
-// platforms. The bulk of the code is devoted to parsing prefixes on Windows.
-
-#[cfg(unix)]
-mod platform {
- use super::Prefix;
- use ffi::OsStr;
-
- #[inline]
- pub fn is_sep_byte(b: u8) -> bool {
- b == b'/'
- }
-
- #[inline]
- pub fn is_verbatim_sep(b: u8) -> bool {
- b == b'/'
- }
-
- pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
- None
- }
-
- pub const MAIN_SEP_STR: &'static str = "/";
- pub const MAIN_SEP: char = '/';
-}
-
-#[cfg(windows)]
-mod platform {
- use ascii::*;
-
- use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
- use ffi::OsStr;
-
- #[inline]
- pub fn is_sep_byte(b: u8) -> bool {
- b == b'/' || b == b'\\'
- }
-
- #[inline]
- pub fn is_verbatim_sep(b: u8) -> bool {
- b == b'\\'
- }
-
- pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
- use super::Prefix::*;
- unsafe {
- // The unsafety here stems from converting between &OsStr and &[u8]
- // and back. This is safe to do because (1) we only look at ASCII
- // contents of the encoding and (2) new &OsStr values are produced
- // only from ASCII-bounded slices of existing &OsStr values.
- let mut path = os_str_as_u8_slice(path);
-
- if path.starts_with(br"\\") {
- // \\
- path = &path[2..];
- if path.starts_with(br"?\") {
- // \\?\
- path = &path[2..];
- if path.starts_with(br"UNC\") {
- // \\?\UNC\server\share
- path = &path[4..];
- let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
- Some((server, share)) =>
- (u8_slice_as_os_str(server), u8_slice_as_os_str(share)),
- None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])),
- };
- return Some(VerbatimUNC(server, share));
- } else {
- // \\?\path
- let idx = path.iter().position(|&b| b == b'\\');
- if idx == Some(2) && path[1] == b':' {
- let c = path[0];
- if c.is_ascii() && (c as char).is_alphabetic() {
- // \\?\C:\ path
- return Some(VerbatimDisk(c.to_ascii_uppercase()));
- }
- }
- let slice = &path[..idx.unwrap_or(path.len())];
- return Some(Verbatim(u8_slice_as_os_str(slice)));
- }
- } else if path.starts_with(b".\\") {
- // \\.\path
- path = &path[2..];
- let pos = path.iter().position(|&b| b == b'\\');
- let slice = &path[..pos.unwrap_or(path.len())];
- return Some(DeviceNS(u8_slice_as_os_str(slice)));
- }
- match parse_two_comps(path, is_sep_byte) {
- Some((server, share)) if !server.is_empty() && !share.is_empty() => {
- // \\server\share
- return Some(UNC(u8_slice_as_os_str(server), u8_slice_as_os_str(share)));
- }
- _ => (),
- }
- } else if path.len() > 1 && path[1] == b':' {
- // C:
- let c = path[0];
- if c.is_ascii() && (c as char).is_alphabetic() {
- return Some(Disk(c.to_ascii_uppercase()));
- }
- }
- return None;
- }
-
- fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
- let first = match path.iter().position(|x| f(*x)) {
- None => return None,
- Some(x) => &path[..x],
- };
- path = &path[(first.len() + 1)..];
- let idx = path.iter().position(|x| f(*x));
- let second = &path[..idx.unwrap_or(path.len())];
- Some((first, second))
- }
- }
-
- pub const MAIN_SEP_STR: &'static str = "\\";
- pub const MAIN_SEP: char = '\\';
-}
-
////////////////////////////////////////////////////////////////////////////////
// Windows Prefixes
////////////////////////////////////////////////////////////////////////////////
-/// Path prefixes (Windows only).
+/// Windows path prefixes, e.g. `C:` or `\\server\share`.
+///
+/// Windows uses a variety of path prefix styles, including references to drive
+/// volumes (like `C:`), network shared folders (like `\\server\share`), and
+/// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
+/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
+/// no normalization is performed.
+///
+/// # Examples
+///
+/// ```
+/// use std::path::{Component, Path, Prefix};
+/// use std::path::Prefix::*;
+/// use std::ffi::OsStr;
+///
+/// fn get_path_prefix(s: &str) -> Prefix {
+/// let path = Path::new(s);
+/// match path.components().next().unwrap() {
+/// Component::Prefix(prefix_component) => prefix_component.kind(),
+/// _ => panic!(),
+/// }
+/// }
///
-/// Windows uses a variety of path styles, including references to drive
-/// volumes (like `C:`), network shared folders (like `\\server\share`) and
-/// others. In addition, some path prefixes are "verbatim", in which case
-/// `/` is *not* treated as a separator and essentially no normalization is
-/// performed.
+/// # if cfg!(windows) {
+/// assert_eq!(Verbatim(OsStr::new("pictures")),
+/// get_path_prefix(r"\\?\pictures\kittens"));
+/// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
+/// get_path_prefix(r"\\?\UNC\server\share"));
+/// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
+/// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
+/// get_path_prefix(r"\\.\BrainInterface"));
+/// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
+/// get_path_prefix(r"\\server\share"));
+/// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
+/// # }
+/// ```
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Prefix<'a> {
- /// Prefix `\\?\`, together with the given component immediately following it.
+ /// Verbatim prefix, e.g. `\\?\cat_pics`.
+ ///
+ /// Verbatim prefixes consist of `\\?\` immediately followed by the given
+ /// component.
#[stable(feature = "rust1", since = "1.0.0")]
- Verbatim(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
+ Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
- /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
+ /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
+ /// e.g. `\\?\UNC\server\share`.
+ ///
+ /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
+ /// server's hostname and a share name.
#[stable(feature = "rust1", since = "1.0.0")]
VerbatimUNC(
- #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
- #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
+ #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
+ #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
),
- /// Prefix like `\\?\C:\`, for the given drive letter
+ /// Verbatim disk prefix, e.g. `\\?\C:\`.
+ ///
+ /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
+ /// drive letter and `:\`.
#[stable(feature = "rust1", since = "1.0.0")]
- VerbatimDisk(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] u8),
+ VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
- /// Prefix `\\.\`, together with the given component immediately following it.
+ /// Device namespace prefix, e.g. `\\.\COM42`.
+ ///
+ /// Device namespace prefixes consist of `\\.\` immediately followed by the
+ /// device name.
#[stable(feature = "rust1", since = "1.0.0")]
- DeviceNS(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
+ DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
- /// Prefix `\\server\share`, with the given "server" and "share" components.
+ /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
+ /// `\\server\share`.
+ ///
+ /// UNC prefixes consist of the server's hostname and a share name.
#[stable(feature = "rust1", since = "1.0.0")]
UNC(
- #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
- #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
+ #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
+ #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
),
/// Prefix `C:` for the given disk drive.
#[stable(feature = "rust1", since = "1.0.0")]
- Disk(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] u8),
+ Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
}
impl<'a> Prefix<'a> {
}
/// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::Prefix::*;
+ /// use std::ffi::OsStr;
+ ///
+ /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
+ /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
+ /// assert!(VerbatimDisk(b'C').is_verbatim());
+ /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
+ /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
+ /// assert!(!Disk(b'C').is_verbatim());
+ /// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_verbatim(&self) -> bool {
use self::Prefix::*;
match *self {
- Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
+ Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
_ => false,
}
}
/// ```
/// use std::path;
///
-/// assert!(path::is_separator('/'));
+/// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
/// assert!(!path::is_separator('❤'));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
c.is_ascii() && is_sep_byte(c as u8)
}
-/// The primary separator for the current platform
+/// The primary separator of path components for the current platform.
+///
+/// For example, `/` on Unix and `\` on Windows.
#[stable(feature = "rust1", since = "1.0.0")]
-pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
+pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
////////////////////////////////////////////////////////////////////////////////
// Misc helpers
loop {
let mut iter_next = iter.clone();
match (iter_next.next(), prefix.next()) {
- (Some(x), Some(y)) => {
- if x != y {
- return None;
- }
- }
+ (Some(ref x), Some(ref y)) if x == y => (),
+ (Some(_), Some(_)) => return None,
(Some(_), None) => return Some(iter),
(None, None) => return Some(iter),
(None, Some(_)) => return None,
// See note at the top of this module to understand why these are used:
fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
- unsafe { mem::transmute(s) }
+ unsafe { &*(s as *const OsStr as *const [u8]) }
}
unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
- mem::transmute(s)
+ &*(s as *const [u8] as *const OsStr)
+}
+
+// Detect scheme on Redox
+fn has_redox_scheme(s: &[u8]) -> bool {
+ cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
}
////////////////////////////////////////////////////////////////////////////////
Done = 3,
}
-/// A Windows path prefix, e.g. `C:` or `\server\share`.
+/// A structure wrapping a Windows path prefix as well as its unparsed string
+/// representation.
+///
+/// In addition to the parsed [`Prefix`] information returned by [`kind`],
+/// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
+/// returned by [`as_os_str`].
+///
+/// Instances of this `struct` can be obtained by matching against the
+/// [`Prefix` variant] on [`Component`].
///
/// Does not occur on Unix.
+///
+/// # Examples
+///
+/// ```
+/// # if cfg!(windows) {
+/// use std::path::{Component, Path, Prefix};
+/// use std::ffi::OsStr;
+///
+/// let path = Path::new(r"c:\you\later\");
+/// match path.components().next().unwrap() {
+/// Component::Prefix(prefix_component) => {
+/// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
+/// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
+/// }
+/// _ => unreachable!(),
+/// }
+/// # }
+/// ```
+///
+/// [`as_os_str`]: #method.as_os_str
+/// [`Component`]: enum.Component.html
+/// [`kind`]: #method.kind
+/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
+/// [`Prefix` variant]: enum.Component.html#variant.Prefix
+/// [`Prefix`]: enum.Prefix.html
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy, Clone, Eq, Debug)]
pub struct PrefixComponent<'a> {
}
impl<'a> PrefixComponent<'a> {
- /// The parsed prefix data.
+ /// Returns the parsed prefix data.
+ ///
+ /// See [`Prefix`]'s documentation for more information on the different
+ /// kinds of prefixes.
+ ///
+ /// [`Prefix`]: enum.Prefix.html
#[stable(feature = "rust1", since = "1.0.0")]
pub fn kind(&self) -> Prefix<'a> {
self.parsed
}
- /// The raw `OsStr` slice for this prefix.
+ /// Returns the raw [`OsStr`] slice for this prefix.
+ ///
+ /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_os_str(&self) -> &'a OsStr {
self.raw
/// A single component of a path.
///
-/// See the module documentation for an in-depth explanation of components and
-/// their role in the API.
+/// A `Component` roughly corresponds to a substring between path separators
+/// (`/` or `\`).
+///
+/// This `enum` is created by iterating over [`Components`], which in turn is
+/// created by the [`components`][`Path::components`] method on [`Path`].
+///
+/// # Examples
+///
+/// ```rust
+/// use std::path::{Component, Path};
+///
+/// let path = Path::new("/tmp/foo/bar.txt");
+/// let components = path.components().collect::<Vec<_>>();
+/// assert_eq!(&components, &[
+/// Component::RootDir,
+/// Component::Normal("tmp".as_ref()),
+/// Component::Normal("foo".as_ref()),
+/// Component::Normal("bar.txt".as_ref()),
+/// ]);
+/// ```
+///
+/// [`Components`]: struct.Components.html
+/// [`Path`]: struct.Path.html
+/// [`Path::components`]: struct.Path.html#method.components
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Component<'a> {
- /// A Windows path prefix, e.g. `C:` or `\server\share`.
+ /// A Windows path prefix, e.g. `C:` or `\\server\share`.
+ ///
+ /// There is a large variety of prefix types, see [`Prefix`]'s documentation
+ /// for more.
///
/// Does not occur on Unix.
+ ///
+ /// [`Prefix`]: enum.Prefix.html
#[stable(feature = "rust1", since = "1.0.0")]
Prefix(
- #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] PrefixComponent<'a>
+ #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
),
- /// The root directory component, appears after any prefix and before anything else
+ /// The root directory component, appears after any prefix and before anything else.
+ ///
+ /// It represents a separator that designates that a path starts from root.
#[stable(feature = "rust1", since = "1.0.0")]
RootDir,
- /// A reference to the current directory, i.e. `.`
+ /// A reference to the current directory, i.e. `.`.
#[stable(feature = "rust1", since = "1.0.0")]
CurDir,
- /// A reference to the parent directory, i.e. `..`
+ /// A reference to the parent directory, i.e. `..`.
#[stable(feature = "rust1", since = "1.0.0")]
ParentDir,
- /// A normal component, i.e. `a` and `b` in `a/b`
+ /// A normal component, e.g. `a` and `b` in `a/b`.
+ ///
+ /// This variant is the most common one, it represents references to files
+ /// or directories.
#[stable(feature = "rust1", since = "1.0.0")]
- Normal(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
+ Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
}
impl<'a> Component<'a> {
- /// Extracts the underlying `OsStr` slice
+ /// Extracts the underlying [`OsStr`] slice.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::Path;
+ ///
+ /// let path = Path::new("./tmp/foo/bar.txt");
+ /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
+ /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
+ /// ```
+ ///
+ /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_os_str(self) -> &'a OsStr {
match self {
}
}
-/// The core iterator giving the components of a path.
+/// An iterator over the [`Component`]s of a [`Path`].
///
-/// See the module documentation for an in-depth explanation of components and
-/// their role in the API.
+/// This `struct` is created by the [`components`] method on [`Path`].
+/// See its documentation for more.
///
/// # Examples
///
/// println!("{:?}", component);
/// }
/// ```
+///
+/// [`Component`]: enum.Component.html
+/// [`components`]: struct.Path.html#method.components
+/// [`Path`]: struct.Path.html
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Components<'a> {
back: State,
}
-/// An iterator over the components of a path, as `OsStr` slices.
+/// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
+///
+/// This `struct` is created by the [`iter`] method on [`Path`].
+/// See its documentation for more.
+///
+/// [`Component`]: enum.Component.html
+/// [`iter`]: struct.Path.html#method.iter
+/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
+/// [`Path`]: struct.Path.html
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a> {
inner: Components<'a>,
}
+#[stable(feature = "path_components_debug", since = "1.13.0")]
+impl<'a> fmt::Debug for Components<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ struct DebugHelper<'a>(&'a Path);
+
+ impl<'a> fmt::Debug for DebugHelper<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_list()
+ .entries(self.0.components())
+ .finish()
+ }
+ }
+
+ f.debug_tuple("Components")
+ .field(&DebugHelper(self.as_path()))
+ .finish()
+ }
+}
+
impl<'a> Components<'a> {
// how long is the prefix, if any?
#[inline]
}
}
}
-
- /// Examine the next component without consuming it.
- #[unstable(feature = "path_components_peek", issue = "27727")]
- #[rustc_deprecated(reason = "use peekable() instead",
- since = "1.6.0")]
- pub fn peek(&self) -> Option<Component<'a>> {
- self.clone().next()
- }
}
#[stable(feature = "rust1", since = "1.0.0")]
}
}
+#[stable(feature = "path_iter_debug", since = "1.13.0")]
+impl<'a> fmt::Debug for Iter<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ struct DebugHelper<'a>(&'a Path);
+
+ impl<'a> fmt::Debug for DebugHelper<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_list()
+ .entries(self.0.iter())
+ .finish()
+ }
+ }
+
+ f.debug_tuple("Iter")
+ .field(&DebugHelper(self.as_path()))
+ .finish()
+ }
+}
+
impl<'a> Iter<'a> {
/// Extracts a slice corresponding to the portion of the path remaining for iteration.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::Path;
+ ///
+ /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
+ /// iter.next();
+ /// iter.next();
+ ///
+ /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_path(&self) -> &'a Path {
self.inner.as_path()
}
}
+#[unstable(feature = "fused", issue = "35602")]
+impl<'a> FusedIterator for Iter<'a> {}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Iterator for Components<'a> {
type Item = Component<'a>;
}
}
+#[unstable(feature = "fused", issue = "35602")]
+impl<'a> FusedIterator for Components<'a> {}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> cmp::PartialEq for Components<'a> {
fn eq(&self, other: &Components<'a>) -> bool {
// Basic types and traits
////////////////////////////////////////////////////////////////////////////////
-/// An owned, mutable path (akin to `String`).
+/// An owned, mutable path (akin to [`String`]).
///
-/// This type provides methods like `push` and `set_extension` that mutate the
-/// path in place. It also implements `Deref` to `Path`, meaning that all
-/// methods on `Path` slices are available on `PathBuf` values as well.
+/// This type provides methods like [`push`] and [`set_extension`] that mutate
+/// the path in place. It also implements [`Deref`] to [`Path`], meaning that
+/// all methods on [`Path`] slices are available on `PathBuf` values as well.
+///
+/// [`String`]: ../string/struct.String.html
+/// [`Path`]: struct.Path.html
+/// [`push`]: struct.PathBuf.html#method.push
+/// [`set_extension`]: struct.PathBuf.html#method.set_extension
+/// [`Deref`]: ../ops/trait.Deref.html
///
/// More details about the overall approach can be found in
-/// the module documentation.
+/// the [module documentation](index.html).
///
/// # Examples
///
+/// You can use [`push`] to build up a `PathBuf` from
+/// components:
+///
/// ```
/// use std::path::PathBuf;
///
-/// let mut path = PathBuf::from("c:\\");
+/// let mut path = PathBuf::new();
+///
+/// path.push(r"C:\");
/// path.push("windows");
/// path.push("system32");
+///
/// path.set_extension("dll");
/// ```
+///
+/// However, [`push`] is best used for dynamic situations. This is a better way
+/// to do this when you know all of the components ahead of time:
+///
+/// ```
+/// use std::path::PathBuf;
+///
+/// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
+/// ```
+///
+/// We can still do better than this! Since these are all strings, we can use
+/// `From::from`:
+///
+/// ```
+/// use std::path::PathBuf;
+///
+/// let path = PathBuf::from(r"C:\windows\system32.dll");
+/// ```
+///
+/// Which method works best depends on what kind of situation you're in.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PathBuf {
}
/// Allocates an empty `PathBuf`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::PathBuf;
+ ///
+ /// let path = PathBuf::new();
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> PathBuf {
PathBuf { inner: OsString::new() }
}
- /// Coerces to a `Path` slice.
+ /// Coerces to a [`Path`] slice.
+ ///
+ /// [`Path`]: struct.Path.html
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::{Path, PathBuf};
+ ///
+ /// let p = PathBuf::from("/test");
+ /// assert_eq!(Path::new("/test"), p.as_path());
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_path(&self) -> &Path {
self
///
/// # Examples
///
+ /// Pushing a relative path extends the existing path:
+ ///
/// ```
/// use std::path::PathBuf;
///
- /// let mut path = PathBuf::new();
- /// path.push("/tmp");
+ /// let mut path = PathBuf::from("/tmp");
/// path.push("file.bk");
/// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
+ /// ```
+ ///
+ /// Pushing an absolute path replaces the existing path:
///
- /// // Pushing an absolute path replaces the current path
- /// path.push("/etc/passwd");
- /// assert_eq!(path, PathBuf::from("/etc/passwd"));
+ /// ```
+ /// use std::path::PathBuf;
+ ///
+ /// let mut path = PathBuf::from("/tmp");
+ /// path.push("/etc");
+ /// assert_eq!(path, PathBuf::from("/etc"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push<P: AsRef<Path>>(&mut self, path: P) {
self._push(path.as_ref())
}
- #[allow(deprecated)]
fn _push(&mut self, path: &Path) {
// in general, a separator is needed if the rightmost byte is not a separator
let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
self.inner.push(path);
}
- /// Truncate `self` to `self.parent()`.
+ /// Truncates `self` to [`self.parent`].
///
- /// Returns false and does nothing if `self.file_name()` is `None`.
+ /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
/// Otherwise, returns `true`.
+ ///
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
+ /// [`self.parent`]: struct.PathBuf.html#method.parent
+ /// [`self.file_name`]: struct.PathBuf.html#method.file_name
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::{Path, PathBuf};
+ ///
+ /// let mut p = PathBuf::from("/test/test.rs");
+ ///
+ /// p.pop();
+ /// assert_eq!(Path::new("/test"), p);
+ /// p.pop();
+ /// assert_eq!(Path::new("/"), p);
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> bool {
match self.parent().map(|p| p.as_u8_slice().len()) {
}
}
- /// Updates `self.file_name()` to `file_name`.
+ /// Updates [`self.file_name`] to `file_name`.
///
- /// If `self.file_name()` was `None`, this is equivalent to pushing
+ /// If [`self.file_name`] was [`None`], this is equivalent to pushing
/// `file_name`.
///
+ /// Otherwise it is equivalent to calling [`pop`] and then pushing
+ /// `file_name`. The new path will be a sibling of the original path.
+ /// (That is, it will have the same parent.)
+ ///
+ /// [`self.file_name`]: struct.PathBuf.html#method.file_name
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
+ /// [`pop`]: struct.PathBuf.html#method.pop
+ ///
/// # Examples
///
/// ```
self.push(file_name);
}
- /// Updates `self.extension()` to `extension`.
+ /// Updates [`self.extension`] to `extension`.
+ ///
+ /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
+ /// returns `true` and updates the extension otherwise.
+ ///
+ /// If [`self.extension`] is [`None`], the extension is added; otherwise
+ /// it is replaced.
+ ///
+ /// [`self.file_name`]: struct.PathBuf.html#method.file_name
+ /// [`self.extension`]: struct.PathBuf.html#method.extension
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::{Path, PathBuf};
///
- /// If `self.file_name()` is `None`, does nothing and returns `false`.
+ /// let mut p = PathBuf::from("/feel/the");
///
- /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
- /// is added; otherwise it is replaced.
+ /// p.set_extension("force");
+ /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
+ ///
+ /// p.set_extension("dark_side");
+ /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
self._set_extension(extension.as_ref())
true
}
- /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
+ /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
+ ///
+ /// [`OsString`]: ../ffi/struct.OsString.html
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::PathBuf;
+ ///
+ /// let p = PathBuf::from("/the/head");
+ /// let os_str = p.into_os_string();
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_os_string(self) -> OsString {
self.inner
}
+
+ /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
+ ///
+ /// [`Box`]: ../../std/boxed/struct.Box.html
+ /// [`Path`]: struct.Path.html
+ #[stable(feature = "into_boxed_path", since = "1.20.0")]
+ pub fn into_boxed_path(self) -> Box<Path> {
+ let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
+ unsafe { Box::from_raw(rw) }
+ }
+}
+
+#[stable(feature = "box_from_path", since = "1.17.0")]
+impl<'a> From<&'a Path> for Box<Path> {
+ fn from(path: &'a Path) -> Box<Path> {
+ let boxed: Box<OsStr> = path.inner.into();
+ let rw = Box::into_raw(boxed) as *mut Path;
+ unsafe { Box::from_raw(rw) }
+ }
+}
+
+#[stable(feature = "path_buf_from_box", since = "1.18.0")]
+impl From<Box<Path>> for PathBuf {
+ fn from(boxed: Box<Path>) -> PathBuf {
+ boxed.into_path_buf()
+ }
+}
+
+#[stable(feature = "box_from_path_buf", since = "1.20.0")]
+impl From<PathBuf> for Box<Path> {
+ fn from(p: PathBuf) -> Box<Path> {
+ p.into_boxed_path()
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
}
}
+#[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
+impl From<PathBuf> for OsString {
+ fn from(path_buf : PathBuf) -> OsString {
+ path_buf.inner
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for PathBuf {
fn from(s: String) -> PathBuf {
}
}
-#[stable(feature = "rust1", since = "1.0.0")]
-#[allow(deprecated)]
-impl IntoCow<'static, Path> for PathBuf {
- fn into_cow(self) -> Cow<'static, Path> {
- Cow::Owned(self)
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-#[allow(deprecated)]
-impl<'a> IntoCow<'a, Path> for &'a Path {
- fn into_cow(self) -> Cow<'a, Path> {
- Cow::Borrowed(self)
+#[stable(feature = "default_for_pathbuf", since = "1.17.0")]
+impl Default for PathBuf {
+ fn default() -> Self {
+ PathBuf::new()
}
}
fn to_owned(&self) -> PathBuf {
self.to_path_buf()
}
+ fn clone_into(&self, target: &mut PathBuf) {
+ self.inner.clone_into(&mut target.inner);
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
}
}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl Into<OsString> for PathBuf {
- fn into(self) -> OsString {
- self.inner
- }
-}
-
-/// A slice of a path (akin to `str`).
+/// A slice of a path (akin to [`str`]).
///
/// This type supports a number of operations for inspecting a path, including
-/// breaking the path into its components (separated by `/` or `\`, depending on
-/// the platform), extracting the file name, determining whether the path is
-/// absolute, and so on. More details about the overall approach can be found in
-/// the module documentation.
+/// breaking the path into its components (separated by `/` on Unix and by either
+/// `/` or `\` on Windows), extracting the file name, determining whether the path
+/// is absolute, and so on.
///
/// This is an *unsized* type, meaning that it must always be used behind a
-/// pointer like `&` or `Box`.
+/// pointer like `&` or [`Box`]. For an owned version of this type,
+/// see [`PathBuf`].
+///
+/// [`str`]: ../primitive.str.html
+/// [`Box`]: ../boxed/struct.Box.html
+/// [`PathBuf`]: struct.PathBuf.html
+///
+/// More details about the overall approach can be found in
+/// the [module documentation](index.html).
///
/// # Examples
///
/// ```
/// use std::path::Path;
+/// use std::ffi::OsStr;
+///
+/// // Note: this example does work on Windows
+/// let path = Path::new("./foo/bar.txt");
+///
+/// let parent = path.parent();
+/// assert_eq!(parent, Some(Path::new("./foo")));
+///
+/// let file_stem = path.file_stem();
+/// assert_eq!(file_stem, Some(OsStr::new("bar")));
///
-/// let path = Path::new("/tmp/foo/bar.txt");
-/// let file = path.file_name();
/// let extension = path.extension();
-/// let parent_dir = path.parent();
+/// assert_eq!(extension, Some(OsStr::new("txt")));
/// ```
-///
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Path {
inner: OsStr,
}
-/// An error returned from the `Path::strip_prefix` method indicating that the
-/// prefix was not found in `self`.
+/// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
+/// was not found.
+///
+/// This `struct` is created by the [`strip_prefix`] method on [`Path`].
+/// See its documentation for more.
+///
+/// [`strip_prefix`]: struct.Path.html#method.strip_prefix
+/// [`Path`]: struct.Path.html
#[derive(Debug, Clone, PartialEq, Eq)]
#[stable(since = "1.7.0", feature = "strip_prefix")]
pub struct StripPrefixError(());
os_str_as_u8_slice(&self.inner)
}
- /// Directly wrap a string slice as a `Path` slice.
+ /// Directly wraps a string slice as a `Path` slice.
///
/// This is a cost-free conversion.
///
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
- unsafe { mem::transmute(s.as_ref()) }
+ unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
}
- /// Yields the underlying `OsStr` slice.
+ /// Yields the underlying [`OsStr`] slice.
+ ///
+ /// [`OsStr`]: ../ffi/struct.OsStr.html
///
/// # Examples
///
&self.inner
}
- /// Yields a `&str` slice if the `Path` is valid unicode.
+ /// Yields a [`&str`] slice if the `Path` is valid unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
///
+ /// [`&str`]: ../primitive.str.html
+ ///
/// # Examples
///
/// ```
/// use std::path::Path;
///
- /// let path_str = Path::new("foo.txt").to_str();
- /// assert_eq!(path_str, Some("foo.txt"));
+ /// let path = Path::new("foo.txt");
+ /// assert_eq!(path.to_str(), Some("foo.txt"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_str(&self) -> Option<&str> {
self.inner.to_str()
}
- /// Converts a `Path` to a `Cow<str>`.
+ /// Converts a `Path` to a [`Cow<str>`].
///
/// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
///
+ /// [`Cow<str>`]: ../borrow/enum.Cow.html
+ ///
/// # Examples
///
+ /// Calling `to_string_lossy` on a `Path` with valid unicode:
+ ///
/// ```
/// use std::path::Path;
///
- /// let path_str = Path::new("foo.txt").to_string_lossy();
- /// assert_eq!(path_str, "foo.txt");
+ /// let path = Path::new("foo.txt");
+ /// assert_eq!(path.to_string_lossy(), "foo.txt");
/// ```
+ ///
+ /// Had `path` contained invalid unicode, the `to_string_lossy` call might
+ /// have returned `"fo�.txt"`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_string_lossy(&self) -> Cow<str> {
self.inner.to_string_lossy()
}
- /// Converts a `Path` to an owned `PathBuf`.
+ /// Converts a `Path` to an owned [`PathBuf`].
+ ///
+ /// [`PathBuf`]: struct.PathBuf.html
///
/// # Examples
///
PathBuf::from(self.inner.to_os_string())
}
- /// A path is *absolute* if it is independent of the current directory.
+ /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
+ /// the current directory.
///
/// * On Unix, a path is absolute if it starts with the root, so
- /// `is_absolute` and `has_root` are equivalent.
+ /// `is_absolute` and [`has_root`] are equivalent.
///
/// * On Windows, a path is absolute if it has a prefix and starts with the
- /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
- /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
+ /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
///
/// # Examples
///
///
/// assert!(!Path::new("foo.txt").is_absolute());
/// ```
+ ///
+ /// [`has_root`]: #method.has_root
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
pub fn is_absolute(&self) -> bool {
- self.has_root() && (cfg!(unix) || self.prefix().is_some())
+ if cfg!(target_os = "redox") {
+ // FIXME: Allow Redox prefixes
+ self.has_root() || has_redox_scheme(self.as_u8_slice())
+ } else {
+ self.has_root() && (cfg!(unix) || self.prefix().is_some())
+ }
}
- /// A path is *relative* if it is not absolute.
+ /// Returns `true` if the `Path` is relative, i.e. not absolute.
+ ///
+ /// See [`is_absolute`]'s documentation for more details.
///
/// # Examples
///
///
/// assert!(Path::new("foo.txt").is_relative());
/// ```
+ ///
+ /// [`is_absolute`]: #method.is_absolute
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_relative(&self) -> bool {
!self.is_absolute()
}
- /// Returns the *prefix* of a path, if any.
- ///
- /// Prefixes are relevant only for Windows paths, and consist of volumes
- /// like `C:`, UNC prefixes like `\\server`, and others described in more
- /// detail in `std::os::windows::PathExt`.
- #[unstable(feature = "path_prefix",
- reason = "uncertain whether to expose this convenience",
- issue = "27722")]
- #[rustc_deprecated(since = "1.7.0",
- reason = "inspect components().next() instead")]
- pub fn prefix(&self) -> Option<Prefix> {
+ fn prefix(&self) -> Option<Prefix> {
self.components().prefix
}
- /// A path has a root if the body of the path begins with the directory separator.
+ /// Returns `true` if the `Path` has a root.
///
/// * On Unix, a path has a root if it begins with `/`.
///
self.components().has_root()
}
- /// The path without its final component, if any.
+ /// Returns the `Path` without its final component, if there is one.
+ ///
+ /// Returns [`None`] if the path terminates in a root or prefix.
///
- /// Returns `None` if the path terminates in a root or prefix.
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
})
}
- /// The final component of the path, if it is a normal file.
+ /// Returns the final component of the `Path`, if there is one.
+ ///
+ /// If the path is a normal file, this is the file name. If it's the path of a directory, this
+ /// is the directory name.
///
- /// If the path terminates in `.`, `..`, or consists solely of a root of
- /// prefix, `file_name` will return `None`.
+ /// Returns [`None`] If the path terminates in `..`.
+ ///
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// use std::path::Path;
/// use std::ffi::OsStr;
///
- /// let path = Path::new("foo.txt");
- /// let os_str = OsStr::new("foo.txt");
- ///
- /// assert_eq!(Some(os_str), path.file_name());
+ /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
+ /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
+ /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
+ /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
+ /// assert_eq!(None, Path::new("foo.txt/..").file_name());
+ /// assert_eq!(None, Path::new("/").file_name());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn file_name(&self) -> Option<&OsStr> {
/// Returns a path that, when joined onto `base`, yields `self`.
///
- /// If `base` is not a prefix of `self` (i.e. `starts_with`
- /// returns false), then `relative_from` returns `None`.
- #[unstable(feature = "path_relative_from", reason = "see #23284",
- issue = "23284")]
- #[rustc_deprecated(since = "1.7.0", reason = "renamed to strip_prefix")]
- pub fn relative_from<'a, P: ?Sized + AsRef<Path>>(&'a self, base: &'a P) -> Option<&Path> {
- self._strip_prefix(base.as_ref()).ok()
- }
-
- /// Returns a path that, when joined onto `base`, yields `self`.
+ /// # Errors
+ ///
+ /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
+ /// returns `false`), returns [`Err`].
+ ///
+ /// [`starts_with`]: #method.starts_with
+ /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::path::Path;
+ ///
+ /// let path = Path::new("/test/haha/foo.txt");
///
- /// If `base` is not a prefix of `self` (i.e. `starts_with`
- /// returns false), then `relative_from` returns `None`.
+ /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
+ /// assert_eq!(path.strip_prefix("test").is_ok(), false);
+ /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
+ /// ```
#[stable(since = "1.7.0", feature = "path_strip_prefix")]
pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
-> Result<&'a Path, StripPrefixError>
iter_after(self.components().rev(), child.components().rev()).is_some()
}
- /// Extracts the stem (non-extension) portion of `self.file_name()`.
+ /// Extracts the stem (non-extension) portion of [`self.file_name`].
+ ///
+ /// [`self.file_name`]: struct.Path.html#method.file_name
///
/// The stem is:
///
- /// * None, if there is no file name;
+ /// * [`None`], if there is no file name;
/// * The entire file name if there is no embedded `.`;
/// * The entire file name if the file name begins with `.` and has no other `.`s within;
/// * Otherwise, the portion of the file name before the final `.`
///
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
+ ///
/// # Examples
///
/// ```
self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
}
- /// Extracts the extension of `self.file_name()`, if possible.
+ /// Extracts the extension of [`self.file_name`], if possible.
///
/// The extension is:
///
- /// * None, if there is no file name;
- /// * None, if there is no embedded `.`;
- /// * None, if the file name begins with `.` and has no other `.`s within;
+ /// * [`None`], if there is no file name;
+ /// * [`None`], if there is no embedded `.`;
+ /// * [`None`], if the file name begins with `.` and has no other `.`s within;
/// * Otherwise, the portion of the file name after the final `.`
///
+ /// [`self.file_name`]: struct.Path.html#method.file_name
+ /// [`None`]: ../../std/option/enum.Option.html#variant.None
+ ///
/// # Examples
///
/// ```
self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
}
- /// Creates an owned `PathBuf` with `path` adjoined to `self`.
+ /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
///
- /// See `PathBuf::push` for more details on what it means to adjoin a path.
+ /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
+ ///
+ /// [`PathBuf`]: struct.PathBuf.html
+ /// [`PathBuf::push`]: struct.PathBuf.html#method.push
///
/// # Examples
///
buf
}
- /// Creates an owned `PathBuf` like `self` but with the given file name.
+ /// Creates an owned [`PathBuf`] like `self` but with the given file name.
+ ///
+ /// See [`PathBuf::set_file_name`] for more details.
///
- /// See `PathBuf::set_file_name` for more details.
+ /// [`PathBuf`]: struct.PathBuf.html
+ /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
///
/// # Examples
///
///
/// let path = Path::new("/tmp/foo.txt");
/// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
+ ///
+ /// let path = Path::new("/tmp");
+ /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
buf
}
- /// Creates an owned `PathBuf` like `self` but with the given extension.
+ /// Creates an owned [`PathBuf`] like `self` but with the given extension.
///
- /// See `PathBuf::set_extension` for more details.
+ /// See [`PathBuf::set_extension`] for more details.
+ ///
+ /// [`PathBuf`]: struct.PathBuf.html
+ /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
///
/// # Examples
///
buf
}
- /// Produce an iterator over the components of the path.
+ /// Produces an iterator over the [`Component`]s of the path.
+ ///
+ /// When parsing the path, there is a small amount of normalization:
+ ///
+ /// * Repeated separators are ignored, so `a/b` and `a//b` both have
+ /// `a` and `b` as components.
+ ///
+ /// * Occurrences of `.` are normalized away, except if they are at the
+ /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
+ /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
+ /// an additional [`CurDir`] component.
+ ///
+ /// Note that no other normalization takes place; in particular, `a/c`
+ /// and `a/b/../c` are distinct, to account for the possibility that `b`
+ /// is a symbolic link (so its parent isn't `a`).
///
/// # Examples
///
/// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
/// assert_eq!(components.next(), None)
/// ```
+ ///
+ /// [`Component`]: enum.Component.html
+ /// [`CurDir`]: enum.Component.html#variant.CurDir
#[stable(feature = "rust1", since = "1.0.0")]
pub fn components(&self) -> Components {
let prefix = parse_prefix(self.as_os_str());
Components {
path: self.as_u8_slice(),
- prefix: prefix,
- has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
+ prefix,
+ has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
+ has_redox_scheme(self.as_u8_slice()),
front: State::Prefix,
back: State::Body,
}
}
- /// Produce an iterator over the path's components viewed as `OsStr` slices.
+ /// Produces an iterator over the path's components viewed as [`OsStr`]
+ /// slices.
+ ///
+ /// For more information about the particulars of how the path is separated
+ /// into components, see [`components`].
+ ///
+ /// [`components`]: #method.components
+ /// [`OsStr`]: ../ffi/struct.OsStr.html
///
/// # Examples
///
Iter { inner: self.components() }
}
- /// Returns an object that implements `Display` for safely printing paths
+ /// Returns an object that implements [`Display`] for safely printing paths
/// that may contain non-Unicode data.
///
+ /// [`Display`]: ../fmt/trait.Display.html
+ ///
/// # Examples
///
/// ```
Display { path: self }
}
-
- /// Gets information on the file, directory, etc at this path.
+ /// Queries the file system to get information about a file, directory, etc.
+ ///
+ /// This function will traverse symbolic links to query information about the
+ /// destination file.
+ ///
+ /// This is an alias to [`fs::metadata`].
+ ///
+ /// [`fs::metadata`]: ../fs/fn.metadata.html
+ ///
+ /// # Examples
///
- /// Consult the `fs::metadata` documentation for more info.
+ /// ```no_run
+ /// use std::path::Path;
///
- /// This call preserves identical runtime/error semantics with
- /// `fs::metadata`.
+ /// let path = Path::new("/Minas/tirith");
+ /// let metadata = path.metadata().expect("metadata call failed");
+ /// println!("{:?}", metadata.file_type());
+ /// ```
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn metadata(&self) -> io::Result<fs::Metadata> {
fs::metadata(self)
}
- /// Gets information on the file, directory, etc at this path.
+ /// Queries the metadata about a file without following symlinks.
+ ///
+ /// This is an alias to [`fs::symlink_metadata`].
+ ///
+ /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
+ ///
+ /// # Examples
///
- /// Consult the `fs::symlink_metadata` documentation for more info.
+ /// ```no_run
+ /// use std::path::Path;
///
- /// This call preserves identical runtime/error semantics with
- /// `fs::symlink_metadata`.
+ /// let path = Path::new("/Minas/tirith");
+ /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
+ /// println!("{:?}", metadata.file_type());
+ /// ```
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
fs::symlink_metadata(self)
}
- /// Returns the canonical form of a path, normalizing all components and
- /// eliminate all symlinks.
+ /// Returns the canonical form of the path with all intermediate components
+ /// normalized and symbolic links resolved.
+ ///
+ /// This is an alias to [`fs::canonicalize`].
+ ///
+ /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::path::{Path, PathBuf};
///
- /// This call preserves identical runtime/error semantics with
- /// `fs::canonicalize`.
+ /// let path = Path::new("/foo/test/../test/bar.rs");
+ /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
+ /// ```
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn canonicalize(&self) -> io::Result<PathBuf> {
fs::canonicalize(self)
}
- /// Reads the symlink at this path.
+ /// Reads a symbolic link, returning the file that the link points to.
+ ///
+ /// This is an alias to [`fs::read_link`].
+ ///
+ /// [`fs::read_link`]: ../fs/fn.read_link.html
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::path::Path;
///
- /// For more information see `fs::read_link`.
+ /// let path = Path::new("/laputa/sky_castle.rs");
+ /// let path_link = path.read_link().expect("read_link call failed");
+ /// ```
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn read_link(&self) -> io::Result<PathBuf> {
fs::read_link(self)
}
- /// Reads the directory at this path.
+ /// Returns an iterator over the entries within a directory.
+ ///
+ /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
+ /// errors may be encountered after an iterator is initially constructed.
+ ///
+ /// This is an alias to [`fs::read_dir`].
+ ///
+ /// [`io::Result`]: ../io/type.Result.html
+ /// [`DirEntry`]: ../fs/struct.DirEntry.html
+ /// [`fs::read_dir`]: ../fs/fn.read_dir.html
+ ///
+ /// # Examples
///
- /// For more information see `fs::read_dir`.
+ /// ```no_run
+ /// use std::path::Path;
+ ///
+ /// let path = Path::new("/laputa");
+ /// for entry in path.read_dir().expect("read_dir call failed") {
+ /// if let Ok(entry) = entry {
+ /// println!("{:?}", entry.path());
+ /// }
+ /// }
+ /// ```
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
fs::read_dir(self)
}
- /// Boolean value indicator whether the underlying file exists on the local
- /// filesystem. Returns false in exactly the cases where `fs::metadata`
- /// fails.
+ /// Returns whether the path points at an existing entity.
+ ///
+ /// This function will traverse symbolic links to query information about the
+ /// destination file. In case of broken symbolic links this will return `false`.
+ ///
+ /// If you cannot access the directory containing the file, e.g. because of a
+ /// permission error, this will return `false`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::path::Path;
+ /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
+ /// ```
+ ///
+ /// # See Also
+ ///
+ /// This is a convenience function that coerces errors to false. If you want to
+ /// check errors, call [fs::metadata].
+ ///
+ /// [fs::metadata]: ../../std/fs/fn.metadata.html
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn exists(&self) -> bool {
fs::metadata(self).is_ok()
}
- /// Whether the underlying implementation (be it a file path, or something
- /// else) points at a "regular file" on the FS. Will return false for paths
- /// to non-existent locations or directories or other non-regular files
- /// (named pipes, etc). Follows links when making this determination.
+ /// Returns whether the path exists on disk and is pointing at a regular file.
+ ///
+ /// This function will traverse symbolic links to query information about the
+ /// destination file. In case of broken symbolic links this will return `false`.
+ ///
+ /// If you cannot access the directory containing the file, e.g. because of a
+ /// permission error, this will return `false`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::path::Path;
+ /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
+ /// assert_eq!(Path::new("a_file.txt").is_file(), true);
+ /// ```
+ ///
+ /// # See Also
+ ///
+ /// This is a convenience function that coerces errors to false. If you want to
+ /// check errors, call [fs::metadata] and handle its Result. Then call
+ /// [fs::Metadata::is_file] if it was Ok.
+ ///
+ /// [fs::metadata]: ../../std/fs/fn.metadata.html
+ /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn is_file(&self) -> bool {
fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
}
- /// Whether the underlying implementation (be it a file path, or something
- /// else) is pointing at a directory in the underlying FS. Will return
- /// false for paths to non-existent locations or if the item is not a
- /// directory (eg files, named pipes, etc). Follows links when making this
- /// determination.
+ /// Returns whether the path exists on disk and is pointing at a directory.
+ ///
+ /// This function will traverse symbolic links to query information about the
+ /// destination file. In case of broken symbolic links this will return `false`.
+ ///
+ /// If you cannot access the directory containing the file, e.g. because of a
+ /// permission error, this will return `false`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::path::Path;
+ /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
+ /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
+ /// ```
+ ///
+ /// # See Also
+ ///
+ /// This is a convenience function that coerces errors to false. If you want to
+ /// check errors, call [fs::metadata] and handle its Result. Then call
+ /// [fs::Metadata::is_dir] if it was Ok.
+ ///
+ /// [fs::metadata]: ../../std/fs/fn.metadata.html
+ /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
#[stable(feature = "path_ext", since = "1.5.0")]
pub fn is_dir(&self) -> bool {
fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
}
+
+ /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
+ /// allocating.
+ ///
+ /// [`Box`]: ../../std/boxed/struct.Box.html
+ /// [`PathBuf`]: struct.PathBuf.html
+ #[stable(feature = "into_boxed_path", since = "1.20.0")]
+ pub fn into_path_buf(self: Box<Path>) -> PathBuf {
+ let rw = Box::into_raw(self) as *mut OsStr;
+ let inner = unsafe { Box::from_raw(rw) };
+ PathBuf { inner: OsString::from(inner) }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Path {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- self.inner.fmt(formatter)
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ fmt::Debug::fmt(&self.inner, formatter)
}
}
-/// Helper struct for safely printing paths with `format!()` and `{}`
+/// Helper struct for safely printing paths with [`format!`] and `{}`.
+///
+/// A [`Path`] might contain non-Unicode data. This `struct` implements the
+/// [`Display`] trait in a way that mitigates that. It is created by the
+/// [`display`][`Path::display`] method on [`Path`].
+///
+/// # Examples
+///
+/// ```
+/// use std::path::Path;
+///
+/// let path = Path::new("/tmp/foo.rs");
+///
+/// println!("{}", path.display());
+/// ```
+///
+/// [`Display`]: ../../std/fmt/trait.Display.html
+/// [`format!`]: ../../std/macro.format.html
+/// [`Path`]: struct.Path.html
+/// [`Path::display`]: struct.Path.html#method.display
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Display<'a> {
path: &'a Path,
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> fmt::Debug for Display<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- fmt::Debug::fmt(&self.path.to_string_lossy(), f)
+ fmt::Debug::fmt(&self.path, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> fmt::Display for Display<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- fmt::Display::fmt(&self.path.to_string_lossy(), f)
+ self.path.inner.display(f)
}
}
}
}
+#[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
+impl<'a> AsRef<Path> for Cow<'a, OsStr> {
+ fn as_ref(&self) -> &Path {
+ Path::new(self)
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for OsString {
fn as_ref(&self) -> &Path {
fn into_iter(self) -> Iter<'a> { self.iter() }
}
-macro_rules! impl_eq {
+macro_rules! impl_cmp {
($lhs:ty, $rhs: ty) => {
#[stable(feature = "partialeq_path", since = "1.6.0")]
impl<'a, 'b> PartialEq<$rhs> for $lhs {
fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
}
+ #[stable(feature = "cmp_path", since = "1.8.0")]
+ impl<'a, 'b> PartialOrd<$rhs> for $lhs {
+ #[inline]
+ fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
+ <Path as PartialOrd>::partial_cmp(self, other)
+ }
+ }
+
+ #[stable(feature = "cmp_path", since = "1.8.0")]
+ impl<'a, 'b> PartialOrd<$lhs> for $rhs {
+ #[inline]
+ fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
+ <Path as PartialOrd>::partial_cmp(self, other)
+ }
+ }
+ }
+}
+
+impl_cmp!(PathBuf, Path);
+impl_cmp!(PathBuf, &'a Path);
+impl_cmp!(Cow<'a, Path>, Path);
+impl_cmp!(Cow<'a, Path>, &'b Path);
+impl_cmp!(Cow<'a, Path>, PathBuf);
+
+macro_rules! impl_cmp_os_str {
+ ($lhs:ty, $rhs: ty) => {
+ #[stable(feature = "cmp_path", since = "1.8.0")]
+ impl<'a, 'b> PartialEq<$rhs> for $lhs {
+ #[inline]
+ fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
+ }
+
+ #[stable(feature = "cmp_path", since = "1.8.0")]
+ impl<'a, 'b> PartialEq<$lhs> for $rhs {
+ #[inline]
+ fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
+ }
+
+ #[stable(feature = "cmp_path", since = "1.8.0")]
+ impl<'a, 'b> PartialOrd<$rhs> for $lhs {
+ #[inline]
+ fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
+ <Path as PartialOrd>::partial_cmp(self, other.as_ref())
+ }
+ }
+
+ #[stable(feature = "cmp_path", since = "1.8.0")]
+ impl<'a, 'b> PartialOrd<$lhs> for $rhs {
+ #[inline]
+ fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
+ <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
+ }
+ }
}
}
-impl_eq!(PathBuf, Path);
-impl_eq!(PathBuf, &'a Path);
-impl_eq!(Cow<'a, Path>, Path);
-impl_eq!(Cow<'a, Path>, &'b Path);
-impl_eq!(Cow<'a, Path>, PathBuf);
+impl_cmp_os_str!(PathBuf, OsStr);
+impl_cmp_os_str!(PathBuf, &'a OsStr);
+impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
+impl_cmp_os_str!(PathBuf, OsString);
+impl_cmp_os_str!(Path, OsStr);
+impl_cmp_os_str!(Path, &'a OsStr);
+impl_cmp_os_str!(Path, Cow<'a, OsStr>);
+impl_cmp_os_str!(Path, OsString);
+impl_cmp_os_str!(&'a Path, OsStr);
+impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
+impl_cmp_os_str!(&'a Path, OsString);
+impl_cmp_os_str!(Cow<'a, Path>, OsStr);
+impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
+impl_cmp_os_str!(Cow<'a, Path>, OsString);
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl fmt::Display for StripPrefixError {
#[cfg(test)]
mod tests {
use super::*;
- use string::{ToString, String};
- use vec::Vec;
macro_rules! t(
($path:expr, iter: $iter:expr) => (
);
);
- #[test]
- #[allow(deprecated)]
- fn into_cow() {
- use borrow::{Cow, IntoCow};
-
- let static_path = Path::new("/home/foo");
- let static_cow_path: Cow<'static, Path> = static_path.into_cow();
- let pathbuf = PathBuf::from("/home/foo");
-
- {
- let path: &Path = &pathbuf;
- let borrowed_cow_path: Cow<Path> = path.into_cow();
-
- assert_eq!(static_cow_path, borrowed_cow_path);
- }
-
- let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
-
- assert_eq!(static_cow_path, owned_cow_path);
- }
-
#[test]
fn into() {
use borrow::Cow;
#[test]
pub fn test_compare() {
- use hash::{Hash, Hasher, SipHasher};
+ use hash::{Hash, Hasher};
+ use collections::hash_map::DefaultHasher;
fn hash<T: Hash>(t: T) -> u64 {
- let mut s = SipHasher::new_with_keys(0, 0);
+ let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}
"{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
$ends_with, ends_with);
- let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
+ let relative_from = path1.strip_prefix(path2)
+ .map(|p| p.to_str().unwrap())
+ .ok();
let exp: Option<&str> = $relative_from;
assert!(relative_from == exp,
- "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
- exp, relative_from);
+ "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
+ $path1, $path2, exp, relative_from);
});
);
);
}
}
+
+ #[test]
+ fn test_components_debug() {
+ let path = Path::new("/tmp");
+
+ let mut components = path.components();
+
+ let expected = "Components([RootDir, Normal(\"tmp\")])";
+ let actual = format!("{:?}", components);
+ assert_eq!(expected, actual);
+
+ let _ = components.next().unwrap();
+ let expected = "Components([Normal(\"tmp\")])";
+ let actual = format!("{:?}", components);
+ assert_eq!(expected, actual);
+
+ let _ = components.next().unwrap();
+ let expected = "Components([])";
+ let actual = format!("{:?}", components);
+ assert_eq!(expected, actual);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_iter_debug() {
+ let path = Path::new("/tmp");
+
+ let mut iter = path.iter();
+
+ let expected = "Iter([\"/\", \"tmp\"])";
+ let actual = format!("{:?}", iter);
+ assert_eq!(expected, actual);
+
+ let _ = iter.next().unwrap();
+ let expected = "Iter([\"tmp\"])";
+ let actual = format!("{:?}", iter);
+ assert_eq!(expected, actual);
+
+ let _ = iter.next().unwrap();
+ let expected = "Iter([])";
+ let actual = format!("{:?}", iter);
+ assert_eq!(expected, actual);
+ }
+
+ #[test]
+ fn into_boxed() {
+ let orig: &str = "some/sort/of/path";
+ let path = Path::new(orig);
+ let boxed: Box<Path> = Box::from(path);
+ let path_buf = path.to_owned().into_boxed_path().into_path_buf();
+ assert_eq!(path, &*boxed);
+ assert_eq!(&*boxed, &*path_buf);
+ assert_eq!(&*path_buf, path);
+ }
+
+ #[test]
+ fn test_clone_into() {
+ let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
+ let path = Path::new("short");
+ path.clone_into(&mut path_buf);
+ assert_eq!(path, path_buf);
+ assert!(path_buf.into_os_string().capacity() >= 15);
+ }
+
+ #[test]
+ fn display_format_flags() {
+ assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
+ assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
+ }
}