about summary refs log tree commit diff
diff options
context:
space:
mode:
authorDylan DPC <dylan.dpc@gmail.com>2020-04-19 15:12:40 +0200
committerGitHub <noreply@github.com>2020-04-19 15:12:40 +0200
commit7cdcc876a5bc2b7a4bad094da395309da22760d6 (patch)
treeb26348bbcfa5233bd00f3168ef639ebf3cf1109c
parent9c370383806ae821b927a288e1164c8e2138f80a (diff)
parent1a1863b815d0db6aa1751e88e7044e9e2f02ac51 (diff)
downloadrust-7cdcc876a5bc2b7a4bad094da395309da22760d6.tar.gz
rust-7cdcc876a5bc2b7a4bad094da395309da22760d6.zip
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
-rw-r--r--src/libcore/intrinsics.rs18
1 files changed, 18 insertions, 0 deletions
diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs
index 4a11fb39389..75c73130891 100644
--- a/src/libcore/intrinsics.rs
+++ b/src/libcore/intrinsics.rs
@@ -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`:
     ///
     /// ```