Skip to main content

cachekit/
key.rs

1use blake2::{digest::consts::U32, Blake2b, Digest};
2
3use crate::error::CachekitError;
4
5type Blake2b256 = Blake2b<U32>;
6
7/// Generate a deterministic cache key by Blake2b-256 hashing the function name
8/// and serialized arguments, optionally prefixed with a namespace.
9pub fn generate_cache_key(
10    namespace: &str,
11    function_name: &str,
12    serialized_args: &[u8],
13) -> Result<String, CachekitError> {
14    let key_material = rmp_serde::to_vec(&(function_name, serialized_args))
15        .map_err(|e| CachekitError::Serialization(e.to_string()))?;
16
17    let mut hasher = Blake2b256::new();
18    hasher.update(&key_material);
19    let hash = hasher.finalize();
20    let hex_hash = hex::encode(hash);
21
22    Ok(if namespace.is_empty() {
23        hex_hash
24    } else {
25        format!("{namespace}:{hex_hash}")
26    })
27}