Struct path::PathBuf

source ·
pub struct PathBuf { /* private fields */ }
Expand description

An owned, mutable path.

This type is just a wrapper around a String.

Implementations§

source§

impl PathBuf

source

pub fn new() -> Self

Allocates an empty PathBuf.

source

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

Extends self with path.

If path is absolute, it replaces the current path.

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"));
source

pub fn pop(&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);

Methods from Deref<Target = Path>§

source

pub fn components(&self) -> Components<'_>

Produces an iterator over the Components 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.
  • A trailing slash is normalized away, /a/b and /a/b/ are equivalent.
Examples
let mut components = Path::new("/tmp/foo.txt").components();

assert_eq!(components.next(), Some(Component::RootDir));
assert_eq!(components.next(), Some(Component::Normal("tmp")));
assert_eq!(components.next(), Some(Component::Normal("foo.txt")));
assert_eq!(components.next(), None)
source

pub fn is_absolute(&self) -> bool

Returns true if the path starts with the root.

Examples
assert!(Path::new("/foo.txt").is_absolute());
assert!(!Path::new("foo.txt").is_absolute());
source

pub fn join<P>(&self, path: P) -> PathBufwhere P: AsRef<Self>,

Creates an owned PathBuf with path adjoined to self.

If path is absolute, it replaces the current path.

Examples
assert_eq!(
    Path::new("/etc").join("passwd"),
    PathBuf::from("/etc/passwd")
);
assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh"));
source

pub fn parent(&self) -> Option<&Self>

Returns the path without its final component, if there is one.

Examples
let path = Path::new("/foo/bar");
let parent = path.parent().unwrap();
assert_eq!(parent, Path::new("/foo"));

let grand_parent = parent.parent().unwrap();
assert_eq!(grand_parent, Path::new("/"));
assert_eq!(grand_parent.parent(), None);

let relative_path = Path::new("foo/bar");
let parent = relative_path.parent();
assert_eq!(parent, Some(Path::new("foo")));
let grand_parent = parent.and_then(Path::parent);
assert_eq!(grand_parent, Some(Path::new("")));
assert_eq!(grand_parent, Some(Path::new("")));
let great_grand_parent = grand_parent.and_then(Path::parent);
assert_eq!(great_grand_parent, None);
source

pub fn file_name(&self) -> Option<&str>

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.

Returns None if the path terminates in ...

Examples
assert_eq!(Some("bin"), Path::new("/usr/bin/").file_name());
assert_eq!(Some("foo.txt"), Path::new("tmp/foo.txt").file_name());
assert_eq!(Some("foo.txt"), Path::new("foo.txt/.").file_name());
assert_eq!(Some("foo.txt"), Path::new("foo.txt/.//").file_name());
assert_eq!(None, Path::new("foo.txt/..").file_name());
assert_eq!(None, Path::new("/").file_name());
source

pub fn file_stem(&self) -> Option<&str>

Extracts the stem (non-extension) portion of self.file_name.

The stem is:

  • 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 .
Examples
assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
assert_eq!(".foo", Path::new(".foo").file_stem().unwrap());
assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
source

pub fn get(&self, cwd: &DirRef) -> Option<FileOrDir>

Returns the file or directory at the given path.

The path can be relative or absolute.

If the path does not point to a file system object, None is returned.

source

pub fn get_file(&self, cwd: &DirRef) -> Option<FileRef>

Returns the file at the given path.

The path can be relative or absolute.

If the path does not point to a file, None is returned.

source

pub fn get_dir(&self, cwd: &DirRef) -> Option<DirRef>

Returns the directory at the given path.

The path can be relative or absolute.

If the path does not point to a directory, None is returned.

source

pub fn relative<P>(&self, base: P) -> Option<PathBuf>where P: AsRef<Path>,

Construct a relative path from a provided base directory path to the provided path.

source

pub fn extension(&self) -> Option<&str>

Extracts the extension (without the leading dot) 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;
  • Otherwise, the portion of the file name after the final .
Examples
assert_eq!(None, Path::new("foo").extension());
assert_eq!(None, Path::new(".foo").extension());
assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());

Trait Implementations§

source§

impl AsRef<Path> for PathBuf

source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl AsRef<str> for PathBuf

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Borrow<Path> for PathBuf

source§

fn borrow(&self) -> &Path

Immutably borrows from an owned value. Read more
source§

impl Clone for PathBuf

source§

fn clone(&self) -> PathBuf

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PathBuf

source§

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

Formats the value using the given formatter. Read more
source§

impl Default for PathBuf

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl Deref for PathBuf

§

type Target = Path

The resulting type after dereferencing.
source§

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

Dereferences the value.
source§

impl DerefMut for PathBuf

source§

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

Mutably dereferences the value.
source§

impl Display for PathBuf

source§

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

Formats the value using the given formatter. Read more
source§

impl<T> From<&T> for PathBufwhere T: ?Sized + AsRef<str>,

source§

fn from(value: &T) -> Self

Converts to this type from the input type.
source§

impl From<PathBuf> for String

source§

fn from(value: PathBuf) -> Self

Converts to this type from the input type.
source§

impl From<String> for PathBuf

source§

fn from(value: String) -> Self

Converts to this type from the input type.
source§

impl<P> FromIterator<P> for PathBufwhere P: AsRef<Path>,

source§

fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = P>,

Creates a value from an iterator. Read more
source§

impl Ord for PathBuf

source§

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

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<PathBuf> for PathBuf

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<PathBuf> for PathBuf

source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Eq for PathBuf

source§

impl StructuralEq for PathBuf

source§

impl StructuralPartialEq for PathBuf

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

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

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

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

Performs the conversion.