1use std::borrow::Cow;
2use std::hash::{Hash, Hasher};
3
4use seahash::SeaHasher;
5
6use crate::cache_key::{CacheKey, CacheKeyHasher};
7
8pub fn cache_digest<H: CacheKey>(hashable: &H) -> String {
12 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
22pub fn hash_digest<H: Hash>(hashable: &H) -> String {
24 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
34fn to_hex(num: u64) -> String {
36 hex::encode(num.to_le_bytes())
37}
38
39pub 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 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}