sugar_path
Ergonomic path manipulation for Rust — normalize, absolutize, relativize, and slash-convert with zero-cost Cow returns.
Quick start
use SugarPath;
// Normalize messy paths
assert_eq!;
// Absolutize relative paths
let abs = "src/main.rs".absolutize;
// Get relative paths between two locations
assert_eq!;
// Cross-platform slash conversion
assert_eq!;
API overview
All methods are provided by the SugarPath trait, implemented for Path, &str, and String.
Path conversion
| Method | Description |
|---|---|
as_path() |
Convert &str / String to &Path — lets you call SugarPath methods on strings directly |
to_slash() |
Convert a path to a /-separated string (None if invalid UTF-8) |
to_slash_lossy() |
Like to_slash(), but replaces invalid UTF-8 with U+FFFD |
use Path;
use SugarPath;
assert_eq!;
Normalization
normalize() resolves . and .. segments and collapses repeated separators. Returns Cow::Borrowed when the path is already clean.
use Path;
use SugarPath;
assert_eq!;
Absolutize
absolutize() resolves a relative path against the current working directory. absolutize_with() lets you supply a custom base.
use SugarPath;
Relative paths
relative() computes the relative path from self to a target.
use Path;
use SugarPath;
assert_eq!;
assert_eq!;
assert_eq!;
Features
| Feature | Description |
|---|---|
cached_current_dir |
Cache std::env::current_dir() so absolutize() only reads it once |
= { = "2", = ["cached_current_dir"] }
Performance
- Zero-alloc fast paths — methods return
Cow<'_, Path>, borrowing the input when no transformation is needed. memchr-accelerated scanning for separator detection.SmallVec<[_; 8]>keeps component lists on the stack for typical path depths.
Platform support
- Unix and Windows, tested in CI on Ubuntu, macOS, and Windows.
to_slash/to_slash_lossyprovide consistent/-separated output across all platforms.- On Windows, forward slashes in input are normalized to
\.
License
MIT