about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorubsan <npmazzuca@gmail.com>2016-07-02 08:45:01 -0700
committerubsan <npmazzuca@gmail.com>2016-07-02 08:45:01 -0700
commit377bbfe96b9d5f20ca6aec84f68ad8161f307ab5 (patch)
treed22d842cc48ee9a5849518985e5d6535e193393d /src/libcore
parent2413b52b886bc9ba4db6c5bc5eb0712c6e4f554a (diff)
downloadrust-377bbfe96b9d5f20ca6aec84f68ad8161f307ab5.tar.gz
rust-377bbfe96b9d5f20ca6aec84f68ad8161f307ab5.zip
Add a new alternative
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/intrinsics.rs23
1 files changed, 23 insertions, 0 deletions
diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs
index d2bf9d94399..5bd35ae1ac2 100644
--- a/src/libcore/intrinsics.rs
+++ b/src/libcore/intrinsics.rs
@@ -346,6 +346,29 @@ extern "rust-intrinsic" {
     /// assert_eq!(b"Rust", [82, 117, 116, 116]);
     ///
     ///
+    /// // Turning a Vec<&T> into a Vec<Option<&T>>
+    /// let store = [0, 1, 2, 3];
+    /// let v_orig = store.iter().collect::<Vec<&i32>>();
+    /// // Using transmute; Undefined Behavior
+    /// let v_transmuted = mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(
+    ///     v_orig);
+    /// // The suggested, safe way
+    /// let v_collected = v_orig.into_iter()
+    ///                         .map(|r| Some(r))
+    ///                         .collect::<Vec<Option<&i32>>>();
+    /// // The no-copy, unsafe way, still using transmute, but not UB
+    /// let v_no_copy = Vec::from_raw_parts(v_orig.as_mut_ptr(),
+    ///                                     v_orig.len(),
+    ///                                     v_orig.capacity());
+    /// mem::forget(v_orig);
+    /// // This is equivalent to the original, but safer, and reuses the same
+    /// // Vec internals. Therefore the new inner type must have the exact same
+    /// // size, and the same or lesser alignment, as the old type.
+    /// // The same caveats exist for this method as transmute, for the original
+    /// // inner type (`&i32`) to the converted inner type (`Option<&i32>`), so
+    /// // read the nomicon page linked above.
+    ///
+    ///
     /// // Copying an `&mut T` to reslice:
     /// fn split_at_mut_transmute<T>(slice: &mut [T], index: usize)
     ///                              -> (&mut [T], &mut [T]) {