Skip to content

Commit

Permalink
Implement Index(Mut) using macro to reduce duplication
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev committed Jan 31, 2024
1 parent 0b89c70 commit 166fe3e
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,29 +169,32 @@ impl<T: Clone, LenT: ValidLength> Clone for FixedArray<T, LenT> {
}
}

impl<T, LenT: ValidLength> core::ops::Index<usize> for FixedArray<T, LenT> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
&self.as_slice()[index]
}
}
macro_rules! impl_index_with {
($(fn index_with($index:ident: $T:ty) -> usize {$body:expr})*) => {
$(
impl<T, LenT: ValidLength> core::ops::Index<$T> for FixedArray<T, LenT> {
type Output = T;
fn index(&self, $index: $T) -> &Self::Output {
&self.as_slice()[$body]
}
}

impl<T, LenT: ValidLength> core::ops::IndexMut<usize> for FixedArray<T, LenT> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.as_slice_mut()[index]
}
impl<T, LenT: ValidLength> core::ops::IndexMut<$T> for FixedArray<T, LenT> {
fn index_mut(&mut self, $index: $T) -> &mut Self::Output {
&mut self.as_slice_mut()[$body]
}
}
)*
};
}

impl<T, LenT: ValidLength> core::ops::Index<LenT> for FixedArray<T, LenT> {
type Output = T;
fn index(&self, index: LenT) -> &Self::Output {
&self.as_slice()[index.to_usize()]
impl_index_with! {
fn index_with(index: usize) -> usize {
index
}
}

impl<T, LenT: ValidLength> core::ops::IndexMut<LenT> for FixedArray<T, LenT> {
fn index_mut(&mut self, index: LenT) -> &mut Self::Output {
&mut self.as_slice_mut()[index.to_usize()]
fn index_with(index: LenT) -> usize {
index.to_usize()
}
}

Expand Down

0 comments on commit 166fe3e

Please sign in to comment.