Creating types analoguous to `Path` and `PathBuf`

Hi there!

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?

Many thanks :slight_smile:

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.

1 Like

Doesn't that require unsafe?

Yes, dereferencing a raw pointer requires unsafe.

1 Like

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.

3 Likes

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.

2 Likes

I've wrote an online document for defining custom slice types... in Japanese :sweat_smile: (Rustで独自のスライス型を定義する本), but you can see the implementation example https://gitlab.com/lo48576/rust-custom-slice-book/-/tree/master/sample/src for reference. The sample code only contains english comments.
(The definition of new()-like methods are here.)

2 Likes

Ok, that's clearer now..
Thanks everyone for your help :slight_smile:

You make it generic, opt out of Sized, then coerce. Code.

Again, you opt out of implicit Sized bounds. More code.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.