Guest User

Untitled

a guest
May 24th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. use std::boxed::Box;
  2. use std::mem;
  3.  
  4. unsafe fn alloc<T>(count: usize) -> Box<[T]> {
  5. let mut allocated = Vec::with_capacity(count);
  6. allocated.set_len(count); // If you don't do this, the vec will be trimmed.
  7. allocated.into_boxed_slice()
  8. }
  9.  
  10. fn main() {
  11. println!("{}", unsafe {
  12. const REGION_SIZE: usize = 4;
  13. let mut region: Box<[u8]> = alloc(REGION_SIZE);
  14. *(region.as_mut_ptr() as *mut u32) = 0x73746974;
  15. let string = String::from_raw_parts(
  16. region.as_mut_ptr(),
  17. REGION_SIZE,
  18. REGION_SIZE,
  19. );
  20. mem::forget(region); // `String::from_raw_parts` took ownership
  21. string
  22. });
  23. }
Add Comment
Please, Sign In to add comment