Skip to main content

rustc_data_structures/
fingerprint.rs

1use std::hash::{Hash, Hasher};
2
3use rustc_hashes::Hash64;
4use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
5
6use crate::stable_hash::{
7    FromStableHash, StableHash, StableHashCtxt, StableHasher, StableHasherHash,
8};
9
10#[cfg(test)]
11mod tests;
12
13#[derive(#[automatically_derived]impl ::core::cmp::Eq for Fingerprint {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u64>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    Fingerprint {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Fingerprint {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0 && self.1 == other.1
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Ord for Fingerprint {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.0, &other.0) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.1, &other.1),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]impl ::core::cmp::PartialOrd for Fingerprint {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::fmt::Debug for Fingerprint {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Fingerprint",
            &self.0, &&self.1)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Fingerprint {
}
#[automatically_derived]impl ::core::clone::Clone for Fingerprint {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u64>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Fingerprint { }Copy)]
14#[repr(C)]
15pub struct Fingerprint(u64, u64);
16
17pub trait FingerprintComponent {
18    fn as_u64(&self) -> u64;
19}
20
21impl FingerprintComponent for Hash64 {
22    #[inline]
23    fn as_u64(&self) -> u64 {
24        Hash64::as_u64(*self)
25    }
26}
27
28impl FingerprintComponent for u64 {
29    #[inline]
30    fn as_u64(&self) -> u64 {
31        *self
32    }
33}
34
35impl Fingerprint {
36    pub const ZERO: Fingerprint = Fingerprint(0, 0);
37
38    #[inline]
39    pub fn new<A, B>(_0: A, _1: B) -> Fingerprint
40    where
41        A: FingerprintComponent,
42        B: FingerprintComponent,
43    {
44        Fingerprint(_0.as_u64(), _1.as_u64())
45    }
46
47    #[inline]
48    pub fn to_smaller_hash(&self) -> Hash64 {
49        // Even though both halves of the fingerprint are expected to be good
50        // quality hash values, let's still combine the two values because the
51        // Fingerprints in DefPathHash have the StableCrateId portion which is
52        // the same for all DefPathHashes from the same crate. Combining the
53        // two halves makes sure we get a good quality hash in such cases too.
54        Hash64::new(self.0.wrapping_mul(3).wrapping_add(self.1))
55    }
56
57    #[inline]
58    pub fn split(&self) -> (Hash64, Hash64) {
59        (Hash64::new(self.0), Hash64::new(self.1))
60    }
61
62    #[inline]
63    pub fn combine(self, other: Fingerprint) -> Fingerprint {
64        // See https://stackoverflow.com/a/27952689 on why this function is
65        // implemented this way.
66        Fingerprint(
67            self.0.wrapping_mul(3).wrapping_add(other.0),
68            self.1.wrapping_mul(3).wrapping_add(other.1),
69        )
70    }
71
72    #[inline]
73    pub(crate) fn as_u128(self) -> u128 {
74        u128::from(self.1) << 64 | u128::from(self.0)
75    }
76
77    // Combines two hashes in an order independent way. Make sure this is what
78    // you want.
79    #[inline]
80    pub fn combine_commutative(self, other: Fingerprint) -> Fingerprint {
81        let a = u128::from(self.1) << 64 | u128::from(self.0);
82        let b = u128::from(other.1) << 64 | u128::from(other.0);
83
84        let c = a.wrapping_add(b);
85
86        Fingerprint(c as u64, (c >> 64) as u64)
87    }
88
89    pub fn to_hex(&self) -> String {
90        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:x}{1:x}", self.0, self.1))
    })format!("{:x}{:x}", self.0, self.1)
91    }
92
93    #[inline]
94    pub fn to_le_bytes(&self) -> [u8; 16] {
95        // This seems to optimize to the same machine code as
96        // `unsafe { mem::transmute(*k) }`. Well done, LLVM! :)
97        let mut result = [0u8; 16];
98
99        let first_half: &mut [u8; 8] = (&mut result[0..8]).try_into().unwrap();
100        *first_half = self.0.to_le_bytes();
101
102        let second_half: &mut [u8; 8] = (&mut result[8..16]).try_into().unwrap();
103        *second_half = self.1.to_le_bytes();
104
105        result
106    }
107
108    #[inline]
109    pub fn from_le_bytes(bytes: [u8; 16]) -> Fingerprint {
110        Fingerprint(
111            u64::from_le_bytes(bytes[0..8].try_into().unwrap()),
112            u64::from_le_bytes(bytes[8..16].try_into().unwrap()),
113        )
114    }
115}
116
117impl std::fmt::Display for Fingerprint {
118    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        formatter.write_fmt(format_args!("{0:x}-{1:x}", self.0, self.1))write!(formatter, "{:x}-{:x}", self.0, self.1)
120    }
121}
122
123impl Hash for Fingerprint {
124    #[inline]
125    fn hash<H: Hasher>(&self, state: &mut H) {
126        state.write_fingerprint(self);
127    }
128}
129
130trait FingerprintHasher {
131    fn write_fingerprint(&mut self, fingerprint: &Fingerprint);
132}
133
134impl<H: Hasher> FingerprintHasher for H {
135    #[inline]
136    default fn write_fingerprint(&mut self, fingerprint: &Fingerprint) {
137        self.write_u64(fingerprint.0);
138        self.write_u64(fingerprint.1);
139    }
140}
141
142impl FingerprintHasher for crate::unhash::Unhasher {
143    #[inline]
144    fn write_fingerprint(&mut self, fingerprint: &Fingerprint) {
145        // Even though both halves of the fingerprint are expected to be good
146        // quality hash values, let's still combine the two values because the
147        // Fingerprints in DefPathHash have the StableCrateId portion which is
148        // the same for all DefPathHashes from the same crate. Combining the
149        // two halves makes sure we get a good quality hash in such cases too.
150        //
151        // Since `Unhasher` is used only in the context of HashMaps, it is OK
152        // to combine the two components in an order-independent way (which is
153        // cheaper than the more robust Fingerprint::to_smaller_hash()). For
154        // HashMaps we don't really care if Fingerprint(x,y) and
155        // Fingerprint(y, x) result in the same hash value. Collision
156        // probability will still be much better than with FxHash.
157        self.write_u64(fingerprint.0.wrapping_add(fingerprint.1));
158    }
159}
160
161impl FromStableHash for Fingerprint {
162    type Hash = StableHasherHash;
163
164    #[inline]
165    fn from(StableHasherHash([_0, _1]): Self::Hash) -> Self {
166        Fingerprint(_0, _1)
167    }
168}
169
170impl StableHash for Fingerprint {
171    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
172        let &Fingerprint(a, b) = self;
173        a.stable_hash(hcx, hasher);
174        b.stable_hash(hcx, hasher);
175    }
176}
177
178impl<E: Encoder> Encodable<E> for Fingerprint {
179    #[inline]
180    fn encode(&self, s: &mut E) {
181        s.emit_raw_bytes(&self.to_le_bytes());
182    }
183}
184
185impl<D: Decoder> Decodable<D> for Fingerprint {
186    #[inline]
187    fn decode(d: &mut D) -> Self {
188        Fingerprint::from_le_bytes(d.read_raw_bytes(16).try_into().unwrap())
189    }
190}
191
192/// `PackedFingerprint` wraps a `Fingerprint`.
193/// Its purpose is to behave like a `Fingerprint` without alignment requirements.
194///
195/// This may be preferable to use in large collections of structs containing
196/// fingerprints, as it can reduce memory consumption by preventing the padding
197/// that the more strictly-aligned `Fingerprint` can introduce. An application of
198/// this is in the query dependency graph, which contains a large collection of
199/// `DepNode`s. As of this writing, the size of a `DepNode` decreases by 25%
200/// (from 24 bytes to 18) by using the packed representation here, which
201/// noticeably decreases total memory usage when compiling large crates.
202///
203/// (Unalignment was previously restricted to `x86` and `x86_64` hosts, but is
204/// now enabled by default for all host architectures, in the hope that the
205/// memory and cache savings should outweigh any unaligned access penalty.)
206///
207/// The wrapped `Fingerprint` is private to reduce the chance of a client
208/// invoking undefined behavior by taking a reference to the packed field.
209#[repr(packed)]
210#[derive(#[automatically_derived]impl ::core::cmp::Eq for PackedFingerprint {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Fingerprint>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    PackedFingerprint {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PackedFingerprint {
    #[inline]
    fn eq(&self, other: &Self) -> bool { ({ self.0 }) == ({ other.0 }) }
}PartialEq, #[automatically_derived]impl ::core::cmp::Ord for PackedFingerprint {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&{ self.0 }, &{ other.0 })
    }
}Ord, #[automatically_derived]impl ::core::cmp::PartialOrd for PackedFingerprint {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::fmt::Debug for PackedFingerprint {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "PackedFingerprint", &&{ self.0 })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PackedFingerprint {
}
#[automatically_derived]impl ::core::clone::Clone for PackedFingerprint {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Fingerprint>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PackedFingerprint { }Copy, #[automatically_derived]impl ::core::hash::Hash for PackedFingerprint {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&{ self.0 }, state)
    }
}Hash)]
211pub struct PackedFingerprint(Fingerprint);
212
213impl std::fmt::Display for PackedFingerprint {
214    #[inline]
215    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        // Copy to avoid taking reference to packed field.
217        let copy = self.0;
218        copy.fmt(formatter)
219    }
220}
221
222impl<E: Encoder> Encodable<E> for PackedFingerprint {
223    #[inline]
224    fn encode(&self, s: &mut E) {
225        // Copy to avoid taking reference to packed field.
226        let copy = self.0;
227        copy.encode(s);
228    }
229}
230
231impl<D: Decoder> Decodable<D> for PackedFingerprint {
232    #[inline]
233    fn decode(d: &mut D) -> Self {
234        Self(Fingerprint::decode(d))
235    }
236}
237
238impl From<Fingerprint> for PackedFingerprint {
239    #[inline]
240    fn from(f: Fingerprint) -> PackedFingerprint {
241        PackedFingerprint(f)
242    }
243}
244
245impl From<PackedFingerprint> for Fingerprint {
246    #[inline]
247    fn from(f: PackedFingerprint) -> Fingerprint {
248        f.0
249    }
250}