Stream: t-lang/wg-unsafe-code-guidelines

Topic: Is reinerpreting a slice &[u8] to &[bool] UB?

Maik Klein (Jul 26 2019 at 08:54, on Zulip):


RalfJ (Jul 26 2019 at 09:48, on Zulip):

@Maik Klein it is UB unless you know for sure that every element in the slice is either 0 or 1

RalfJ (Jul 26 2019 at 09:49, on Zulip):

IOW, the slice has to contain bytes that are "valid" for bool

RalfJ (Jul 26 2019 at 09:50, on Zulip):

However, this is based on the strictest possible resolution for We might end up being more relaxed and decide that data behind references does not have to be valid until the reference is actually used (for some notion of "use"). But, until the lang team decided that this is not UB, it is UB (to remain forward compatible).

Maik Klein (Jul 26 2019 at 17:00, on Zulip):

Thanks for the reply, just to be sure this would only apply to references and not pointers? So I could have worked around it by creating my own slice type?

pub struct SliceMut<'a, T> {
    start: *mut T,
    len: usize,
    _marker: PhantomData<&'a ()>,
RalfJ (Jul 26 2019 at 17:02, on Zulip):

by pointers you mean raw pointers?

Maik Klein (Jul 26 2019 at 17:02, on Zulip):


RalfJ (Jul 26 2019 at 17:02, on Zulip):

@Maik Klein you might be interested in :)

Maik Klein (Jul 27 2019 at 10:14, on Zulip):

Yeah that is essentially what I want thanks. Also much nice than my impl, I'll just steal it.

RalfJ (Jul 27 2019 at 10:24, on Zulip):

@Maik Klein notice that this is the kind of code that is correct in libstd but not correct outside

RalfJ (Jul 27 2019 at 10:24, on Zulip):

rustc reserves to change the way slices are represented etc, and libstd will be updated

RalfJ (Jul 27 2019 at 10:25, on Zulip):

but code outside libstd cannot make assumptions about rustc implementation details the same way libstd does

Maik Klein (Jul 27 2019 at 11:06, on Zulip):

Yeah I'd be fine to sync it manually until it would be on stable, but I just realized that unions with non copy fields are unstable as well

Maik Klein (Jul 27 2019 at 11:23, on Zulip):

So I just go with my own slice impl until this is on stable

Last update: Jul 14 2020 at 12:25UTC