Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::boxed::Box;
- use std::mem;
- unsafe fn alloc<T>(count: usize) -> Box<[T]> {
- let mut allocated = Vec::with_capacity(count);
- allocated.set_len(count); // If you don't do this, the vec will be trimmed.
- allocated.into_boxed_slice()
- }
- fn main() {
- println!("{}", unsafe {
- const REGION_SIZE: usize = 4;
- let mut region: Box<[u8]> = alloc(REGION_SIZE);
- *(region.as_mut_ptr() as *mut u32) = 0x73746974;
- let string = String::from_raw_parts(
- region.as_mut_ptr(),
- REGION_SIZE,
- REGION_SIZE,
- );
- mem::forget(region); // `String::from_raw_parts` took ownership
- string
- });
- }
Add Comment
Please, Sign In to add comment