Skip to content

Commit

Permalink
hybrid-array: use handwritten instead of derived impls (#940)
Browse files Browse the repository at this point in the history
Uses handwritten impls for the following traits on the `Array` type:

- Debug
- Eq
- Hash
- PartialEq
- PartialOrd
- Ord

The handwritten impls have looser bounds.
  • Loading branch information
tarcieri authored Sep 4, 2023
1 parent 0726442 commit 8df5747
Showing 1 changed file with 62 additions and 1 deletion.
63 changes: 62 additions & 1 deletion hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ pub use typenum::consts;
use core::{
array::{IntoIter, TryFromSliceError},
borrow::{Borrow, BorrowMut},
cmp::Ordering,
fmt::{self, Debug},
hash::{Hash, Hasher},
ops::{Deref, DerefMut, Index, IndexMut, Range},
slice::{Iter, IterMut},
};
Expand All @@ -38,7 +41,6 @@ use typenum::Unsigned;
///
/// Provides the flexibility of typenum-based expressions while also
/// allowing interoperability and a transition path to const generics.
#[derive(Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Array<T, U: ArraySize>(pub U::ArrayType<T>);

Expand Down Expand Up @@ -188,6 +190,17 @@ where
{
}

impl<T, U> Debug for Array<T, U>
where
T: Debug,
U: ArraySize,
U::ArrayType<T>: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Array").field(&self.0).finish()
}
}

impl<T, U> Default for Array<T, U>
where
T: Default,
Expand Down Expand Up @@ -220,6 +233,13 @@ where
}
}

impl<T, U> Eq for Array<T, U>
where
T: Eq,
U: ArraySize,
{
}

impl<T, U, const N: usize> From<[T; N]> for Array<T, U>
where
Self: ArrayOps<T, N>,
Expand Down Expand Up @@ -253,6 +273,17 @@ where
}
}

impl<T, U> Hash for Array<T, U>
where
T: Hash,
U: ArraySize,
{
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.as_ref().hash(state);
}
}

impl<T, I, U> Index<I> for Array<T, U>
where
[T]: Index<I>,
Expand All @@ -277,6 +308,36 @@ where
}
}

impl<T, U> PartialEq for Array<T, U>
where
T: PartialEq,
U: ArraySize,
{
fn eq(&self, other: &Self) -> bool {
self.0.as_ref().eq(other.0.as_ref())
}
}

impl<T, U> PartialOrd for Array<T, U>
where
T: PartialOrd,
U: ArraySize,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.0.as_ref().partial_cmp(other.0.as_ref())
}
}

impl<T, U> Ord for Array<T, U>
where
T: Ord,
U: ArraySize,
{
fn cmp(&self, other: &Self) -> Ordering {
self.0.as_ref().cmp(other.0.as_ref())
}
}

impl<'a, T, U> TryFrom<&'a [T]> for Array<T, U>
where
T: Copy,
Expand Down

0 comments on commit 8df5747

Please sign in to comment.