Guest User

Untitled

a guest
Oct 18th, 2019
79
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