]> git.lizzy.rs Git - rust.git/commitdiff
Implement StableHash for BitSet and BitMatrix via Hash
authorTomasz Miąsko <tomasz.miasko@gmail.com>
Sat, 18 Dec 2021 00:00:00 +0000 (00:00 +0000)
committerTomasz Miąsko <tomasz.miasko@gmail.com>
Sat, 18 Dec 2021 00:00:00 +0000 (00:00 +0000)
This fixes an issue where bit sets / bit matrices the same word
content but a different domain size would receive the same hash.

compiler/rustc_data_structures/src/stable_hasher.rs
compiler/rustc_data_structures/src/stable_hasher/tests.rs

index b8ad66901c6991fce35ebb861778a5143ef02801..b8e6497d5731b6445c64a488a75cebf43993d8b1 100644 (file)
@@ -476,14 +476,14 @@ fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
 }
 
 impl<I: vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I> {
-    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
-        self.words().hash_stable(ctx, hasher);
+    fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
+        ::std::hash::Hash::hash(self, hasher);
     }
 }
 
 impl<R: vec::Idx, C: vec::Idx, CTX> HashStable<CTX> for bit_set::BitMatrix<R, C> {
-    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
-        self.words().hash_stable(ctx, hasher);
+    fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
+        ::std::hash::Hash::hash(self, hasher);
     }
 }
 
index cd6ff96a555f4785a4b47f53f4dff2fc20fd414c..391db67d29dbb282e2333336806b2c5ca632345b 100644 (file)
@@ -71,3 +71,30 @@ fn test_hash_isize() {
 
     assert_eq!(h.finalize(), expected);
 }
+
+fn hash<T: HashStable<()>>(t: &T) -> u128 {
+    let mut h = StableHasher::new();
+    let ctx = &mut ();
+    t.hash_stable(ctx, &mut h);
+    h.finish()
+}
+
+// Check that bit set hash includes the domain size.
+#[test]
+fn test_hash_bit_set() {
+    use rustc_index::bit_set::BitSet;
+    let a: BitSet<usize> = BitSet::new_empty(1);
+    let b: BitSet<usize> = BitSet::new_empty(2);
+    assert_ne!(a, b);
+    assert_ne!(hash(&a), hash(&b));
+}
+
+// Check that bit matrix hash includes the matrix dimensions.
+#[test]
+fn test_hash_bit_matrix() {
+    use rustc_index::bit_set::BitMatrix;
+    let a: BitMatrix<usize, usize> = BitMatrix::new(1, 1);
+    let b: BitMatrix<usize, usize> = BitMatrix::new(1, 2);
+    assert_ne!(a, b);
+    assert_ne!(hash(&a), hash(&b));
+}