Struct PathBuf

struct PathBuf { ... }

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.

More details about the overall approach can be found in the module documentation.

Examples

You can use push to build up a PathBuf from components:

use std::path::PathBuf;

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.

Note that PathBuf does not always sanitize arguments, for example push allows paths built from strings which include separators:

use std::path::PathBuf;

let mut path = PathBuf::new();

path.push(r"C:\");
path.push("windows");
path.push(r"..\otherdir");
path.push("system32");

The behavior of PathBuf may be changed to a panic on such inputs in the future. Extend::extend should be used to add multi-part paths.

Implementations

impl PathBuf

const fn new() -> PathBuf

Allocates an empty PathBuf.

Examples

use std::path::PathBuf;

let path = PathBuf::new();
fn with_capacity(capacity: usize) -> PathBuf

Creates a new PathBuf with a given capacity used to create the internal OsString. See with_capacity defined on OsString.

Examples

use std::path::PathBuf;

let mut path = PathBuf::with_capacity(10);
let capacity = path.capacity();

// This push is done without reallocating
path.push(r"C:\");

assert_eq!(capacity, path.capacity());
fn as_path(self: &Self) -> &Path

Coerces to a Path slice.

Examples

use std::path::{Path, PathBuf};

let p = PathBuf::from("/test");
assert_eq!(Path::new("/test"), p.as_path());
fn leak<'a>(self: Self) -> &'a mut Path

Consumes and leaks the PathBuf, returning a mutable reference to the contents, &'a mut Path.

The caller has free choice over the returned lifetime, including 'static. Indeed, this function is ideally used for data that lives for the remainder of the program's life, as dropping the returned reference will cause a memory leak.

It does not reallocate or shrink the PathBuf, so the leaked allocation may include unused capacity that is not part of the returned slice. If you want to discard excess capacity, call into_boxed_path, and then Box::leak instead. However, keep in mind that trimming the capacity may result in a reallocation and copy.

fn push<P: AsRef<Path>>(self: &mut Self, path: P)

Extends self with path.

If path is absolute, it replaces the current path.

On Windows:

  • if path has a root but no prefix (e.g., \windows), it replaces everything except for the prefix (if any) of self.
  • if path has a prefix but no root, it replaces self.
  • if self has a verbatim prefix (e.g. \\?\C:\windows) and path is not empty, the new path is normalized: all references to . and .. are removed.

Consider using Path::join if you need a new PathBuf instead of using this function on a cloned PathBuf.

Examples

Pushing a relative path extends the existing path:

use std::path::PathBuf;

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:

use std::path::PathBuf;

let mut path = PathBuf::from("/tmp");
path.push("/etc");
assert_eq!(path, PathBuf::from("/etc"));
fn pop(self: &mut Self) -> bool

Truncates self to self.parent.

Returns false and does nothing if self.parent is None. Otherwise, returns true.

Examples

use std::path::{Path, PathBuf};

let mut p = PathBuf::from("/spirited/away.rs");

p.pop();
assert_eq!(Path::new("/spirited"), p);
p.pop();
assert_eq!(Path::new("/"), p);
fn set_trailing_sep(self: &mut Self, trailing_sep: bool)

Sets whether the path has a trailing separator.

The value returned by has_trailing_sep will be equivalent to the provided value if possible.

Examples

#![feature(path_trailing_sep)]
use std::path::PathBuf;

let mut p = PathBuf::from("dir");

assert!(!p.has_trailing_sep());
p.set_trailing_sep(false);
assert!(!p.has_trailing_sep());
p.set_trailing_sep(true);
assert!(p.has_trailing_sep());
p.set_trailing_sep(false);
assert!(!p.has_trailing_sep());

p = PathBuf::from("/");
assert!(p.has_trailing_sep());
p.set_trailing_sep(false);
assert!(p.has_trailing_sep());
fn push_trailing_sep(self: &mut Self)

Adds a trailing separator to the path.

This acts similarly to Path::with_trailing_sep, but mutates the underlying PathBuf.

Examples

#![feature(path_trailing_sep)]
use std::ffi::OsStr;
use std::path::PathBuf;

let mut p = PathBuf::from("dir");

assert!(!p.has_trailing_sep());
p.push_trailing_sep();
assert!(p.has_trailing_sep());
p.push_trailing_sep();
assert!(p.has_trailing_sep());

p = PathBuf::from("dir/");
p.push_trailing_sep();
assert_eq!(p.as_os_str(), OsStr::new("dir/"));
fn pop_trailing_sep(self: &mut Self)

Removes a trailing separator from the path, if possible.

This acts similarly to Path::trim_trailing_sep, but mutates the underlying PathBuf.

Examples

#![feature(path_trailing_sep)]
use std::ffi::OsStr;
use std::path::PathBuf;

let mut p = PathBuf::from("dir//");

assert!(p.has_trailing_sep());
assert_eq!(p.as_os_str(), OsStr::new("dir//"));
p.pop_trailing_sep();
assert!(!p.has_trailing_sep());
assert_eq!(p.as_os_str(), OsStr::new("dir"));
p.pop_trailing_sep();
assert!(!p.has_trailing_sep());
assert_eq!(p.as_os_str(), OsStr::new("dir"));

p = PathBuf::from("/");
assert!(p.has_trailing_sep());
p.pop_trailing_sep();
assert!(p.has_trailing_sep());
fn set_file_name<S: AsRef<OsStr>>(self: &mut Self, file_name: S)

Updates self.file_name to file_name.

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.)

The argument is not sanitized, so can include separators. This behavior may be changed to a panic in the future.

Examples

use std::path::PathBuf;

let mut buf = PathBuf::from("/");
assert!(buf.file_name() == None);

buf.set_file_name("foo.txt");
assert!(buf == PathBuf::from("/foo.txt"));
assert!(buf.file_name().is_some());

buf.set_file_name("bar.txt");
assert!(buf == PathBuf::from("/bar.txt"));

buf.set_file_name("baz");
assert!(buf == PathBuf::from("/baz"));

buf.set_file_name("../b/c.txt");
assert!(buf == PathBuf::from("/../b/c.txt"));

buf.set_file_name("baz");
assert!(buf == PathBuf::from("/../b/baz"));
fn set_extension<S: AsRef<OsStr>>(self: &mut Self, extension: S) -> bool

Updates self.extension to Some(extension) or to None if extension is empty.

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.

If extension is the empty string, self.extension will be None afterwards, not Some("").

Panics

Panics if the passed extension contains a path separator (see is_separator).

Caveats

The new extension may contain dots and will be used in its entirety, but only the part after the final dot will be reflected in self.extension.

If the file stem contains internal dots and extension is empty, part of the old file stem will be considered the new self.extension.

See the examples below.

Examples

use std::path::{Path, PathBuf};

let mut p = PathBuf::from("/feel/the");

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());

p.set_extension("cookie");
assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path());

p.set_extension("");
assert_eq!(Path::new("/feel/the.dark"), p.as_path());

p.set_extension("");
assert_eq!(Path::new("/feel/the"), p.as_path());

p.set_extension("");
assert_eq!(Path::new("/feel/the"), p.as_path());
fn add_extension<S: AsRef<OsStr>>(self: &mut Self, extension: S) -> bool

Append self.extension with extension.

Returns false and does nothing if self.file_name is None, returns true and updates the extension otherwise.

Panics

Panics if the passed extension contains a path separator (see is_separator).

Caveats

The appended extension may contain dots and will be used in its entirety, but only the part after the final dot will be reflected in self.extension.

See the examples below.

Examples

use std::path::{Path, PathBuf};

let mut p = PathBuf::from("/feel/the");

p.add_extension("formatted");
assert_eq!(Path::new("/feel/the.formatted"), p.as_path());

p.add_extension("dark.side");
assert_eq!(Path::new("/feel/the.formatted.dark.side"), p.as_path());

p.set_extension("cookie");
assert_eq!(Path::new("/feel/the.formatted.dark.cookie"), p.as_path());

p.set_extension("");
assert_eq!(Path::new("/feel/the.formatted.dark"), p.as_path());

p.add_extension("");
assert_eq!(Path::new("/feel/the.formatted.dark"), p.as_path());
fn as_mut_os_string(self: &mut Self) -> &mut OsString

Yields a mutable reference to the underlying OsString instance.

Examples

use std::path::{Path, PathBuf};

let mut path = PathBuf::from("/foo");

path.push("bar");
assert_eq!(path, Path::new("/foo/bar"));

// OsString's `push` does not add a separator.
path.as_mut_os_string().push("baz");
assert_eq!(path, Path::new("/foo/barbaz"));
fn into_os_string(self: Self) -> OsString

Consumes the PathBuf, yielding its internal OsString storage.

Examples

use std::path::PathBuf;

let p = PathBuf::from("/the/head");
let os_str = p.into_os_string();
fn into_boxed_path(self: Self) -> Box<Path>

Converts this PathBuf into a boxed Path.

fn capacity(self: &Self) -> usize

Invokes capacity on the underlying instance of OsString.

fn clear(self: &mut Self)

Invokes clear on the underlying instance of OsString.

fn reserve(self: &mut Self, additional: usize)

Invokes reserve on the underlying instance of OsString.

fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>

Invokes try_reserve on the underlying instance of OsString.

fn reserve_exact(self: &mut Self, additional: usize)

Invokes reserve_exact on the underlying instance of OsString.

fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>

Invokes try_reserve_exact on the underlying instance of OsString.

fn shrink_to_fit(self: &mut Self)

Invokes shrink_to_fit on the underlying instance of OsString.

fn shrink_to(self: &mut Self, min_capacity: usize)

Invokes shrink_to on the underlying instance of OsString.

impl AsRef for PathBuf

fn as_ref(self: &Self) -> &Path

impl AsRef for PathBuf

fn as_ref(self: &Self) -> &OsStr

impl Borrow for PathBuf

fn borrow(self: &Self) -> &Path

impl Clone for PathBuf

fn clone(self: &Self) -> Self
fn clone_from(self: &mut Self, source: &Self)

Clones the contents of source into self.

This method is preferred over simply assigning source.clone() to self, as it avoids reallocation if possible.

impl Debug for PathBuf

fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result

impl Default for PathBuf

fn default() -> Self

impl Deref for PathBuf

fn deref(self: &Self) -> &Path

impl DerefMut for PathBuf

fn deref_mut(self: &mut Self) -> &mut Path

impl Eq for PathBuf

impl Freeze for PathBuf

impl From for PathBuf

fn from(boxed: Box<Path>) -> PathBuf

Converts a [Box]<[Path]> into a PathBuf.

This conversion does not allocate or copy memory.

impl From for PathBuf

fn from(s: OsString) -> PathBuf

Converts an OsString into a PathBuf.

This conversion does not allocate or copy memory.

impl From for PathBuf

fn from(s: String) -> PathBuf

Converts a String into a PathBuf

This conversion does not allocate or copy memory.

impl FromStr for PathBuf

fn from_str(s: &str) -> Result<Self, <Self as >::Err>

impl Hash for PathBuf

fn hash<H: Hasher>(self: &Self, h: &mut H)

impl Ord for PathBuf

fn cmp(self: &Self, other: &PathBuf) -> cmp::Ordering

impl PartialEq for PathBuf

fn eq(self: &Self, other: &String) -> bool

impl PartialEq for PathBuf

fn eq(self: &Self, other: &Path) -> bool

impl PartialEq for PathBuf

fn eq(self: &Self, other: &PathBuf) -> bool

impl PartialEq for PathBuf

fn eq(self: &Self, other: &OsString) -> bool

impl PartialEq for PathBuf

fn eq(self: &Self, other: &OsStr) -> bool

impl PartialEq for PathBuf

fn eq(self: &Self, other: &str) -> bool

impl PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &PathBuf) -> Option<cmp::Ordering>

impl PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &Path) -> Option<cmp::Ordering>

impl PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &OsString) -> Option<cmp::Ordering>

impl PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &OsStr) -> Option<cmp::Ordering>

impl RefUnwindSafe for PathBuf

impl Send for PathBuf

impl Sync for PathBuf

impl Unpin for PathBuf

impl UnwindSafe for PathBuf

impl<'a> From for PathBuf

fn from(p: Cow<'a, Path>) -> Self

Converts a clone-on-write pointer to an owned path.

Converting from a Cow::Owned does not clone or allocate.

impl<'a> PartialEq for PathBuf

fn eq(self: &Self, other: &&'a OsStr) -> bool

impl<'a> PartialEq for PathBuf

fn eq(self: &Self, other: &Cow<'a, OsStr>) -> bool

impl<'a> PartialEq for PathBuf

fn eq(self: &Self, other: &&'a Path) -> bool

impl<'a> PartialEq for PathBuf

fn eq(self: &Self, other: &Cow<'a, Path>) -> bool

impl<'a> PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &&'a OsStr) -> Option<cmp::Ordering>

impl<'a> PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &Cow<'a, OsStr>) -> Option<cmp::Ordering>

impl<'a> PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &&'a Path) -> Option<cmp::Ordering>

impl<'a> PartialOrd for PathBuf

fn partial_cmp(self: &Self, other: &Cow<'a, Path>) -> Option<cmp::Ordering>

impl<P, T> Receiver for PathBuf

impl<P: AsRef<Path>> Extend for PathBuf

fn extend<I: IntoIterator<Item = P>>(self: &mut Self, iter: I)

Extends self with Path elements from iter.

This uses push to add each element, so can be used to adjoin multiple path components.

Examples

# use std::path::PathBuf;
let mut path = PathBuf::from("/tmp");
path.extend(["foo", "bar", "file.txt"]);
assert_eq!(path, PathBuf::from("/tmp/foo/bar/file.txt"));

See documentation for push for more details on how the path is constructed.

fn extend_one(self: &mut Self, p: P)

impl<P: AsRef<Path>> FromIterator for PathBuf

fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf

Creates a new PathBuf from the Path elements of an iterator.

This uses push to add each element, so can be used to adjoin multiple path components.

Examples

# use std::path::PathBuf;
let path = PathBuf::from_iter(["/tmp", "foo", "bar"]);
assert_eq!(path, PathBuf::from("/tmp/foo/bar"));

See documentation for push for more details on how the path is constructed.

impl<T> Any for PathBuf

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for PathBuf

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for PathBuf

fn borrow_mut(self: &mut Self) -> &mut T

impl<T> CloneToUninit for PathBuf

unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)

impl<T> From for PathBuf

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> ToOwned for PathBuf

fn to_owned(self: &Self) -> T
fn clone_into(self: &Self, target: &mut T)

impl<T, U> Into for PathBuf

fn into(self: Self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom for PathBuf

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto for PathBuf

fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>

impl<T: ?Sized + AsRef<crate::ffi::OsStr>> From for PathBuf

fn from(s: &T) -> PathBuf

Converts a borrowed OsStr to a PathBuf.

Allocates a PathBuf and copies the data into it.