MaybePath
A Near-Zero-Overhead read-only Path wrapper that can also hold a str.
The primary usecase is static initialization of a Path at compile-time.
It implements Deref<Target = Path>, so you can treat it as a drop-in replacement for Path in most cases.
Basic usage is as follows:
use ;
// These are both equivalent to `Path::new("foo/bar/baz")`
// But normally the const could not also be a `Path`
let path = new_path;
const PATH: MaybePath = new_str;
// An equivalent to `Cow<Path>` is also included
let not_a_cow = new_path;
const NOT_A_COW: MaybePathBuf = new_str;
Performance
MaybePath is a zero-runtime-cost abstraction over Path and str.
Benchmarks show that MaybePath is faster than Cow<Path> for most operations:
- Read:
798.20 psvs1.5002 ns - Clone:
811.02 psvs2.3745 ns
However, it does store a u8 to differentiate between Path and str,
which may increase memory usage for massive amounts of MaybePath instances.
Safety
While it is possible to access the underlying memory as-is with as_path_unchecked or as_str_unchecked,
it is not recommended to do so unless you are absolutely sure that the MaybePath is a Path or str.
However, in the current implementation of Path, all valid str's are valid paths - but this implementation detail may change in the future.
This implementation uses a union internally, since this method yields performance gains of up to 4x over using an enum.
use MaybePath;
let path = new_path;
const PATH: MaybePath = new_str;
Also includes MaybePathBuf, a drop-in replacement for Cow<Path> that includes a 3rd state for MaybePath's str variant.
This type has performance matching that of Cow<Path>: ( Produced ASM is identical )
- Read:
1.5958 nsvs1.6596 ns - Clone:
3.8059 nsvs3.2304 ns - AsRef x1000:
2.1066 µsvs3.2081 µs
use MaybePathBuf;
let path = new_path;
const PATH: MaybePathBuf = new_str;