vec-option
A space optimized version of Vec<Option<T>>
that stores the discriminant seperately.
Feature flags
nightly
- This turns on a few optimizations (makes Clone
ing Copy
elements much cheaper) and extends try_fold
and try_for_each
to work with all Try
types. Finally, this also allows the iterator.nth_back(n)
methods to be used.
Pros
- Can have a smaller memory footprint compared to
Vec<Option<T>>
ifOption<T>
's space optimizations don't take effect - More cache-friendly if
Option<T>
's space optimizations don't take effect - Quickly set the entire collection to contain
None
- Fast extend with
None
Cons
- 2 allocations, instead of a single allocation
- Cannot remove elements from the middle of the vector
- Cannot work on the option's directly
Example
Just like a normal vector, you can push and pop elements from the end of the vector
let mut vec = new;
vec.push;
assert_eq!;
vec.push;
vec.push;
vec.push;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
You can get elements from the vector
let mut vec = from;
assert_eq!;
assert_eq!;
assert_eq!;
You can swap and replace elements
vec.swap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
or if vec.replace(index, None)
is too much, you can do
assert_eq!;
assert_eq!;
Of course, you can also truncate or clear the vector
let mut vec = from;
assert_eq!;
vec.truncate;
assert_eq!;
vec.clear;
assert!;
But due to the limitations imposed by spliting the representation of the vector, you can't really get a
&Option<T>
/&mut Option<T>
outside of a closure.
In fact, you can't get an &Option<T>
at all, it would be fairly useless, as the only thing you can really do with it is convert it to a Option<&T>
. But &mut Option<T>
is usefull, so there are a handful of functions that allow you to operate with them.
// This one allows you to edit a single value however you want, and the updates will
// be reflected once the closure returns. If the closure panics, then it is as if you took the
// option out of the vector.
vec.with_mut;
These functions below are like the corrosponding functions in Iterator
, they iterate over the vector and allow you to do stuff based on which one you call. The only difference is that you get to operate on &mut Option<T>
directly. Again, if the closure panics, it will be as if you took the value out of the vector.
vec.try_fold;
vec.fold;
vec.try_for_each;
vec.for_each;
But because of these limitations, you can very quickly fill up your vector with None
and set all of the elements in your vector to None
! This can compile down to just a memset
if your types don't have drop glue!
let mut vec = from;
assert_eq!;
vec.extend_none;
assert_eq!;
vec.set_all_none;
assert_eq!;