From 62ec49c0d803e7748f0b2c1debd22d9de3722e83 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Wed, 10 Jan 2024 09:27:29 -0700 Subject: [PATCH] hybrid-array: add `FromIterator` impl (#1039) 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. --- hybrid-array/src/lib.rs | 19 +++++++++++++++++++ hybrid-array/tests/mod.rs | 20 +++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) 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(); +}