Stream: general

Topic: quick poll: `as` vs `transmute`


Jake Goulding (Jan 01 2019 at 23:54, on Zulip):

Please vote which you prefer using some emoji! I didn't test either, but I hope the intent is clear.

Jake Goulding (Jan 01 2019 at 23:54, on Zulip):
&mut *(v as *mut Val as *mut WrappedVal)
Jake Goulding (Jan 01 2019 at 23:55, on Zulip):
mem::transmute::<&mut Val, &mut WrappedVal>(v)
Alexander Regueiro (Jan 02 2019 at 00:44, on Zulip):

@Jake Goulding Yeah, I'm chipping away at that one... should have a WIP PR up in a few days I think.

snf (Jan 02 2019 at 01:15, on Zulip):

ByteOrder uses the first one though: https://github.com/BurntSushi/byteorder/blob/master/src/lib.rs#L744

Jake Goulding (Jan 02 2019 at 01:56, on Zulip):

I have a little voice in the back of my head that says "avoid transmute as much as possible", but I also feel that someone (maybe @eddyb ?) had a set of guidelines when transmute was "better".

nagisa (Jan 02 2019 at 11:19, on Zulip):

&mut *(v as *mut _ as *mut T) is preferred. One case where it catches an issue (and transmute won’t) is if you’re casting between fat pointers.

EDIT: oh wait... does it?
EDIT2: yeah, it does.

error[E0606]: casting `*mut dyn std::fmt::Display` as `*mut dyn std::fmt::Debug` is invalid
nagisa (Jan 02 2019 at 11:20, on Zulip):

I was also going to say that you avoid accidentally increasing the lifetime, but it turns out that it happens with the casts as well :frown:

unsafe fn foo(x: &mut u32) -> &'static mut u32 {
    // both work...
    //std::intrinsics::transmute::<&mut u32, &mut u32>(x)
    &mut *(x as *mut u32)
}
RalfJ (Jan 02 2019 at 15:26, on Zulip):

OTOH transmute at least screams DANGER, whereas as of a raw ptr type looks awfully harmless

RalfJ (Jan 02 2019 at 15:27, on Zulip):

as a reviewer I very strongly dislike these raw ptr casts, they are so easy to miss

nagisa (Jan 02 2019 at 16:15, on Zulip):

how about unsafe fn almost_transmute<T, U>(x: &mut T) -> &mut U { ... } ? Preserves the lifetime too!

centril (Jan 02 2019 at 16:16, on Zulip):

bikeshed: transmute_almost (since we have transmute_copy)

nagisa (Jan 02 2019 at 16:20, on Zulip):

transmute_me_maybe.

RalfJ (Jan 02 2019 at 16:45, on Zulip):

transmute_ref

Last update: Nov 20 2019 at 13:15UTC