diff --git a/hybrid-array/src/lib.rs b/hybrid-array/src/lib.rs index ae14a80f..4eeb183c 100644 --- a/hybrid-array/src/lib.rs +++ b/hybrid-array/src/lib.rs @@ -421,6 +421,25 @@ where } } +impl FromIterator for Array +where + U: ArraySize, +{ + fn from_iter>(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 Hash for Array where T: Hash, diff --git a/hybrid-array/tests/mod.rs b/hybrid-array/tests/mod.rs index c4b86196..90949ee4 100644 --- a/hybrid-array/tests/mod.rs +++ b/hybrid-array/tests/mod.rs @@ -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]; @@ -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 = EXAMPLE_SLICE.iter().copied().collect(); + assert_eq!(array.as_slice(), EXAMPLE_SLICE); +} + +#[test] +#[should_panic] +fn from_iterator_too_short() { + let _array: Array = EXAMPLE_SLICE.iter().copied().collect(); +} + +#[test] +#[should_panic] +fn from_iterator_too_long() { + let _array: Array = EXAMPLE_SLICE.iter().copied().collect(); +}