Skip to content

Commit bc26f97

Browse files
authored
Rollup merge of #93193 - Kobzol:stable-hash-permutation-test, r=the8472
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`
2 parents 54f3578 + 1ffd043 commit bc26f97

File tree

1 file changed

+42
-0
lines changed
  • compiler/rustc_data_structures/src/stable_hasher

1 file changed

+42
-0
lines changed

compiler/rustc_data_structures/src/stable_hasher/tests.rs

+42
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,45 @@ fn test_hash_bit_matrix() {
9898
assert_ne!(a, b);
9999
assert_ne!(hash(&a), hash(&b));
100100
}
101+
102+
// Check that exchanging the value of two adjacent fields changes the hash.
103+
#[test]
104+
fn test_attribute_permutation() {
105+
macro_rules! test_type {
106+
($ty: ty) => {{
107+
struct Foo {
108+
a: $ty,
109+
b: $ty,
110+
}
111+
112+
impl<CTX> HashStable<CTX> for Foo {
113+
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
114+
self.a.hash_stable(hcx, hasher);
115+
self.b.hash_stable(hcx, hasher);
116+
}
117+
}
118+
119+
#[allow(overflowing_literals)]
120+
let mut item = Foo { a: 0xFF, b: 0xFF_FF };
121+
let hash_a = hash(&item);
122+
std::mem::swap(&mut item.a, &mut item.b);
123+
let hash_b = hash(&item);
124+
assert_ne!(
125+
hash_a,
126+
hash_b,
127+
"The hash stayed the same after values were swapped for type `{}`!",
128+
stringify!($ty)
129+
);
130+
}};
131+
}
132+
133+
test_type!(u16);
134+
test_type!(u32);
135+
test_type!(u64);
136+
test_type!(u128);
137+
138+
test_type!(i16);
139+
test_type!(i32);
140+
test_type!(i64);
141+
test_type!(i128);
142+
}

0 commit comments

Comments
 (0)