1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use crate::stable_hasher;
use rustc_serialize::{
    opaque::{self, EncodeResult},
    Decodable, Encodable,
};
use std::hash::{Hash, Hasher};
use std::mem;

#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy)]
pub struct Fingerprint(u64, u64);

impl Fingerprint {
    pub const ZERO: Fingerprint = Fingerprint(0, 0);

    #[inline]
    pub fn from_smaller_hash(hash: u64) -> Fingerprint {
        Fingerprint(hash, hash)
    }

    #[inline]
    pub fn to_smaller_hash(&self) -> u64 {
        self.0
    }

    #[inline]
    pub fn as_value(&self) -> (u64, u64) {
        (self.0, self.1)
    }

    #[inline]
    pub fn combine(self, other: Fingerprint) -> Fingerprint {
        // See https://stackoverflow.com/a/27952689 on why this function is
        // implemented this way.
        Fingerprint(
            self.0.wrapping_mul(3).wrapping_add(other.0),
            self.1.wrapping_mul(3).wrapping_add(other.1),
        )
    }

    // Combines two hashes in an order independent way. Make sure this is what
    // you want.
    #[inline]
    pub fn combine_commutative(self, other: Fingerprint) -> Fingerprint {
        let a = u128::from(self.1) << 64 | u128::from(self.0);
        let b = u128::from(other.1) << 64 | u128::from(other.0);

        let c = a.wrapping_add(b);

        Fingerprint((c >> 64) as u64, c as u64)
    }

    pub fn to_hex(&self) -> String {
        format!("{:x}{:x}", self.0, self.1)
    }

    pub fn encode_opaque(&self, encoder: &mut opaque::Encoder) -> EncodeResult {
        let bytes: [u8; 16] = unsafe { mem::transmute([self.0.to_le(), self.1.to_le()]) };

        encoder.emit_raw_bytes(&bytes);
        Ok(())
    }

    pub fn decode_opaque(decoder: &mut opaque::Decoder<'_>) -> Result<Fingerprint, String> {
        let mut bytes = [0; 16];

        decoder.read_raw_bytes(&mut bytes)?;

        let [l, r]: [u64; 2] = unsafe { mem::transmute(bytes) };

        Ok(Fingerprint(u64::from_le(l), u64::from_le(r)))
    }
}

impl std::fmt::Display for Fingerprint {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{:x}-{:x}", self.0, self.1)
    }
}

impl Hash for Fingerprint {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_fingerprint(self);
    }
}

trait FingerprintHasher {
    fn write_fingerprint(&mut self, fingerprint: &Fingerprint);
}

impl<H: Hasher> FingerprintHasher for H {
    #[inline]
    default fn write_fingerprint(&mut self, fingerprint: &Fingerprint) {
        self.write_u64(fingerprint.0);
        self.write_u64(fingerprint.1);
    }
}

impl FingerprintHasher for crate::unhash::Unhasher {
    #[inline]
    fn write_fingerprint(&mut self, fingerprint: &Fingerprint) {
        // `Unhasher` only wants a single `u64`
        self.write_u64(fingerprint.0);
    }
}

impl stable_hasher::StableHasherResult for Fingerprint {
    #[inline]
    fn finish(hasher: stable_hasher::StableHasher) -> Self {
        let (_0, _1) = hasher.finalize();
        Fingerprint(_0, _1)
    }
}

impl_stable_hash_via_hash!(Fingerprint);

impl<E: rustc_serialize::Encoder> Encodable<E> for Fingerprint {
    fn encode(&self, s: &mut E) -> Result<(), E::Error> {
        s.encode_fingerprint(self)
    }
}

impl<D: rustc_serialize::Decoder> Decodable<D> for Fingerprint {
    fn decode(d: &mut D) -> Result<Self, D::Error> {
        d.decode_fingerprint()
    }
}

pub trait FingerprintEncoder: rustc_serialize::Encoder {
    fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error>;
}

pub trait FingerprintDecoder: rustc_serialize::Decoder {
    fn decode_fingerprint(&mut self) -> Result<Fingerprint, Self::Error>;
}

impl<E: rustc_serialize::Encoder> FingerprintEncoder for E {
    default fn encode_fingerprint(&mut self, _: &Fingerprint) -> Result<(), E::Error> {
        panic!("Cannot encode `Fingerprint` with `{}`", std::any::type_name::<E>());
    }
}

impl FingerprintEncoder for opaque::Encoder {
    fn encode_fingerprint(&mut self, f: &Fingerprint) -> EncodeResult {
        f.encode_opaque(self)
    }
}

impl<D: rustc_serialize::Decoder> FingerprintDecoder for D {
    default fn decode_fingerprint(&mut self) -> Result<Fingerprint, D::Error> {
        panic!("Cannot decode `Fingerprint` with `{}`", std::any::type_name::<D>());
    }
}
impl FingerprintDecoder for opaque::Decoder<'_> {
    fn decode_fingerprint(&mut self) -> Result<Fingerprint, String> {
        Fingerprint::decode_opaque(self)
    }
}