Skip to main content

uv_cache_key/
digest.rs

1use std::borrow::Cow;
2use std::hash::{Hash, Hasher};
3
4use seahash::SeaHasher;
5
6use crate::cache_key::{CacheKey, CacheKeyHasher};
7
8/// Compute a hex string hash of a `CacheKey` object.
9///
10/// The value returned by [`cache_digest`] should be stable across releases and platforms.
11pub fn cache_digest<H: CacheKey>(hashable: &H) -> String {
12    /// Compute a u64 hash of a [`CacheKey`] object.
13    fn cache_key_u64<H: CacheKey>(hashable: &H) -> u64 {
14        let mut hasher = CacheKeyHasher::new();
15        hashable.cache_key(&mut hasher);
16        hasher.finish()
17    }
18
19    to_hex(cache_key_u64(hashable))
20}
21
22/// Compute a hex string hash of a hashable object.
23pub fn hash_digest<H: Hash>(hashable: &H) -> String {
24    /// Compute a u64 hash of a hashable object.
25    fn hash_u64<H: Hash>(hashable: &H) -> u64 {
26        let mut hasher = SeaHasher::new();
27        hashable.hash(&mut hasher);
28        hasher.finish()
29    }
30
31    to_hex(hash_u64(hashable))
32}
33
34/// Convert a u64 to a hex string.
35fn to_hex(num: u64) -> String {
36    hex::encode(num.to_le_bytes())
37}
38
39/// Normalize a name for use in a cache entry.
40///
41/// Replaces non-alphanumeric characters with dashes, and lowercases the name.
42///
43/// If `max_len` is provided, the output is truncated to at most that many bytes
44/// (trailing dashes from truncation are stripped).
45pub fn cache_name(name: &str, max_len: Option<usize>) -> Option<Cow<'_, str>> {
46    let limit = max_len.unwrap_or(usize::MAX);
47
48    if name
49        .bytes()
50        .all(|char| matches!(char, b'0'..=b'9' | b'a'..=b'f'))
51    {
52        return if name.is_empty() {
53            None
54        } else {
55            Some(Cow::Borrowed(name.get(..limit).unwrap_or(name)))
56        };
57    }
58    let mut normalized = String::with_capacity(name.len().min(limit));
59    let mut dash = false;
60    for char in name.bytes().take(limit) {
61        match char {
62            b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' => {
63                dash = false;
64                normalized.push(char.to_ascii_lowercase() as char);
65            }
66            _ => {
67                if !dash {
68                    normalized.push('-');
69                    dash = true;
70                }
71            }
72        }
73    }
74    if normalized.ends_with('-') {
75        normalized.pop();
76    }
77    if normalized.is_empty() {
78        None
79    } else {
80        Some(Cow::Owned(normalized))
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use std::error::Error;
87    use uv_redacted::{
88        SafeUrl,
89        policy::{Raw, Stripped},
90    };
91
92    use super::*;
93
94    #[test]
95    fn url_policy_preserves_cache_key() -> Result<(), Box<dyn Error>> {
96        let safe_url =
97            SafeUrl::parse_relaxed("https://user:password@example.com/script.py?sig=signature")?;
98        // `SafeUrl` uses the complete URL for its cache key regardless of serialization policy.
99        // The digest must stay stable so existing cache entries remain addressable.
100        let expected = "a9cdc0a52c71246a";
101        assert_eq!(cache_digest(&safe_url), expected);
102        assert_eq!(
103            cache_digest(&safe_url.clone().with_policy(Stripped)),
104            expected
105        );
106        assert_eq!(cache_digest(&safe_url.with_policy(Raw)), expected);
107        Ok(())
108    }
109
110    #[test]
111    fn test_cache_name() {
112        assert_eq!(cache_name("foo", None), Some("foo".into()));
113        assert_eq!(cache_name("foo-bar", None), Some("foo-bar".into()));
114        assert_eq!(cache_name("foo_bar", None), Some("foo-bar".into()));
115        assert_eq!(cache_name("foo-bar_baz", None), Some("foo-bar-baz".into()));
116        assert_eq!(cache_name("foo-bar_baz_", None), Some("foo-bar-baz".into()));
117        assert_eq!(cache_name("foo-_bar_baz", None), Some("foo-bar-baz".into()));
118        assert_eq!(cache_name("_+-_", None), None);
119    }
120
121    #[test]
122    fn test_cache_name_max_len() {
123        let long = "a".repeat(300);
124        assert_eq!(
125            cache_name(&long, Some(100)).as_deref().map(str::len),
126            Some(100)
127        );
128
129        let long_hex = "abcdef".repeat(50);
130        assert_eq!(
131            cache_name(&long_hex, Some(100)).as_deref().map(str::len),
132            Some(100)
133        );
134
135        assert_eq!(cache_name("aaaa_bbbb", Some(5)), Some("aaaa".into()));
136        assert_eq!(cache_name(&long, None).as_deref().map(str::len), Some(300));
137    }
138}