Skip to content

Commit

Permalink
feat: accept &(usize, usize) as Matrix index
Browse files Browse the repository at this point in the history
This comes in addition to `(usize, usize)`.
  • Loading branch information
samueltardieu committed Dec 29, 2024
1 parent 0f5bdd3 commit e2fb157
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -787,13 +787,28 @@ impl<C> Index<(usize, usize)> for Matrix<C> {
}
}

impl<C> Index<&(usize, usize)> for Matrix<C> {
type Output = C;

#[must_use]
fn index(&self, index: &(usize, usize)) -> &C {
&self[*index]
}
}

impl<C> IndexMut<(usize, usize)> for Matrix<C> {
fn index_mut(&mut self, index: (usize, usize)) -> &mut C {
let i = self.idx(index);
&mut self.data[i]
}
}

impl<C> IndexMut<&(usize, usize)> for Matrix<C> {
fn index_mut(&mut self, index: &(usize, usize)) -> &mut C {
&mut self[*index]
}
}

impl<C> Deref for Matrix<C> {
type Target = [C];

Expand Down
19 changes: 19 additions & 0 deletions tests/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit e2fb157

Please sign in to comment.