]> git.proxmox.com Git - rustc.git/blob - src/doc/nomicon/src/transmutes.md
New upstream version 1.17.0+dfsg1
[rustc.git] / src / doc / nomicon / src / transmutes.md
1 # Transmutes
2
3 Get out of our way type system! We're going to reinterpret these bits or die
4 trying! Even though this book is all about doing things that are unsafe, I
5 really can't emphasize that you should deeply think about finding Another Way
6 than the operations covered in this section. This is really, truly, the most
7 horribly unsafe thing you can do in Rust. The railguards here are dental floss.
8
9 `mem::transmute<T, U>` takes a value of type `T` and reinterprets it to have
10 type `U`. The only restriction is that the `T` and `U` are verified to have the
11 same size. The ways to cause Undefined Behavior with this are mind boggling.
12
13 * First and foremost, creating an instance of *any* type with an invalid state
14 is going to cause arbitrary chaos that can't really be predicted.
15 * Transmute has an overloaded return type. If you do not specify the return type
16 it may produce a surprising type to satisfy inference.
17 * Making a primitive with an invalid value is UB
18 * Transmuting between non-repr(C) types is UB
19 * Transmuting an & to &mut is UB
20 * Transmuting an & to &mut is *always* UB
21 * No you can't do it
22 * No you're not special
23 * Transmuting to a reference without an explicitly provided lifetime
24 produces an [unbounded lifetime]
25
26 `mem::transmute_copy<T, U>` somehow manages to be *even more* wildly unsafe than
27 this. It copies `size_of<U>` bytes out of an `&T` and interprets them as a `U`.
28 The size check that `mem::transmute` has is gone (as it may be valid to copy
29 out a prefix), though it is Undefined Behavior for `U` to be larger than `T`.
30
31 Also of course you can get most of the functionality of these functions using
32 pointer casts.
33
34
35 [unbounded lifetime]: unbounded-lifetimes.html