You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/casts.md
+5-41Lines changed: 5 additions & 41 deletions
Original file line number
Diff line number
Diff line change
@@ -19,47 +19,11 @@ very easily lead to terrible things. However the act of creating the pointer
19
19
itself is safe, because actually using a raw pointer is already marked as
20
20
`unsafe`.
21
21
22
-
Here's an exhaustive list of all the true casts. For brevity, we will use `*`
23
-
to denote either a `*const` or `*mut`, and `integer` to denote any integral
24
-
primitive:
22
+
Note that lengths are not adjusted when casting raw slices; `*const [u16] as *const [u8]` creates a slice that only includes half of the original memory.
25
23
26
-
*`*T as *U` where `T, U: Sized`
27
-
*`*T as *U` TODO: explain unsized situation
28
-
*`*T as integer`
29
-
*`integer as *T`
30
-
*`number as number`
31
-
*`field-less enum as integer`
32
-
*`bool as integer`
33
-
*`char as integer`
34
-
*`u8 as char`
35
-
*`&[T; n] as *const T`
36
-
*`fn as *T` where `T: Sized`
37
-
*`fn as integer`
24
+
Casting is not transitive, that is, even if `e as U1 as U2` is a valid expression, `e as U2` is not necessarily so.
38
25
39
-
Note that lengths are not adjusted when casting raw slices -
40
-
`*const [u16] as *const [u8]` creates a slice that only includes
41
-
half of the original memory.
26
+
You can find an exhaustive list of [all the true casts][cast list] and [casting semantics][semantics list] on the reference.
42
27
43
-
Casting is not transitive, that is, even if `e as U1 as U2` is a valid
44
-
expression, `e as U2` is not necessarily so.
45
-
46
-
For numeric casts, there are quite a few cases to consider:
47
-
48
-
* casting between two integers of the same size (e.g. i32 -> u32) is a no-op
49
-
(Rust uses 2's complement for negative values of fixed integers)
50
-
* casting from a larger integer to a smaller integer (e.g. u32 -> u8) will
51
-
truncate
52
-
* casting from a smaller integer to a larger integer (e.g. u8 -> u32) will
53
-
* zero-extend if the source is unsigned
54
-
* sign-extend if the source is signed
55
-
* casting from a float to an integer will round the float towards zero and
56
-
produces a "saturating cast" when the float is outside the integer's range
57
-
* floats that are too big turn into the largest possible integer
58
-
* floats that are too small produce the smallest possible integer
59
-
* NaN produces zero
60
-
* casting from an integer to float will produce the floating point
61
-
representation of the integer, rounded if necessary (rounding to
62
-
nearest, ties to even)
63
-
* casting from an f32 to an f64 is perfect and lossless
64
-
* casting from an f64 to an f32 will produce the closest possible value
0 commit comments