uv_cache_key/
digest.rs

1use std::hash::{Hash, Hasher};
2
3use seahash::SeaHasher;
4
5use crate::cache_key::{CacheKey, CacheKeyHasher};
6
7/// Compute a hex string hash of a `CacheKey` object.
8///
9/// The value returned by [`cache_digest`] should be stable across releases and platforms.
10pub fn cache_digest<H: CacheKey>(hashable: &H) -> String {
11    /// Compute a u64 hash of a [`CacheKey`] object.
12    fn cache_key_u64<H: CacheKey>(hashable: &H) -> u64 {
13        let mut hasher = CacheKeyHasher::new();
14        hashable.cache_key(&mut hasher);
15        hasher.finish()
16    }
17
18    to_hex(cache_key_u64(hashable))
19}
20
21/// Compute a hex string hash of a hashable object.
22pub fn hash_digest<H: Hash>(hashable: &H) -> String {
23    /// Compute a u64 hash of a hashable object.
24    fn hash_u64<H: Hash>(hashable: &H) -> u64 {
25        let mut hasher = SeaHasher::new();
26        hashable.hash(&mut hasher);
27        hasher.finish()
28    }
29
30    to_hex(hash_u64(hashable))
31}
32
33/// Convert a u64 to a hex string.
34fn to_hex(num: u64) -> String {
35    hex::encode(num.to_le_bytes())
36}