Skip to content

Commit

Permalink
hybrid-array: add FromIterator impl (#1039)
Browse files Browse the repository at this point in the history
For feature parity with `GenericArray`.

It would be nice to have a fallible version of this which returns an
error instead of panicking on length mismatch, but we'd first need to
add `FromFn::try_from_fn` or thereabouts.

This is enough to cover the immediate use cases in the meantime.
  • Loading branch information
tarcieri authored Jan 10, 2024
1 parent cdc6acd commit 62ec49c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
19 changes: 19 additions & 0 deletions hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,25 @@ where
}
}

impl<T, U> FromIterator<T> for Array<T, U>
where
U: ArraySize,
{
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut iter = iter.into_iter();
let ret = Self::from_fn(|_| {
iter.next()
.expect("iterator should have enough items to fill array")
});

assert!(
iter.next().is_none(),
"too many items in iterator to fit in array"
);
ret
}
}

impl<T, U> Hash for Array<T, U>
where
T: Hash,
Expand Down
20 changes: 19 additions & 1 deletion hybrid-array/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use hybrid_array::{Array, ArrayN};
use typenum::{U0, U2, U3, U4, U6, U7};
use typenum::{U0, U2, U3, U4, U5, U6, U7};

const EXAMPLE_SLICE: &[u8] = &[1, 2, 3, 4, 5, 6];

Expand Down Expand Up @@ -72,3 +72,21 @@ fn split_ref_mut() {
assert_eq!(prefix.as_slice(), &EXAMPLE_SLICE[..4]);
assert_eq!(suffix.as_slice(), &EXAMPLE_SLICE[4..]);
}

#[test]
fn from_iterator_correct_size() {
let array: Array<u8, U6> = EXAMPLE_SLICE.iter().copied().collect();
assert_eq!(array.as_slice(), EXAMPLE_SLICE);
}

#[test]
#[should_panic]
fn from_iterator_too_short() {
let _array: Array<u8, U7> = EXAMPLE_SLICE.iter().copied().collect();
}

#[test]
#[should_panic]
fn from_iterator_too_long() {
let _array: Array<u8, U5> = EXAMPLE_SLICE.iter().copied().collect();
}

0 comments on commit 62ec49c

Please sign in to comment.