SeaHash: A fast, portable hash function in Rust
Type punning is a mess in C because you have to jump through hoops to make it legal. The language subsequently failed to provide ergonomic solutions to the very real problems type punning solves in a systems language.<p>Type punning is perfectly allowed in Rust, I&#x27;m not aware of any lints against it. Although you need to use an annotation to specify the struct layout algorithm to do it &quot;correctly&quot; for custom types.<p>We use it in BTreeMap to implement a kind of inheritance between nodes. Internal nodes have the same layout as Leaf nodes, except internal nodes have an extra field for their array of edges (which you don&#x27;t want to allocate for leaf nodes). So everything stores pointers to leaf nodes, and mostly manipulates all nodes as leaf nodes, but sometimes you &quot;down cast&quot; them to internal nodes to manipulate the edges.<p>In this particular case we use the standard C++ pattern of making a LeafNode the first field of an InternalNode.<p><a href="https:&#x2F;&#x2F;doc.rust-lang.org&#x2F;nightly&#x2F;src&#x2F;collections&#x2F;up&#x2F;src&#x2F;libcollections&#x2F;btree&#x2F;node.rs.html#57-115" rel="nofollow">https:&#x2F;&#x2F;doc.rust-lang.org&#x2F;nightly&#x2F;src&#x2F;collections&#x2F;up&#x2F;src&#x2F;lib...</a><p>The other common usage of punning in Rust is to gain access to some raw representation of a type. For instance, last time I worked on Rust, this was how fat pointers (&amp;[T], &amp;Trait) were constructed and decomposed at the lowest level.<p>I can&#x27;t speak to whether the usage of punning in this code is particularly good though.