Skip to content

Commit 311050d

Browse files
committed
Use full hash bytes and use fixed endianness
1 parent 38b97bc commit 311050d

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

compiler/rustc_data_structures/src/fingerprint.rs

+10-5
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,16 @@ impl FromStableHash for Fingerprint {
159159

160160
#[inline]
161161
fn from(hash: Self::Hash) -> Self {
162-
let bytes = hash.as_bytes();
163-
Fingerprint(
164-
u64::from_ne_bytes(bytes[0..8].try_into().unwrap()),
165-
u64::from_ne_bytes(bytes[8..16].try_into().unwrap()),
166-
)
162+
let bytes: &[u8; 32] = hash.as_bytes();
163+
164+
let p0 = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
165+
let p1 = u64::from_le_bytes(bytes[8..16].try_into().unwrap());
166+
let p2 = u64::from_le_bytes(bytes[16..24].try_into().unwrap());
167+
let p3 = u64::from_le_bytes(bytes[24..32].try_into().unwrap());
168+
169+
// See https://stackoverflow.com/a/27952689 on why this function is
170+
// implemented this way.
171+
Fingerprint(p0.wrapping_mul(3).wrapping_add(p1), p2.wrapping_mul(3).wrapping_add(p3))
167172
}
168173
}
169174

compiler/rustc_data_structures/src/hashes.rs

+25-2
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,19 @@ impl FromStableHash for Hash64 {
6262
#[inline]
6363
fn from(hash: Self::Hash) -> Self {
6464
let bytes = hash.as_bytes();
65-
Self { inner: u64::from_ne_bytes(bytes[0..8].try_into().unwrap()) }
65+
66+
let p0 = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
67+
let p1 = u64::from_le_bytes(bytes[8..16].try_into().unwrap());
68+
let p2 = u64::from_le_bytes(bytes[16..24].try_into().unwrap());
69+
let p3 = u64::from_le_bytes(bytes[24..32].try_into().unwrap());
70+
71+
// See https://stackoverflow.com/a/27952689 on why this function is
72+
// implemented this way.
73+
let m0 = p0.wrapping_mul(3).wrapping_add(p1);
74+
let m1 = p2.wrapping_mul(3).wrapping_add(p3);
75+
let h = m0.wrapping_mul(3).wrapping_add(m1);
76+
77+
Self { inner: h }
6678
}
6779
}
6880

@@ -130,7 +142,18 @@ impl FromStableHash for Hash128 {
130142
#[inline]
131143
fn from(hash: Self::Hash) -> Self {
132144
let bytes = hash.as_bytes();
133-
Self { inner: u128::from_ne_bytes(bytes[0..16].try_into().unwrap()) }
145+
146+
let p0 = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
147+
let p1 = u64::from_le_bytes(bytes[8..16].try_into().unwrap());
148+
let p2 = u64::from_le_bytes(bytes[16..24].try_into().unwrap());
149+
let p3 = u64::from_le_bytes(bytes[24..32].try_into().unwrap());
150+
151+
// See https://stackoverflow.com/a/27952689 on why this function is
152+
// implemented this way.
153+
let upper = p0.wrapping_mul(3).wrapping_add(p1);
154+
let lower = p2.wrapping_mul(3).wrapping_add(p3);
155+
156+
Self { inner: u128::from(lower) | (u128::from(upper) << 64) }
134157
}
135158
}
136159

0 commit comments

Comments
 (0)