Repository: becheran/grid (language: rust)

Issue:
Support Hash
I think it would be nice to support Hash if the elements support Hash. I was trying to use `cached`, and couldn't cache on `Grid<T>` even if T was Hashable. I can try to make a PR.


Discussion / hints:

Fix patch:
diff --git a/src/lib.rs b/src/lib.rs
index 606eb6e..7d91b3d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -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;
@@ -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.
@@ -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;
 
@@ -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]];


Test patch: