Skip to content

Commit 62ec49c

Browse files
authored
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.
1 parent cdc6acd commit 62ec49c

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

hybrid-array/src/lib.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,25 @@ where
421421
}
422422
}
423423

424+
impl<T, U> FromIterator<T> for Array<T, U>
425+
where
426+
U: ArraySize,
427+
{
428+
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
429+
let mut iter = iter.into_iter();
430+
let ret = Self::from_fn(|_| {
431+
iter.next()
432+
.expect("iterator should have enough items to fill array")
433+
});
434+
435+
assert!(
436+
iter.next().is_none(),
437+
"too many items in iterator to fit in array"
438+
);
439+
ret
440+
}
441+
}
442+
424443
impl<T, U> Hash for Array<T, U>
425444
where
426445
T: Hash,

hybrid-array/tests/mod.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use hybrid_array::{Array, ArrayN};
2-
use typenum::{U0, U2, U3, U4, U6, U7};
2+
use typenum::{U0, U2, U3, U4, U5, U6, U7};
33

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

@@ -72,3 +72,21 @@ fn split_ref_mut() {
7272
assert_eq!(prefix.as_slice(), &EXAMPLE_SLICE[..4]);
7373
assert_eq!(suffix.as_slice(), &EXAMPLE_SLICE[4..]);
7474
}
75+
76+
#[test]
77+
fn from_iterator_correct_size() {
78+
let array: Array<u8, U6> = EXAMPLE_SLICE.iter().copied().collect();
79+
assert_eq!(array.as_slice(), EXAMPLE_SLICE);
80+
}
81+
82+
#[test]
83+
#[should_panic]
84+
fn from_iterator_too_short() {
85+
let _array: Array<u8, U7> = EXAMPLE_SLICE.iter().copied().collect();
86+
}
87+
88+
#[test]
89+
#[should_panic]
90+
fn from_iterator_too_long() {
91+
let _array: Array<u8, U5> = EXAMPLE_SLICE.iter().copied().collect();
92+
}

0 commit comments

Comments
 (0)