Crate pathtrim

source ·
Expand description

pathtrim - When all you need is the last few parts of a path.

This crate provides a simple way to obtain the last n parts of a path by implementing the TrimmablePath trait on anything that implements AsRefstd::path::Path.

Edge Cases & Limitations

  • The crate supports both Unix and Windows paths.
  • It doesn’t handle cases where the path is double-escaped or contains invalid components.
  • When using trim_to_nth, the number of parts to be trimmed should be less than the total number of components in the path, otherwise it returns None.

Usage

Add this to your Cargo.toml:

[dependencies]
pathtrim = "0.2.0"

And this to your main file:

use std::path::Path;
use pathtrim::TrimmablePath;

Examples

Basic usage

use std::path::Path;
use pathtrim::TrimmablePath;

let path = Path::new("/usr/local/bin/application");
let trimmed = path.trim_to_nth(2).unwrap();
assert_eq!(trimmed.to_str().unwrap(), "bin/application");

Different platforms

Unix:

use std::path::Path;
use pathtrim::TrimmablePath;
let path = Path::new("/usr/local/bin/application");
let trimmed = path.trim_to_nth(3).unwrap();
assert_eq!(trimmed.to_str().unwrap(), "local/bin/application");

Windows:

use std::path::Path;
use pathtrim::TrimmablePath;
let path = Path::new(r"C:\Program Files\package\bin\application");
let trimmed = path.trim_to_nth(2).unwrap();
assert_eq!(trimmed.to_str().unwrap(), r"bin\application");

Edge Cases

use std::path::Path;
use pathtrim::TrimmablePath;
let path = Path::new("/");
let trimmed = path.trim_to_nth(1);
assert!(trimmed.is_none());

Further Reading

To understand further about path components and various related APIs, refer to the official Rust documentation:

Traits

  • A trait to easily obtain the last n parts of a path.