[Pre-RFC] Patterns allowing transparent wrapper types

I came upon this because I have a #![forbid(unsafe)] crate where these conversions would be handy. Namely it's a crate with its own PathBuf and Path types ala std which specify paths for cryptographic key derivation. Path is a #[repr(transparent)] reference type ala std.

I would love to use a feature like this if available for a safe AsRef<Path> impl for my PathBuf type, especially so I can do a Deref<Target=Path> impl for PathBuf to delegate common methods to the reference type.

There's one complication however: unlike std, my path components aren't a "view" over a string type, but rather are a Vec<Vec<u8>> so as to be binary-safe. What I'd like is a safe conversion to a struct Path<'a>(&'a [&'a [u8]]).

So I guess my question is: would it be possible to support these sort of nested reference conversions, namely for Vec for my purposes, but perhaps more generally for types which impl AsRef<[T]>? That is to say: will it be possible to do reference casts like this for slices-of-slices?

You can't convert a Vec<Vec<u8>> to a slice &[&[u8]] without reallocating.

2 Likes

Aah, oh well then. I guess I will need to do something more like PathBuf-like where I can store all of the components in a contiguous Vec<u8> and parse the components from that bytestring (e.g. mandating a max 255-byte component length and putting a prefix on each one).

If I did that, it sounds like in the future I could leverage this proposal as-is, however, which would be swell.

Or encoding the length like ASN.1, in one byte for any length N < 128 and two bytes (N / 128 + 128, N % 128) for any reasonable larger length.

If possible, use an iterator-of-slices (or even iterator-of-iterators) instead of slice-of-slice and you'll be able to do it without memory allocation.

4 Likes

Already done. I'm now using an unsafe pointer cast to accomplish the reference conversion this Pre-RFC aims to do safely, so it'd be great to replace it with a safe cast instead:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.