Struct AppPath

Source
pub struct AppPath { /* private fields */ }
Expand description

Creates paths relative to the executable location for applications.

AppPath is the core type for building portable applications where all files and directories stay together with the executable. This design choice makes applications truly portable - they can run from USB drives, network shares, or any directory without installation.

§Available Trait Implementations

AppPath implements a comprehensive set of traits for seamless integration with Rust’s standard library and idiomatic code patterns:

Core Traits:

  • Clone - Efficient cloning (only copies the resolved path)
  • Debug - Useful debug output showing the resolved path
  • Default - Creates a path pointing to the executable directory
  • Display - Human-readable path display

Comparison Traits:

  • PartialEq, Eq - Compare paths for equality
  • PartialOrd, Ord - Lexicographic ordering for sorting
  • Hash - Use as keys in HashMap, HashSet, etc.

Conversion Traits:

  • AsRef<Path> - Use with any API expecting &Path
  • Deref<Target=Path> - Direct access to Path methods (e.g., .extension())
  • Borrow<Path> - Enable borrowing as &Path for collection compatibility
  • From<T> for &str, String, &Path, PathBuf, etc. - Flexible construction
  • Into<PathBuf> - Convert to owned PathBuf

These implementations make AppPath a zero-cost abstraction that works seamlessly with existing Rust code while providing portable path resolution.

§Design Rationale

Why relative to executable instead of current directory?

  • Current directory depends on where the user runs the program from
  • Executable location is reliable and predictable
  • Enables true portability - the entire application can be moved as one unit

Why infallible API instead of Result-based?

  • Executable location determination rarely fails in practice
  • When it does fail, it indicates fundamental system issues
  • Infallible API eliminates error handling boilerplate from every usage site
  • Results in cleaner, more maintainable application code

Why static caching?

  • Executable location never changes during program execution
  • Avoids repeated system calls for performance
  • Thread-safe and efficient for concurrent applications

§Perfect For

  • Portable applications that run from USB drives or network shares
  • Development tools that should work anywhere without installation
  • Corporate environments where you can’t install software system-wide
  • Containerized applications with predictable, self-contained layouts
  • Embedded systems with simple, fixed directory structures
  • CLI tools that need configuration and data files nearby

§Memory Layout

Each AppPath instance stores only the final resolved path (PathBuf), making it memory-efficient. The original input path is not retained, as the resolved path contains all necessary information for file operations.

AppPath {
    full_path: PathBuf  // Only field - minimal memory usage
}

§Thread Safety

AppPath is Send + Sync and can be safely shared between threads. The static executable directory cache is initialized once and safely shared across all threads.

§Panics

Panics on first use if the executable location cannot be determined. See crate-level documentation for comprehensive details on panic conditions and edge case handling.

§Examples

§Basic Usage

use app_path::AppPath;

// Simple relative paths - the common case
let config = AppPath::new("config.toml");
let data_dir = AppPath::new("data");
let logs = AppPath::new("logs/app.log");

// Use like normal paths
if config.exists() {
    let settings = std::fs::read_to_string(config.path())?;
}

// Create directories as needed
data_dir.create_dir_all()?;

§Mixed Portable and System Paths

use app_path::AppPath;

// Portable app files (relative paths)
let app_config = AppPath::new("config.toml");       // → exe_dir/config.toml
let app_data = AppPath::new("data/users.db");       // → exe_dir/data/users.db

// System integration (absolute paths)
let system_log = AppPath::new("/var/log/myapp.log"); // → /var/log/myapp.log
let temp_cache = AppPath::new(std::env::temp_dir().join("cache.db"));

println!("App config: {}", app_config);    // Portable
println!("System log: {}", system_log);    // System integration

§Performance-Conscious Usage

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

// Efficient - no unnecessary allocations
let config = AppPath::new("config.toml");          // &str
let data = AppPath::new(Path::new("data.db"));     // &Path

// When you have owned values, borrow them to avoid moves
let filename = "important.log".to_string();
let logs = AppPath::new(&filename);                 // &String - no move

// Use From trait when you want ownership transfer
let owned_path = PathBuf::from("cache.bin");
let cache: AppPath = owned_path.into();             // PathBuf moved

§Portable vs System Integration

use app_path::AppPath;

// Portable application files (relative paths)
let app_config = AppPath::new("config.toml");           // → exe_dir/config.toml
let app_data = AppPath::new("data/users.db");           // → exe_dir/data/users.db
let plugins = AppPath::new("plugins/my_plugin.dll");    // → exe_dir/plugins/my_plugin.dll

// System integration (absolute paths)
let system_config = AppPath::new("/etc/myapp/global.toml");  // → /etc/myapp/global.toml
let temp_file = AppPath::new(r"C:\temp\cache.dat");          // → C:\temp\cache.dat
let user_data = AppPath::new("/home/user/.myapp/prefs");     // → /home/user/.myapp/prefs

§Common Patterns

use app_path::AppPath;
use std::fs;

// Configuration file pattern
let config = AppPath::new("config.toml");
if config.exists() {
    let content = fs::read_to_string(config.path())?;
    // Parse configuration...
}

// Data directory pattern
let data_dir = AppPath::new("data");
data_dir.create_dir_all()?;  // Ensure directory exists
let user_db = AppPath::new("data/users.db");

// Logging pattern
let log_file = AppPath::new("logs/app.log");
log_file.create_dir_all()?;  // Create logs directory if needed
fs::write(log_file.path(), "Application started\n")?;

§Trait Implementation Examples

AppPath implements many useful traits that enable ergonomic usage patterns:

use app_path::AppPath;
use std::collections::{HashMap, BTreeSet};

// Default trait - creates path to executable directory
let exe_dir = AppPath::default();
assert_eq!(exe_dir, AppPath::new(""));

// Comparison traits - enable sorting and equality checks
let mut paths = vec![
    AppPath::new("z.txt"),
    AppPath::new("a.txt"),
    AppPath::new("m.txt"),
];
paths.sort(); // Uses Ord trait
assert!(paths[0] < paths[1]); // Uses PartialOrd trait

// Hash trait - use as keys in collections
let mut file_types = HashMap::new();
file_types.insert(AppPath::new("config.toml"), "Configuration");
file_types.insert(AppPath::new("data.db"), "Database");

// Ordered collections work automatically
let mut sorted_paths = BTreeSet::new();
sorted_paths.insert(AppPath::new("config.toml"));
sorted_paths.insert(AppPath::new("data.db"));

// Deref trait - direct access to Path methods
let config = AppPath::new("config.toml");
assert_eq!(config.extension(), Some("toml".as_ref())); // Direct Path method
assert_eq!(config.file_name(), Some("config.toml".as_ref()));

// Works with functions expecting &Path (deref coercion)
fn analyze_path(path: &std::path::Path) -> Option<&str> {
    path.extension()?.to_str()
}
assert_eq!(analyze_path(&config), Some("toml"));

// From trait - flexible construction from many types
let from_str: AppPath = "data.txt".into();
let from_pathbuf: AppPath = std::path::PathBuf::from("logs.txt").into();

// Display trait - human-readable output
println!("Config path: {}", config); // Clean path display

Implementations§

Source§

impl AppPath

Source

pub fn new(path: impl AsRef<Path>) -> Self

Creates file paths relative to the executable location.

This is the primary constructor for AppPath. The method accepts any type that implements AsRef<Path>, providing maximum flexibility while maintaining zero-allocation performance for most use cases.

§Design Choices

Why impl AsRef<Path> instead of specific types?

  • Accepts all path-like types: &str, String, &Path, PathBuf, etc.
  • Avoids unnecessary allocations through efficient borrowing
  • Provides a single, consistent API instead of multiple overloads
  • Enables efficient usage patterns for both owned and borrowed values

Why infallible constructor?

  • Executable location determination succeeds in >99.9% of real-world usage
  • Eliminates error handling boilerplate from every call site
  • Makes the API more ergonomic for the common case
  • Follows Rust conventions where new() implies infallible construction

Path Resolution Strategy:

  • Relative paths (e.g., "config.toml", "data/file.txt") are resolved relative to the executable’s directory - this is the primary use case
  • Absolute paths (e.g., "/etc/config", "C:\\temp\\file.txt") are used as-is, ignoring the executable’s directory - enables system integration

This dual behavior supports both portable applications (relative paths) and system integration (absolute paths) within the same API.

§Arguments
  • path - A path that will be resolved according to AppPath’s resolution strategy. Accepts any type implementing AsRef<Path>:

    • &str - String literals and string slices
    • String - Owned strings
    • &Path - Path references
    • PathBuf - Path buffers
    • And many others that implement AsRef<Path>

    Path Resolution:

    • Relative paths are resolved relative to the executable directory
    • Absolute paths are used as-is (not modified)
§Panics

Panics on first use if the executable location cannot be determined. This is a one-time initialization panic that occurs during static initialization of the executable directory cache.

See crate-level documentation for comprehensive details on:

  • When panics can occur (rare system failure conditions)
  • How edge cases are handled (root-level executables, containers)
  • Strategies for applications that need fallible behavior
§Performance Notes

This method is highly optimized:

  • Static caching: Executable location determined once, reused forever
  • Zero allocations: Uses AsRef<Path> to avoid unnecessary conversions
  • Minimal memory: Only stores the final resolved path
  • Thread-safe: Safe to call from multiple threads concurrently
§Examples
use app_path::AppPath;

// These create portable paths relative to your executable
let config = AppPath::new("config.toml");           // &str
let data = AppPath::new("data/users.db");           // &str with subdirectory
let logs = AppPath::new("logs/app.log");            // Nested directories
§Efficient Usage with Different Types
use app_path::AppPath;
use std::path::{Path, PathBuf};

// All of these are efficient - no unnecessary allocations
let from_str = AppPath::new("config.toml");         // &str → direct usage
let from_path = AppPath::new(Path::new("data.db")); // &Path → direct usage

// Borrow owned values to avoid moves when you need them later
let filename = "important.log".to_string();
let logs = AppPath::new(&filename);                 // &String → efficient borrowing
println!("Original filename: {}", filename);       // filename still available

let path_buf = PathBuf::from("cache.bin");
let cache = AppPath::new(&path_buf);                // &PathBuf → efficient borrowing
println!("Original path: {}", path_buf.display()); // path_buf still available
§Portable vs System Integration
use app_path::AppPath;

// Portable application files (relative paths)
let app_config = AppPath::new("config.toml");           // → exe_dir/config.toml
let app_data = AppPath::new("data/users.db");           // → exe_dir/data/users.db
let plugins = AppPath::new("plugins/my_plugin.dll");    // → exe_dir/plugins/my_plugin.dll

// System integration (absolute paths)
let system_config = AppPath::new("/etc/myapp/global.toml");  // → /etc/myapp/global.toml
let temp_file = AppPath::new(r"C:\temp\cache.dat");          // → C:\temp\cache.dat
let user_data = AppPath::new("/home/user/.myapp/prefs");     // → /home/user/.myapp/prefs
§Common Patterns
use app_path::AppPath;
use std::fs;

// Configuration file pattern
let config = AppPath::new("config.toml");
if config.exists() {
    let content = fs::read_to_string(config.path())?;
    // Parse configuration...
}

// Data directory pattern
let data_dir = AppPath::new("data");
data_dir.create_dir_all()?;  // Ensure directory exists
let user_db = AppPath::new("data/users.db");

// Logging pattern
let log_file = AppPath::new("logs/app.log");
log_file.create_dir_all()?;  // Create logs directory if needed
fs::write(log_file.path(), "Application started\n")?;
Source

pub fn path(&self) -> &Path

Get the full resolved path.

This is the primary method for getting the actual filesystem path where your file or directory is located.

§Examples
use app_path::AppPath;

let config = AppPath::new("config.toml");

// Get the path for use with standard library functions
println!("Config path: {}", config.path().display());

// The path is always absolute
assert!(config.path().is_absolute());
Source

pub fn exists(&self) -> bool

Check if the path exists.

§Examples
use app_path::AppPath;

let config = AppPath::new("config.toml");

if config.exists() {
    println!("Config file found!");
} else {
    println!("Config file not found, using defaults.");
}
Source

pub fn create_dir_all(&self) -> Result<()>

Create parent directories if they don’t exist.

This is equivalent to calling std::fs::create_dir_all on the parent directory of this path.

§Examples
use app_path::AppPath;
use std::env;

// Use a temporary directory for the example
let temp_dir = env::temp_dir().join("app_path_example");
let data_file_path = temp_dir.join("data/users/profile.json");
let data_file = AppPath::new(data_file_path);

// Ensure the "data/users" directory exists
data_file.create_dir_all()?;

// Verify the directory was created
assert!(data_file.path().parent().unwrap().exists());

Methods from Deref<Target = Path>§

1.0.0 · Source

pub fn as_os_str(&self) -> &OsStr

Yields the underlying OsStr slice.

§Examples
use std::path::Path;

let os_str = Path::new("foo.txt").as_os_str();
assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1.0.0 · Source

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

Yields a &str slice if the Path is valid unicode.

This conversion may entail doing a check for UTF-8 validity. Note that validation is performed because non-UTF-8 strings are perfectly valid for some OS.

§Examples
use std::path::Path;

let path = Path::new("foo.txt");
assert_eq!(path.to_str(), Some("foo.txt"));
1.0.0 · Source

pub fn to_string_lossy(&self) -> Cow<'_, str>

Converts a Path to a Cow<str>.

Any non-UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.

§Examples

Calling to_string_lossy on a Path with valid unicode:

use std::path::Path;

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

1.0.0 · Source

pub fn to_path_buf(&self) -> PathBuf

Converts a Path to an owned PathBuf.

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

let path_buf = Path::new("foo.txt").to_path_buf();
assert_eq!(path_buf, PathBuf::from("foo.txt"));
1.0.0 · Source

pub fn is_absolute(&self) -> bool

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.

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

§Examples
use std::path::Path;

assert!(!Path::new("foo.txt").is_absolute());
1.0.0 · Source

pub fn is_relative(&self) -> bool

Returns true if the Path is relative, i.e., not absolute.

See is_absolute’s documentation for more details.

§Examples
use std::path::Path;

assert!(Path::new("foo.txt").is_relative());
1.0.0 · Source

pub fn has_root(&self) -> bool

Returns true if the Path has a root.

  • On Unix, a path has a root if it begins with /.

  • On Windows, a path has a root if it:

    • has no prefix and begins with a separator, e.g., \windows
    • has a prefix followed by a separator, e.g., c:\windows but not c:windows
    • has any non-disk prefix, e.g., \\server\share
§Examples
use std::path::Path;

assert!(Path::new("/etc/passwd").has_root());
1.0.0 · Source

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

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

This means it returns Some("") for relative paths with one component.

Returns None if the path terminates in a root or prefix, or if it’s the empty string.

§Examples
use std::path::Path;

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("")));
let great_grand_parent = grand_parent.and_then(Path::parent);
assert_eq!(great_grand_parent, None);
1.28.0 · Source

pub fn ancestors(&self) -> Ancestors<'_>

Produces an iterator over Path and its ancestors.

The iterator will yield the Path that is returned if the parent method is used zero or more times. If the parent method returns None, the iterator will do likewise. The iterator will always yield at least one value, namely Some(&self). Next it will yield &self.parent(), &self.parent().and_then(Path::parent) and so on.

§Examples
use std::path::Path;

let mut ancestors = Path::new("/foo/bar").ancestors();
assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
assert_eq!(ancestors.next(), Some(Path::new("/foo")));
assert_eq!(ancestors.next(), Some(Path::new("/")));
assert_eq!(ancestors.next(), None);

let mut ancestors = Path::new("../foo/bar").ancestors();
assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
assert_eq!(ancestors.next(), Some(Path::new("../foo")));
assert_eq!(ancestors.next(), Some(Path::new("..")));
assert_eq!(ancestors.next(), Some(Path::new("")));
assert_eq!(ancestors.next(), None);
1.0.0 · Source

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

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
use std::path::Path;
use std::ffi::OsStr;

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());
1.7.0 · Source

pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
where P: AsRef<Path>,

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.

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

let path = Path::new("/test/haha/foo.txt");

assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));

assert!(path.strip_prefix("test").is_err());
assert!(path.strip_prefix("/te").is_err());
assert!(path.strip_prefix("/haha").is_err());

let prefix = PathBuf::from("/test/");
assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
1.0.0 · Source

pub fn starts_with<P>(&self, base: P) -> bool
where P: AsRef<Path>,

Determines whether base is a prefix of self.

Only considers whole path components to match.

§Examples
use std::path::Path;

let path = Path::new("/etc/passwd");

assert!(path.starts_with("/etc"));
assert!(path.starts_with("/etc/"));
assert!(path.starts_with("/etc/passwd"));
assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay

assert!(!path.starts_with("/e"));
assert!(!path.starts_with("/etc/passwd.txt"));

assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
1.0.0 · Source

pub fn ends_with<P>(&self, child: P) -> bool
where P: AsRef<Path>,

Determines whether child is a suffix of self.

Only considers whole path components to match.

§Examples
use std::path::Path;

let path = Path::new("/etc/resolv.conf");

assert!(path.ends_with("resolv.conf"));
assert!(path.ends_with("etc/resolv.conf"));
assert!(path.ends_with("/etc/resolv.conf"));

assert!(!path.ends_with("/resolv.conf"));
assert!(!path.ends_with("conf")); // use .extension() instead
1.0.0 · Source

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

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
use std::path::Path;

assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
§See Also

This method is similar to Path::file_prefix, which extracts the portion of the file name before the first .

Source

pub fn file_prefix(&self) -> Option<&OsStr>

🔬This is a nightly-only experimental API. (path_file_prefix)

Extracts the prefix of self.file_name.

The prefix is:

  • None, if there is no file name;
  • The entire file name if there is no embedded .;
  • The portion of the file name before the first non-beginning .;
  • The entire file name if the file name begins with . and has no other .s within;
  • The portion of the file name before the second . if the file name begins with .
§Examples
use std::path::Path;

assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
§See Also

This method is similar to Path::file_stem, which extracts the portion of the file name before the last .

1.0.0 · Source

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

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
use std::path::Path;

assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
1.0.0 · Source

pub fn join<P>(&self, path: P) -> PathBuf
where P: AsRef<Path>,

Creates an owned PathBuf with path adjoined to self.

If path is absolute, it replaces the current path.

See PathBuf::push for more details on what it means to adjoin a path.

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

assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh"));
1.0.0 · Source

pub fn with_file_name<S>(&self, file_name: S) -> PathBuf
where S: AsRef<OsStr>,

Creates an owned PathBuf like self but with the given file name.

See PathBuf::set_file_name for more details.

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

let path = Path::new("/tmp/foo.png");
assert_eq!(path.with_file_name("bar"), PathBuf::from("/tmp/bar"));
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"));
1.0.0 · Source

pub fn with_extension<S>(&self, extension: S) -> PathBuf
where S: AsRef<OsStr>,

Creates an owned PathBuf like self but with the given extension.

See PathBuf::set_extension for more details.

§Examples
use std::path::Path;

let path = Path::new("foo.rs");
assert_eq!(path.with_extension("txt"), Path::new("foo.txt"));
assert_eq!(path.with_extension(""), Path::new("foo"));

Handling multiple extensions:

use std::path::Path;

let path = Path::new("foo.tar.gz");
assert_eq!(path.with_extension("xz"), Path::new("foo.tar.xz"));
assert_eq!(path.with_extension("").with_extension("txt"), Path::new("foo.txt"));

Adding an extension where one did not exist:

use std::path::Path;

let path = Path::new("foo");
assert_eq!(path.with_extension("rs"), Path::new("foo.rs"));
Source

pub fn with_added_extension<S>(&self, extension: S) -> PathBuf
where S: AsRef<OsStr>,

🔬This is a nightly-only experimental API. (path_add_extension)

Creates an owned PathBuf like self but with the extension added.

See PathBuf::add_extension for more details.

§Examples
#![feature(path_add_extension)]

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

let path = Path::new("foo.rs");
assert_eq!(path.with_added_extension("txt"), PathBuf::from("foo.rs.txt"));

let path = Path::new("foo.tar.gz");
assert_eq!(path.with_added_extension(""), PathBuf::from("foo.tar.gz"));
assert_eq!(path.with_added_extension("xz"), PathBuf::from("foo.tar.gz.xz"));
assert_eq!(path.with_added_extension("").with_added_extension("txt"), PathBuf::from("foo.tar.gz.txt"));
1.0.0 · 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.

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
use std::path::{Path, Component};
use std::ffi::OsStr;

let mut components = Path::new("/tmp/foo.txt").components();

assert_eq!(components.next(), Some(Component::RootDir));
assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
assert_eq!(components.next(), None)
1.0.0 · Source

pub fn iter(&self) -> Iter<'_>

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.

§Examples
use std::path::{self, Path};
use std::ffi::OsStr;

let mut it = Path::new("/tmp/foo.txt").iter();
assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
assert_eq!(it.next(), Some(OsStr::new("tmp")));
assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
assert_eq!(it.next(), None)
1.0.0 · Source

pub fn display(&self) -> Display<'_>

Returns an object that implements Display for safely printing paths that may contain non-Unicode data. This may perform lossy conversion, depending on the platform. If you would like an implementation which escapes the path please use Debug instead.

§Examples
use std::path::Path;

let path = Path::new("/tmp/foo.rs");

println!("{}", path.display());
1.5.0 · Source

pub fn metadata(&self) -> Result<Metadata, Error>

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.

§Examples
use std::path::Path;

let path = Path::new("/Minas/tirith");
let metadata = path.metadata().expect("metadata call failed");
println!("{:?}", metadata.file_type());

Queries the metadata about a file without following symlinks.

This is an alias to fs::symlink_metadata.

§Examples
use std::path::Path;

let path = Path::new("/Minas/tirith");
let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
println!("{:?}", metadata.file_type());
1.5.0 · Source

pub fn canonicalize(&self) -> Result<PathBuf, Error>

Returns the canonical, absolute form of the path with all intermediate components normalized and symbolic links resolved.

This is an alias to fs::canonicalize.

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

let path = Path::new("/foo/test/../test/bar.rs");
assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
Source

pub fn normalize_lexically(&self) -> Result<PathBuf, NormalizeError>

🔬This is a nightly-only experimental API. (normalize_lexically)

Normalize a path, including .. without traversing the filesystem.

Returns an error if normalization would leave leading .. components.

This function always resolves .. to the “lexical” parent. That is “a/b/../c” will always resolve to a/c which can change the meaning of the path. In particular, a/c and a/b/../c are distinct on many systems because b may be a symbolic link, so its parent isn’t a.

path::absolute is an alternative that preserves ... Or Path::canonicalize can be used to resolve any .. by querying the filesystem.

Reads a symbolic link, returning the file that the link points to.

This is an alias to fs::read_link.

§Examples
use std::path::Path;

let path = Path::new("/laputa/sky_castle.rs");
let path_link = path.read_link().expect("read_link call failed");
1.5.0 · Source

pub fn read_dir(&self) -> Result<ReadDir, Error>

Returns an iterator over the entries within a directory.

The iterator will yield instances of io::Result<fs::DirEntry>. New errors may be encountered after an iterator is initially constructed.

This is an alias to fs::read_dir.

§Examples
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());
    }
}
1.5.0 · Source

pub fn exists(&self) -> bool

Returns true if the path points at an existing entity.

Warning: this method may be error-prone, consider using try_exists() instead! It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.

This function will traverse symbolic links to query information about the destination file.

If you cannot access the metadata of the file, e.g. because of a permission error or broken symbolic links, this will return false.

§Examples
use std::path::Path;
assert!(!Path::new("does_not_exist.txt").exists());
§See Also

This is a convenience function that coerces errors to false. If you want to check errors, call Path::try_exists.

1.63.0 · Source

pub fn try_exists(&self) -> Result<bool, Error>

Returns Ok(true) if 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 Ok(false).

Path::exists() only checks whether or not a path was both found and readable. By contrast, try_exists will return Ok(true) or Ok(false), respectively, if the path was verified to exist or not exist. If its existence can neither be confirmed nor denied, it will propagate an Err(_) instead. This can be the case if e.g. listing permission is denied on one of the parent directories.

Note that while this avoids some pitfalls of the exists() method, it still can not prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios where those bugs are not an issue.

This is an alias for std::fs::exists.

§Examples
use std::path::Path;
assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
1.5.0 · Source

pub fn is_file(&self) -> bool

Returns true if 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.

If you cannot access the metadata of the file, e.g. because of a permission error or broken symbolic links, this will return false.

§Examples
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.

When the goal is simply to read from (or write to) the source, the most reliable way to test the source can be read (or written to) is to open it. Only using is_file can break workflows like diff <( prog_a ) on a Unix-like system for example. See fs::File::open or fs::OpenOptions::open for more information.

1.5.0 · Source

pub fn is_dir(&self) -> bool

Returns true if the path exists on disk and is pointing at a directory.

This function will traverse symbolic links to query information about the destination file.

If you cannot access the metadata of the file, e.g. because of a permission error or broken symbolic links, this will return false.

§Examples
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.

Returns true if the path exists on disk and is pointing at a symbolic link.

This function will not traverse symbolic links. In case of a broken symbolic link this will also return true.

If you cannot access the directory containing the file, e.g., because of a permission error, this will return false.

§Examples
use std::path::Path;
use std::os::unix::fs::symlink;

let link_path = Path::new("link");
symlink("/origin_does_not_exist/", link_path).unwrap();
assert_eq!(link_path.is_symlink(), true);
assert_eq!(link_path.exists(), false);
§See Also

This is a convenience function that coerces errors to false. If you want to check errors, call fs::symlink_metadata and handle its Result. Then call fs::Metadata::is_symlink if it was Ok.

Trait Implementations§

Source§

impl AsRef<Path> for AppPath

Source§

fn as_ref(&self) -> &Path

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

impl Borrow<Path> for AppPath

Source§

fn borrow(&self) -> &Path

Allows AppPath to be borrowed as a Path.

This enables AppPath to be used seamlessly in collections that are keyed by Path, and allows for efficient lookups using &Path values.

§Examples
use app_path::AppPath;
use std::collections::HashMap;
use std::path::Path;

let mut path_map = HashMap::new();
let app_path = AppPath::new("config.toml");
path_map.insert(app_path, "config data");

// Can look up using a &Path
let lookup_path = Path::new("relative/to/exe/config.toml");
// Note: This would only work if the paths actually match
Source§

impl Clone for AppPath

Source§

fn clone(&self) -> AppPath

Returns a duplicate 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 AppPath

Source§

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

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

impl Default for AppPath

Source§

fn default() -> Self

Creates an AppPath pointing to the executable’s directory.

This is equivalent to calling AppPath::new(""). The default instance represents the directory containing the executable, which is useful as a starting point for portable applications.

§Examples
use app_path::AppPath;

let exe_dir = AppPath::default();
let empty_path = AppPath::new("");

// Default should be equivalent to new("")
assert_eq!(exe_dir, empty_path);

// Both should point to the executable directory
assert_eq!(exe_dir.path(), app_path::exe_dir());
Source§

impl Deref for AppPath

Source§

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

Provides direct access to the underlying Path through deref coercion.

This allows AppPath to be used directly with any API that expects a &Path, making it a zero-cost abstraction in many contexts. All Path methods become directly available on AppPath instances.

§Examples
use app_path::AppPath;

let app_path = AppPath::new("config.toml");

// Direct access to Path methods through deref
assert_eq!(app_path.extension(), Some("toml".as_ref()));
assert_eq!(app_path.file_name(), Some("config.toml".as_ref()));

// Works with functions expecting &Path
fn process_path(path: &std::path::Path) {
    println!("Processing: {}", path.display());
}

process_path(&app_path); // Automatic deref coercion
Source§

type Target = Path

The resulting type after dereferencing.
Source§

impl Display for AppPath

Source§

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

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

impl From<&Path> for AppPath

Source§

fn from(path: &Path) -> Self

Converts to this type from the input type.
Source§

impl From<&PathBuf> for AppPath

Source§

fn from(path: &PathBuf) -> Self

Converts to this type from the input type.
Source§

impl From<&String> for AppPath

Source§

fn from(path: &String) -> Self

Converts to this type from the input type.
Source§

impl From<&str> for AppPath

Source§

fn from(path: &str) -> Self

Converts to this type from the input type.
Source§

impl From<AppPath> for PathBuf

Source§

fn from(app_path: AppPath) -> Self

Converts to this type from the input type.
Source§

impl From<PathBuf> for AppPath

Source§

fn from(path: PathBuf) -> Self

Converts to this type from the input type.
Source§

impl From<String> for AppPath

Source§

fn from(path: String) -> Self

Converts to this type from the input type.
Source§

impl Hash for AppPath

Source§

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

Computes a hash for the AppPath based on its resolved path.

This enables AppPath to be used as keys in hash-based collections like HashMap and HashSet. The hash is computed from the full resolved path, ensuring consistent behavior.

§Examples
use app_path::AppPath;
use std::collections::HashMap;

let mut config_map = HashMap::new();
let config_path = AppPath::new("config.toml");
config_map.insert(config_path, "Configuration file");
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for AppPath

Source§

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

Compares two AppPath instances lexicographically based on their resolved paths.

This provides a total ordering that enables AppPath to be used in sorted collections like BTreeMap and BTreeSet.

§Examples
use app_path::AppPath;
use std::collections::BTreeSet;

let mut paths = BTreeSet::new();
paths.insert(AppPath::new("config.toml"));
paths.insert(AppPath::new("data.db"));
paths.insert(AppPath::new("app.log"));

// Paths are automatically sorted lexicographically
let sorted: Vec<_> = paths.into_iter().collect();
1.21.0 · Source§

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

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

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

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

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

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

impl PartialEq for AppPath

Source§

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

Compares two AppPath instances for equality based on their resolved paths.

Two AppPath instances are considered equal if their full resolved paths are identical, regardless of how they were constructed.

§Examples
use app_path::AppPath;

let path1 = AppPath::new("config.toml");
let path2 = AppPath::new("config.toml");
let path3 = AppPath::new("other.toml");

assert_eq!(path1, path2);
assert_ne!(path1, path3);
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for AppPath

Source§

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

Compares two AppPath instances lexicographically based on their resolved paths.

The comparison is performed on the full resolved paths, providing consistent ordering for sorting and collection operations.

§Examples
use app_path::AppPath;

let path1 = AppPath::new("a.txt");
let path2 = AppPath::new("b.txt");

assert!(path1 < path2);
1.0.0 · Source§

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

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

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

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Eq for AppPath

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

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

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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 T
where 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

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 T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

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

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

Source§

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 T
where U: TryFrom<T>,

Source§

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.