diff --git a/src/matrix.rs b/src/matrix.rs index 6df6aa64..deaef393 100644 --- a/src/matrix.rs +++ b/src/matrix.rs @@ -787,6 +787,15 @@ impl Index<(usize, usize)> for Matrix { } } +impl Index<&(usize, usize)> for Matrix { + type Output = C; + + #[must_use] + fn index(&self, index: &(usize, usize)) -> &C { + &self[*index] + } +} + impl IndexMut<(usize, usize)> for Matrix { fn index_mut(&mut self, index: (usize, usize)) -> &mut C { let i = self.idx(index); @@ -794,6 +803,12 @@ impl IndexMut<(usize, usize)> for Matrix { } } +impl IndexMut<&(usize, usize)> for Matrix { + fn index_mut(&mut self, index: &(usize, usize)) -> &mut C { + &mut self[*index] + } +} + impl Deref for Matrix { type Target = [C]; diff --git a/tests/matrix.rs b/tests/matrix.rs index 6ba06e83..0fb71e03 100644 --- a/tests/matrix.rs +++ b/tests/matrix.rs @@ -24,6 +24,25 @@ fn sm() { assert_eq!(m[(1, 1)], 33); } +#[test] +fn index_as_ref() { + let mut m = Matrix::new(2, 2, 0usize); + m[&(0, 0)] = 0; + m[&(0, 1)] = 1; + m[&(1, 0)] = 10; + m[&(1, 1)] = 11; + m[&(0, 1)] = 2; + assert_eq!(m[&(0, 0)], 0); + assert_eq!(m[&(0, 1)], 2); + assert_eq!(m[&(1, 0)], 10); + assert_eq!(m[&(1, 1)], 11); + m.fill(33); + assert_eq!(m[&(0, 0)], 33); + assert_eq!(m[&(0, 1)], 33); + assert_eq!(m[&(1, 0)], 33); + assert_eq!(m[&(1, 1)], 33); +} + #[test] fn from_fn() { let m = Matrix::from_fn(2, 3, |(row, column)| 10 * row + column);