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.
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 // Combines two hashes in an order independent way. Make sure this is what
51 pub fn combine_commutative(self, other: Fingerprint) -> Fingerprint {
52 let a = (self.1 as u128) << 64 | self.0 as u128;
53 let b = (other.1 as u128) << 64 | other.0 as u128;
55 let c = a.wrapping_add(b);
57 Fingerprint((c >> 64) as u64, c as u64)
60 pub fn to_hex(&self) -> String {
61 format!("{:x}{:x}", self.0, self.1)
64 pub fn encode_opaque(&self, encoder: &mut Encoder) -> EncodeResult {
65 let bytes: [u8; 16] = unsafe { mem::transmute([self.0.to_le(), self.1.to_le()]) };
67 encoder.emit_raw_bytes(&bytes);
71 pub fn decode_opaque<'a>(decoder: &mut Decoder<'a>) -> Result<Fingerprint, String> {
72 let mut bytes = [0; 16];
74 decoder.read_raw_bytes(&mut bytes)?;
76 let [l, r]: [u64; 2] = unsafe { mem::transmute(bytes) };
78 Ok(Fingerprint(u64::from_le(l), u64::from_le(r)))
82 impl ::std::fmt::Display for Fingerprint {
83 fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
84 write!(formatter, "{:x}-{:x}", self.0, self.1)
88 impl stable_hasher::StableHasherResult for Fingerprint {
90 fn finish(hasher: stable_hasher::StableHasher<Self>) -> Self {
91 let (_0, _1) = hasher.finalize();
96 impl_stable_hash_via_hash!(Fingerprint);
98 impl serialize::UseSpecializedEncodable for Fingerprint { }
100 impl serialize::UseSpecializedDecodable for Fingerprint { }
102 impl serialize::SpecializedEncoder<Fingerprint> for serialize::opaque::Encoder {
103 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
104 f.encode_opaque(self)
108 impl<'a> serialize::SpecializedDecoder<Fingerprint> for serialize::opaque::Decoder<'a> {
109 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
110 Fingerprint::decode_opaque(self)