Blanket implementation for `impl AsRef<[u8]> for T where T: Sized + Copy`?

Just a quick question/thought: is there a reason why there isn't a blanket implementation of AsRef similar to the following in the standard library? Note that the orphan rule prevented me from testing this, so I probably made a mistake in the implementation somewhere...

impl<T> AsRef<[u8]> for T
where
    T: Copy + Sized,
{
    fn as_ref(&self) -> &[u8] {
        self as &[u8]
    }
}

This would allow safe code to read uninitialized memory when T contains padding or MaybeUninit.

I know there are open questions about whether/when it is UB to read padding bytes, but even if it's not insta-UB, this seems like it would open the door to Heartbleed-like bugs without unsafe.

5 Likes

:flushed: In short, this is a terrible thing...

No shame in that; not everyone can forsee every consequence of such proposals. AFAIU, that's a lot of the reason discussion here is preferred over going straight to a PR that misses some subtle, but important detail.

I myself learned that ToString is very different than Into<String> in my first attempt at an RFC :slight_smile: .

You might be interested in bytemuck.

1 Like

Yup, that was part of the reason I was asking why this wasn't already a thing; it seemed so trivial!

That would be perfect, except that it won't work for my particular use case. What I was planning on using this for is as a key into a RRB tree, where bits would be grouped together to form the keys at each level. The padding bytes mean that won't work... no big deal though, I can do something very similar to what I was originally planning by requiring keys to implement Hash.

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