Skip to content

Instantly share code, notes, and snippets.

@EkremDincel
Created May 4, 2021 23:10
Show Gist options
  • Save EkremDincel/1e6c08d68cd060bc59164135aac96ff0 to your computer and use it in GitHub Desktop.
Save EkremDincel/1e6c08d68cd060bc59164135aac96ff0 to your computer and use it in GitHub Desktop.
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<T, const N: usize>(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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment