Potentially partial-filled arrays.
This crate provides a central new data type, similar to an array: the
[PartialArray<N>
]. It is equivalent to an array, but the number of entries
might be anywhere from 0
to N
. While this has similarities to a Vec<T>
keep in mind, that a [PartialArray
] does not grow its memory: it always
takes up the memory for the fully array (with some additional counter) and
it cannot ever hold more than N
elements. This means that its memory is
fully static and on the stack, making it usable from #![no_std]
crates.
Usages
This new data type is most likely to be used for collecting iterators into arrays, when then length is not known, but has an upper bound, e.g.:
# use PartialArray;
/// Take the first 10 elements of an iterator, that match the condition.
///
/// This can return less than 10 elements if the iterator has fewer than 10
/// items or there are less than 10 matching elements.
Aside from this main usage, the [PartialArray
] can be used like a normal
array, i.e. it can be used as a slice, you can convert from
arrays and
try_from
slices. You can also iterate over the [PartialArray
]s by
value.
# use PartialArray;
let array = from;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
array.into_iter.map.for_each;
As [PartialArray
] implements [IntoIterator
], you can use it in a for
loop directly:
# use partial_array;
let array = partial_array!;
for item in array
This crate also provides a macro to make creating partial arrays easier:
# use partial_array;
let array = partial_array!;
Behavior on out-of-bounds accesses
This crate simply panics on an out-of-bound access, both if you using more
than N
items or if you use a non-initialized entry:
# use partial_array::PartialArray;
// partial array is only filled half, the last entry is uninitialized and
// therefore out of bounds:
let mut array: PartialArray<i32, 4> = (0..2).collect();
array[2] = 42; // panic!
# use partial_array::PartialArray;
// partial array has less space than the iterator has items:
let _array: PartialArray<i32, 4> = (0..42).collect(); // panic!