Skip to content

Commit 7cdcc87

Browse files
authored
Rollup merge of #71315 - huangjiahua:update-documentation, r=Dylan-DPC
Add example in the alternative in std::mem::transmute docs It is safer to use `from_ne_bytes` to convert raw bytes to type like u32. #71187
2 parents 9c37038 + 1a1863b commit 7cdcc87

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/libcore/intrinsics.rs

+18
Original file line numberDiff line numberDiff line change
@@ -1100,6 +1100,24 @@ extern "rust-intrinsic" {
11001100
/// Below are common applications of `transmute` which can be replaced with safer
11011101
/// constructs.
11021102
///
1103+
/// Turning raw bytes(`&[u8]`) to `u32`, `f64`, etc.:
1104+
///
1105+
/// ```
1106+
/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
1107+
///
1108+
/// let num = unsafe {
1109+
/// std::mem::transmute::<[u8; 4], u32>(raw_bytes);
1110+
/// };
1111+
///
1112+
/// // use `u32::from_ne_bytes` instead
1113+
/// let num = u32::from_ne_bytes(raw_bytes);
1114+
/// // or use `u32::from_le_bytes` or `u32::from_ge_bytes` to specify the endianness
1115+
/// let num = u32::from_le_bytes(raw_bytes);
1116+
/// assert_eq!(num, 0x12345678);
1117+
/// let num = u32::from_be_bytes(raw_bytes);
1118+
/// assert_eq!(num, 0x78563412);
1119+
/// ```
1120+
///
11031121
/// Turning a pointer into a `usize`:
11041122
///
11051123
/// ```

0 commit comments

Comments
 (0)