Runtime sized array on heap - different questions


#1

I have fixed size array x: [T; N]. I want to save part of it in heap allocated memory. And after that (in another code point) I want to copy count items from some such heap allocated array to fixed size stack allocated array. What is the best way / types to do it?

Currently I use &x[0..items].to_vec().into_boxed_slice() for first task (give me Box<[T]>) and don’t know how to do second task. And also Vec<T> usage (even temporary) looks redundant because I don’t need resizable container just fixed size heap allocated array (but size is determined in runtime).


#2

The Vec isn’t really redundant, creating a Box<[T]> just entails creating an equivalent Vec<T> first. The final Vec -> Box conversion is free.


#3

Anyway, how can I copy count first items from b: Box<[T]> to x: [T; N]. Of course, I can do it with loop but I want most effective implementation like memcpy (it’s assumed that T is copyable)


#4

You’d have to initialize the [T; N] first, then use .copy_from_slice(). The initialization of the array should hopefully be removed since it’s immediately overwritten.