Is there an equivalent of alloca to create variable length arrays in Rust?
I\'m looking for the equivalent of the following C99 code:
It is not possible directly, as in there is not direct syntax in the language supporting it.
That being said, this particular feature of C99 is debatable, it has certain advantages (cache locality & bypassing malloc) but it also has disadvantages (easy to blow-up the stack, stumps a number of optimizations, may turn static offsets into dynamic offsets, ...).
For now, I would advise you to use Vec instead. If you have performance issues, then you may look into the so-called "Small Vector Optimization". I have regularly seen the following pattern in C code where performance is required:
SomeType array[64] = {};
SomeType* pointer, *dynamic_pointer;
if (n <= 64) {
pointer = array;
} else {
pointer = dynamic_pointer = malloc(sizeof(SomeType) * n);
}
// ...
if (dynamic_pointer) { free(dynamic_pointer); }
Now, this is something that Rust supports easily (and better, in a way):
enum InlineVector {
Inline(usize, [T; 64]),
Dynamic(Vec),
}
You can see an example simplistic implementation below.
What matters, however, is that you now have a type which:
Of course, it also always reserves enough space for 64 elements on the stack even if you only use 2; however in exchange there is no call to alloca so you avoid the issue of having dynamic offsets to your variants.
And contrary to C, you still benefit from lifetime tracking so that you cannot accidentally return a reference to your stack-allocated array outside the function.
Note: a full-blown implementation would require non-type parameters so that you could customize the 64... but Rust is not there yet.
I will show off the most "obvious" methods:
enum InlineVector {
Inline(usize, [T; 64]),
Dynamic(Vec),
}
impl InlineVector {
fn new(v: T, n: usize) -> InlineVector {
if n <= 64 {
InlineVector::Inline(n, [v; 64])
} else {
InlineVector::Dynamic(vec![v; n])
}
}
}
impl InlineVector {
fn len(&self) -> usize {
match self {
InlineVector::Inline(n, _) => *n,
InlineVector::Dynamic(vec) => vec.len(),
}
}
fn as_slice(&self) -> &[T] {
match self {
InlineVector::Inline(_, array) => array,
InlineVector::Dynamic(vec) => vec,
}
}
fn as_mut_slice(&mut self) -> &mut [T] {
match self {
InlineVector::Inline(_, array) => array,
InlineVector::Dynamic(vec) => vec,
}
}
}
use std::ops::{Deref, DerefMut};
impl Deref for InlineVector {
type Target = [T];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl DerefMut for InlineVector {
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_mut_slice()
}
}
Usage:
fn main() {
let mut v = InlineVector::new(1u32, 4);
v[2] = 3;
println!("{}: {}", v.len(), v[2])
}
Which prints 4: 3 as expected.