1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use rustc_data_structures::stable_hasher;
14 use serialize::opaque::{EncodeResult, Encoder, Decoder};
16 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
17 pub struct Fingerprint(u64, u64);
21 pub const ZERO: Fingerprint = Fingerprint(0, 0);
24 pub fn from_smaller_hash(hash: u64) -> Fingerprint {
25 Fingerprint(hash, hash)
29 pub fn to_smaller_hash(&self) -> u64 {
34 pub fn as_value(&self) -> (u64, u64) {
39 pub fn combine(self, other: Fingerprint) -> Fingerprint {
40 // See https://stackoverflow.com/a/27952689 on why this function is
41 // implemented this way.
43 self.0.wrapping_mul(3).wrapping_add(other.0),
44 self.1.wrapping_mul(3).wrapping_add(other.1)
48 pub fn to_hex(&self) -> String {
49 format!("{:x}{:x}", self.0, self.1)
52 pub fn encode_opaque(&self, encoder: &mut Encoder) -> EncodeResult {
53 let bytes: [u8; 16] = unsafe { mem::transmute([self.0.to_le(), self.1.to_le()]) };
55 encoder.emit_raw_bytes(&bytes);
59 pub fn decode_opaque<'a>(decoder: &mut Decoder<'a>) -> Result<Fingerprint, String> {
60 let mut bytes = [0; 16];
62 decoder.read_raw_bytes(&mut bytes)?;
64 let [l, r]: [u64; 2] = unsafe { mem::transmute(bytes) };
66 Ok(Fingerprint(u64::from_le(l), u64::from_le(r)))
70 impl ::std::fmt::Display for Fingerprint {
71 fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
72 write!(formatter, "{:x}-{:x}", self.0, self.1)
76 impl stable_hasher::StableHasherResult for Fingerprint {
77 fn finish(hasher: stable_hasher::StableHasher<Self>) -> Self {
78 let (_0, _1) = hasher.finalize();
83 impl<CTX> stable_hasher::HashStable<CTX> for Fingerprint {
85 fn hash_stable<W: stable_hasher::StableHasherResult>(&self,
87 hasher: &mut stable_hasher::StableHasher<W>) {
88 ::std::hash::Hash::hash(self, hasher);
92 impl serialize::UseSpecializedEncodable for Fingerprint { }
94 impl serialize::UseSpecializedDecodable for Fingerprint { }
96 impl serialize::SpecializedEncoder<Fingerprint> for serialize::opaque::Encoder {
97 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
102 impl<'a> serialize::SpecializedDecoder<Fingerprint> for serialize::opaque::Decoder<'a> {
103 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
104 Fingerprint::decode_opaque(self)