Conversion from a Path
to a C-compatible string is not easy in libstd.
Because the conversion is not well-defined on Windows, access to bytes is hidden behind cfg(unix)
. However, that means that in user code the correct conversion code for Unix also has to be behind cfg(unix)
, and requires writing a fallback implementation. That is a lot to ask for such a minor detail, so people end up writing CString::new(path.to_str().unwrap())
which is the worst case of all.
I suggest adding TryFrom
which preserves bytes on Unix, and falls back to UTF-8 on Windows.
On Windows there's no right way to convert Unicode path to bytes. ANSI code pages could be useful in some cases, but they're a lossy legacy encoding and make the conversion environment-specific. OTOH sticking to UTF-8 wouldn't be worse than the current practice of .to_str().unwrap()
.