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
This commit is contained in:
commit
7cdcc876a5
1 changed files with 18 additions and 0 deletions
|
|
@ -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`:
|
||||
///
|
||||
/// ```
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue