1use crate::consts::METHOD_QUERY;
4use sha2::{Digest, Sha256};
5use std::fmt::Write;
6
7pub fn cache_key(target_url: &str, content_type: &str, body: &[u8]) -> String {
13 let mut hasher = Sha256::new();
14 hasher.update(METHOD_QUERY.as_bytes());
15 hasher.update([0]);
16 hasher.update(target_url.as_bytes());
17 hasher.update([0]);
18 hasher.update(content_type.as_bytes());
19 hasher.update([0]);
20 hasher.update(body);
21
22 let digest = hasher.finalize();
23 let mut out = String::with_capacity(64);
24 for byte in digest {
25 let _ = write!(out, "{byte:02x}");
26 }
27 out
28}
29
30#[cfg(test)]
31mod tests {
32 use super::*;
33
34 #[test]
35 fn depends_on_body_and_url() {
36 let base = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
37 let same = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
38 let other_body = cache_key("https://example.org/s", "application/json", br#"{"q":"b"}"#);
39 let other_url = cache_key("https://example.org/t", "application/json", br#"{"q":"a"}"#);
40
41 assert_eq!(base, same);
42 assert_ne!(base, other_body);
43 assert_ne!(base, other_url);
44 assert_eq!(base.len(), 64);
45 }
46}