A safe way of creating and initializing huge arrays on the heap in Rust.

Home   »   A safe way of creating and initializing huge arrays on the heap in Rust.

#![feature(allocator_api)]
use core::alloc::Layout;
use std::alloc::Allocator;
use std::alloc::Global;

fn new_array(mut initializer: impl FnMut() -> T) -> Box<[T; N]> {
    // allocate the array with default allocator by using low level API
    let ptr: *mut T = Global
        .allocate(Layout::new::<[T; N]>())
        // panic on Out of Memory
        .unwrap()
        // cast [u8] to [T]
        .cast()
        // get the raw pointer
        .as_ptr();

    unsafe {
        // initialize the array with supplied function/closure
        for i in 0..N {
            ptr.offset(i as isize).write(initializer());
        }
        // now that everthing is initialized, convert the pointer into a box and return it
        Box::from_raw(ptr.cast())
    }
}

fn main() {
    const SIZE: usize = 10;
    let array_on_heap: Box<[usize; SIZE]> = new_array(
        // initialize the array with zeros
        || 0,
    );
    println!("{:?}", array_on_heap);
}

Leave a Reply

Your email address will not be published.