raw_box

Function raw_box 

Source
pub unsafe fn raw_box<T>() -> Box<T>
Expand description

Create a box structure without moving the wrapped value from the stack to the heap. This API is most useful when the wrapped value is too large for the default stack size, such that initializing and packing the valuing into the box is a pain.

Note that calling the API is unsafe, because it only creates a well-aligned memory structure in the heap, but all fields are in the state of undefined behavior at the moment. You must initialize the fields with default values, or pack it with meaningful placeholders. Using the object directly after being created by the API is extremely dangerous and will almost certainly lead to undefined behaviors.

ยงExamples

Create a boxed BigStruct

use syncpool::raw_box;

struct BigStruct {
    a: u32,
    b: u32,
    c: [u8; 0x1_000_000],
}

// create the object on the heap directly
let mut big: Box<BigStruct> = unsafe { raw_box::<BigStruct>() };

// initialize the fields
big.a = 0;
big.b = 42;
big.c = [0u8; 0x1_000_000];

// the fields are now valid
assert_eq!(big.c.len(), 0x1_000_000);
assert_eq!(big.c[4200], 0);
assert_eq!(big.a, 0);