News for hackers. Stuff that matters.
Re:Rust 1.56.0 and Rust 2021 by MaulingMonkey on Thursday October 21, 2021 @02:45PM (#28949184)
Per transmute's docs @ https://doc.rust-lang.org/std/mem/fn.transmute.html:

> Because transmute is a by-value operation, alignment of the transmuted values themselves is not a concern. As with any other function, the compiler already ensures both T and U are properly aligned. However, when transmuting values that point elsewhere (such as pointers, references, boxes…), the caller has to ensure proper alignment of the pointed-to values.

The post you've linked transmutes a reference, and as the caller fails to explicitly ensure proper alignment, it explicitly risks invoking undefined behavior - I would consider the code buggy. The easiest way to prove it's broken would be to create an reference that's more likely to be unaligned (&array[1] instead of &array[0]?) and run the code on a less misalignment-tolerant platform (ARM?).

Here are some 100% sound alternatives using bytemuck (no unsafe required!) and core::ptr::{read,write}_unaligned (unsafe required):

https://play.rust-lang.org/?version=stable&mode=debug&editio...

There are no comments on this comment yet.