]>
Commit | Line | Data |
---|---|---|
c30ab7b3 SL |
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. | |
4 | // | |
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. | |
10 | ||
476ff2be | 11 | use rustc_data_structures::stable_hasher; |
7cac9316 XL |
12 | use std::mem; |
13 | use std::slice; | |
c30ab7b3 | 14 | |
7cac9316 XL |
15 | #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)] |
16 | pub struct Fingerprint(u64, u64); | |
c30ab7b3 SL |
17 | |
18 | impl Fingerprint { | |
19 | #[inline] | |
20 | pub fn zero() -> Fingerprint { | |
7cac9316 | 21 | Fingerprint(0, 0) |
c30ab7b3 SL |
22 | } |
23 | ||
7cac9316 | 24 | #[inline] |
c30ab7b3 | 25 | pub fn from_smaller_hash(hash: u64) -> Fingerprint { |
7cac9316 | 26 | Fingerprint(hash, hash) |
c30ab7b3 SL |
27 | } |
28 | ||
7cac9316 | 29 | #[inline] |
c30ab7b3 | 30 | pub fn to_smaller_hash(&self) -> u64 { |
7cac9316 | 31 | self.0 |
c30ab7b3 | 32 | } |
476ff2be SL |
33 | |
34 | pub fn to_hex(&self) -> String { | |
7cac9316 | 35 | format!("{:x}{:x}", self.0, self.1) |
476ff2be | 36 | } |
c30ab7b3 SL |
37 | } |
38 | ||
7cac9316 XL |
39 | impl ::std::fmt::Display for Fingerprint { |
40 | fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { | |
41 | write!(formatter, "{:x}-{:x}", self.0, self.1) | |
c30ab7b3 SL |
42 | } |
43 | } | |
44 | ||
7cac9316 XL |
45 | impl stable_hasher::StableHasherResult for Fingerprint { |
46 | fn finish(mut hasher: stable_hasher::StableHasher<Self>) -> Self { | |
47 | let hash_bytes: &[u8] = hasher.finalize(); | |
c30ab7b3 | 48 | |
7cac9316 XL |
49 | assert!(hash_bytes.len() >= mem::size_of::<u64>() * 2); |
50 | let hash_bytes: &[u64] = unsafe { | |
51 | slice::from_raw_parts(hash_bytes.as_ptr() as *const u64, 2) | |
52 | }; | |
c30ab7b3 | 53 | |
7cac9316 XL |
54 | // The bytes returned bytes the Blake2B hasher are always little-endian. |
55 | Fingerprint(u64::from_le(hash_bytes[0]), u64::from_le(hash_bytes[1])) | |
c30ab7b3 SL |
56 | } |
57 | } | |
476ff2be | 58 | |
7cac9316 XL |
59 | impl<CTX> stable_hasher::HashStable<CTX> for Fingerprint { |
60 | #[inline] | |
61 | fn hash_stable<W: stable_hasher::StableHasherResult>(&self, | |
62 | _: &mut CTX, | |
63 | hasher: &mut stable_hasher::StableHasher<W>) { | |
64 | ::std::hash::Hash::hash(self, hasher); | |
476ff2be SL |
65 | } |
66 | } |