4 ms·
If you’re dealing with pure data, reinterpret_cast/mem::transmute is fine, and for certain types of low-level code, necessary. In Rust, I’ve recently discovered
by codeflo 5y ago
If you’re dealing with pure data, reinterpret_cast/mem::transmute is fine, and for certain types of low-level code, necessary. In Rust, I’ve recently discovered the “bytemuck” crate, which offers ways to do that safely.
- Animats 5y ago"Pure data" has a very specific meaning there. "Bytemuck" uses the trait called "Pod", for "plain old data". What they mean is a structure for which all bit combinations are valid. This includes u8, u16, etc., and the floating point types, but excludes all reference types. "bool" is excluded (because it takes up 8 bits but only 2 of 256 values are valid), as are strings and chars, because they have to follow Unicode rules. And there must be no padding bytes in the structure. For types with such attributes, coercions are safe. C++ could potentially have something like "reinterpret_cast" which worked only on such types. This would make the risky form of reinterpret_cast less necessary, and some projects might disallow it. It's always hard to retrofit safety to a code base. You get a lot of pushback.
- gpderetta 5y agoC++ had the concept of POD type, but it has been superceded by StandardLayout.