SHARE
TWEET

Untitled

a guest Oct 18th, 2019 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #![allow(unused)]
  2. fn main() {
  3. use std::mem::{self, MaybeUninit};
  4. use std::ptr;
  5.  
  6. let data = {
  7.     // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
  8.     // safe because the type we are claiming to have initialized here is a
  9.     // bunch of `MaybeUninit`s, which do not require initialization.
  10.     let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
  11.         MaybeUninit::uninit().assume_init()
  12.     };
  13.  
  14.     // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
  15.     // we have a memory leak, but there is no memory safety issue.
  16.     for elem in &mut data[..] {
  17.         unsafe { ptr::write(elem.as_mut_ptr(), vec![42]); }
  18.     }
  19.  
  20.     // Everything is initialized. Transmute the array to the
  21.     // initialized type.
  22.     unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
  23. };
  24.  
  25. assert_eq!(&data[0], &[42]);
  26. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top