Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hybrid-array: add FromIterator impl #1039

Merged
merged 1 commit into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,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"
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe these should both say "iterator should have exactly as many items as can fit in array"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it could be useful to know whether you have more than needed or not enough elements in iterator to fill array. The other expect message can be "not enough items in iterator to fill 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();
}