Skip to content

Commit

Permalink
Add example in the alternative in std::mem::transmute docs
Browse files Browse the repository at this point in the history
It is safer to use `from_ne_bytes` to convert raw bytes to type like u32.
  • Loading branch information
huangjiahua committed Apr 18, 2020
1 parent 4e4d49d commit 1a1863b
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/libcore/intrinsics.rs
Expand Up @@ -1100,6 +1100,24 @@ extern "rust-intrinsic" {
/// Below are common applications of `transmute` which can be replaced with safer
/// constructs.
///
/// Turning raw bytes(`&[u8]`) to `u32`, `f64`, etc.:
///
/// ```
/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
///
/// let num = unsafe {
/// std::mem::transmute::<[u8; 4], u32>(raw_bytes);
/// };
///
/// // use `u32::from_ne_bytes` instead
/// let num = u32::from_ne_bytes(raw_bytes);
/// // or use `u32::from_le_bytes` or `u32::from_ge_bytes` to specify the endianness
/// let num = u32::from_le_bytes(raw_bytes);
/// assert_eq!(num, 0x12345678);
/// let num = u32::from_be_bytes(raw_bytes);
/// assert_eq!(num, 0x78563412);
/// ```
///
/// Turning a pointer into a `usize`:
///
/// ```
Expand Down

0 comments on commit 1a1863b

Please sign in to comment.