Skip to content

Commit

Permalink
hybrid-array: impl IntoIterator for all ArraySizes (#956)
Browse files Browse the repository at this point in the history
Uses an `IntoIterator` bound on `ArraySize::ArrayType` and forwards the
trait invocation to the inner array.
  • Loading branch information
tarcieri authored Oct 8, 2023
1 parent c19c5cc commit 71ec948
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub use typenum;
pub use typenum::consts;

use core::{
array::{IntoIter, TryFromSliceError},
array::TryFromSliceError,
borrow::{Borrow, BorrowMut},
cmp::Ordering,
fmt::{self, Debug},
Expand Down Expand Up @@ -307,6 +307,21 @@ where
}
}

impl<T, U> IntoIterator for Array<T, U>
where
U: ArraySize,
{
type Item = T;
type IntoIter = <U::ArrayType<T> as IntoIterator>::IntoIter;

/// Creates a consuming iterator, that is, one that moves each value out of
/// the array (from start to end). The array cannot be used after calling
/// this unless `T` implements `Copy`, so the whole array is copied.
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}

impl<T, U> PartialEq for Array<T, U>
where
T: PartialEq,
Expand Down Expand Up @@ -495,9 +510,9 @@ impl<T, const N: usize> ArrayExt<T> for [T; N] {
///
/// NOTE: do not implement this trait yourself. It is implemented for types in
/// [`typenum::consts`].
pub unsafe trait ArraySize: Unsigned {
pub unsafe trait ArraySize: Unsigned + 'static {
/// Array type which corresponds to this size.
type ArrayType<T>: ArrayExt<T> + AsRef<[T]> + AsMut<[T]> + IntoArray<T>;
type ArrayType<T>: ArrayExt<T> + AsRef<[T]> + AsMut<[T]> + IntoArray<T> + IntoIterator<Item = T>;
}

/// Convert the given type into an [`Array`].
Expand Down Expand Up @@ -570,18 +585,6 @@ macro_rules! impl_array_size {
}
}

impl<T> IntoIterator for Array<T, typenum::$ty> {
type Item = T;
type IntoIter = IntoIter<T, $len>;

/// Creates a consuming iterator, that is, one that moves each value out of
/// the array (from start to end). The array cannot be used after calling
/// this unless `T` implements `Copy`, so the whole array is copied.
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}

impl<'a, T> IntoIterator for &'a Array<T, typenum::$ty> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
Expand Down

0 comments on commit 71ec948

Please sign in to comment.