use crate::consts::METHOD_QUERY;
use sha2::{Digest, Sha256};
use std::fmt::Write;
pub fn cache_key(target_url: &str, content_type: &str, body: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(METHOD_QUERY.as_bytes());
hasher.update([0]);
hasher.update(target_url.as_bytes());
hasher.update([0]);
hasher.update(content_type.as_bytes());
hasher.update([0]);
hasher.update(body);
let digest = hasher.finalize();
let mut out = String::with_capacity(64);
for byte in digest {
let _ = write!(out, "{byte:02x}");
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn depends_on_body_and_url() {
let base = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
let same = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
let other_body = cache_key("https://example.org/s", "application/json", br#"{"q":"b"}"#);
let other_url = cache_key("https://example.org/t", "application/json", br#"{"q":"a"}"#);
assert_eq!(base, same);
assert_ne!(base, other_body);
assert_ne!(base, other_url);
assert_eq!(base.len(), 64);
}
}