Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make Grid hashable if T is hashable #44

Merged
merged 2 commits into from
Dec 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ use serde::{
use core::cmp;
use core::cmp::Eq;
use core::fmt;
use core::hash;
use core::iter::StepBy;
use core::ops::Index;
use core::ops::IndexMut;
Expand Down Expand Up @@ -184,7 +185,7 @@ macro_rules! grid_cm {
}

/// Define the internal memory layout of the grid.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Order {
/// The data is ordered row by row.
Expand Down Expand Up @@ -1425,6 +1426,16 @@ impl<T: Clone> Clone for Grid<T> {
}
}

impl<T: hash::Hash> hash::Hash for Grid<T> {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.rows.hash(state);
self.cols.hash(state);
self.order.hash(state);
self.data.hash(state);
}
}

impl<T> Index<(usize, usize)> for Grid<T> {
type Output = T;

Expand Down Expand Up @@ -2509,6 +2520,16 @@ mod test {
test_grid(&clone, 2, 3, Order::RowMajor, &[1, 2, 10, 4, 5, 6]);
}

#[cfg(feature = "std")]
#[test]
fn hash_std() {
let mut set = std::collections::HashSet::new();
set.insert(grid![[1,2,3][4,5,6]]);
set.insert(grid![[1,3,3][4,5,6]]);
set.insert(grid![[1,2,3][4,5,6]]);
assert_eq!(set.len(), 2);
}

#[test]
fn macro_init() {
let grid = grid![[1, 2, 3][4, 5, 6]];
Expand Down