Description
Something like [T, .. n]
but with a length
field (and the correct destructor), so it's valid to store anywhere from 0 upto n
T
s in it. This can have T
s dynamically pushed and popped, but attempting to push more than n
would be an error. I.e.
let mut x = FourBoundedArray::new(); // n == 4
println!("{}", x); // []
x.push(1);
println!("{}", x); // [1]
x.push(2);
x.push(3);
x.push(4);
println!("{}", x); // [1, 2, 3, 4]
x.pop();
println!("{}", x); // [1, 2, 3]
x.push(5);
x.push(6); // error
(The error could either be fail!
or a Result<(), ...>
return value.)
This is useful for data structures like 2-4-trees, B-trees etc., where they have internal nodes that store a sequence of keys with variable, but bounded, length. At the moment the only safe way to encode this is either a heap allocation (Vec
) or with [Option<T>, .. n]
where the "length" is modeled by storing [Some(x_1), Some(x_2), ..., Some(x_length), None, ..., None]
(this leads to a lot of unwrap
and unnecessary branches).
rust-lang/rfcs#197 is related, to make the destructors work right. For full generality we would need integer type params, but we can certainly have an internal abstraction of this form in collections
(for use in btree etc.) with the lengths required hard-coded, and generalise/publish it later.