Q1,
You could create a Vec<T> and then turn it into a Box<[T]>. I don’t see another way to create a dynamic Box<[T]> with safe code.
pub fn make_arr(len: usize) -> Box<[i32]> {
use std::iter::repeat;
repeat(0).take(len).collect::<Vec<i32>>().into_boxed_slice()
}
The code above is pretty slow with the current rustc though. With unsafe code it is 9× faster:
pub fn make_arr_unsafe(len: usize) -> Box<[i32]> {
use std::rt::heap::allocate;
use std::mem::{min_align_of, transmute};
use std::ptr::set_memory;
use std::raw::Slice;
use std::i32;
let size = len * i32::BYTES;
unsafe {
let mem = allocate(size, min_align_of::<i32>());
set_memory(mem, 0, size);
let slice = Slice { data: mem as *const i32, len: len };
transmute(slice)
}
}