3 ms·
Per transmute's docs @ https://doc.rust-lang.org/std/mem/fn.transmute.html https://doc.rust-lang.org/std/mem/fn.transmute.html: > Because transmute is a by-val
by MaulingMonkey 5y ago
Per transmute's docs @ https://doc.rust-lang.org/std/mem/fn.transmute.html 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&edition=2018&gist=bc30cc223eb8a454ca78338cfbee0a7a https://play.rust-lang.org/?version=stable&mode=debug&editio...