Skip to content

Commit

Permalink
Rollup merge of #93193 - Kobzol:stable-hash-permutation-test, r=the8472
Browse files Browse the repository at this point in the history
Add test for stable hash uniqueness of adjacent field values

This PR adds a simple test to check that stable hash will produce a different hash if the order of two values that have the same combined bit pattern changes.

r? `@the8472`
  • Loading branch information
matthiaskrgr authored Jan 27, 2022
2 parents 54f3578 + 1ffd043 commit bc26f97
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions compiler/rustc_data_structures/src/stable_hasher/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,45 @@ fn test_hash_bit_matrix() {
assert_ne!(a, b);
assert_ne!(hash(&a), hash(&b));
}

// Check that exchanging the value of two adjacent fields changes the hash.
#[test]
fn test_attribute_permutation() {
macro_rules! test_type {
($ty: ty) => {{
struct Foo {
a: $ty,
b: $ty,
}

impl<CTX> HashStable<CTX> for Foo {
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
self.a.hash_stable(hcx, hasher);
self.b.hash_stable(hcx, hasher);
}
}

#[allow(overflowing_literals)]
let mut item = Foo { a: 0xFF, b: 0xFF_FF };
let hash_a = hash(&item);
std::mem::swap(&mut item.a, &mut item.b);
let hash_b = hash(&item);
assert_ne!(
hash_a,
hash_b,
"The hash stayed the same after values were swapped for type `{}`!",
stringify!($ty)
);
}};
}

test_type!(u16);
test_type!(u32);
test_type!(u64);
test_type!(u128);

test_type!(i16);
test_type!(i32);
test_type!(i64);
test_type!(i128);
}

0 comments on commit bc26f97

Please sign in to comment.