I'm currently trying to make some types to represent some paths with a custom type. These paths cannot use every character, and they have limitations due to my current case.
What I'd like to do is create types like MySpecialPath and MySpecialPathBuf, analoguous to Path and PathBuf.
But I'm a bit stuck: while it's easy to create the MySpecialPathBuf type, the other one is tricky as it is unsized. And I can't really wrap my head around how to create it.
I was thinking of something like this:
struct MySpecialPath(str);
But I'm unable to find how to "instanciate" this struct type, or how to implement some traits like Display which throw at me an error telling my type is unsized.
Can someone enlighten me on how to solve this problem?
You create &[u8] (or &str if it's always utf-8), get *const [u8] pointer, and then cast the pointer (not transmute!) to your unsized *const MySpecialPath and dereference that.
Put that in a helper function so that input and output lifetimes are the same.
But in this case, if your struct is repr(transparent), this cast and the following dereference are valid, so the safe function wrapping them will be sound.
unsafe is what's used inside Path, at least for now, along with #[repr(transparent)] to make the behaviour defined, but unsafe. There's no current safe way to create an unsized wrapper around an existing unsized type that I can find.
You end up with something like this Rust Playground to have a sound equivalent of Path and PathBuf, but based around str and String. Note that I've missed out a lot there - Borrow and ToOwned impls being the most obvious.