Crate partial_array[][src]

Expand description

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.


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.:

/// 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.
fn first_10_matching<T, I, F>(iter: I, check: F) -> PartialArray<T, 10>
    where I: IntoIterator<Item = T>,
          F: FnMut(&T) -> bool,

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 PartialArrays by value.

let array = PartialArray::from([42_u16; 4]);
assert_eq!(array.len(), 4);
assert_eq!(array[0], 42);
assert_eq!(array[3], 42);
assert_eq!(array[2..].len(), 2);
array.into_iter().map(|x| x + 4).for_each(|x| println!("{}", x));

As PartialArray implements IntoIterator, you can use it in a for loop directly:

let array = partial_array![42_u16; 4];
for item in array {
    println!("{}", item);

This crate also provides a macro to make creating partial arrays easier:

let array = partial_array![42, -13, 2];

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:

// 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!
// partial array has less space than the iterator has items:
let _array: PartialArray<i32, 4> = (0..42).collect(); // panic!


Types for external iteration.


Create a partial array from a given set of values (similar to vec![]).


A potentially partially filled array.