Skip to main content

griz_core/
hash_cache.rs

1//! Reuses SHA-256 results only after comparing every input byte.
2
3use crate::hash::sha256;
4use std::{collections::VecDeque, sync::Mutex};
5
6/// An owned SHA-256 result cache with a byte capacity chosen by its caller.
7pub struct ContentHashCache {
8    capacity: usize,
9    entries: Mutex<VecDeque<CachedDigest>>,
10}
11
12struct CachedDigest {
13    bytes: Vec<u8>,
14    hash: String,
15}
16
17impl ContentHashCache {
18    /// Creates an empty cache retaining at most `capacity` input bytes.
19    #[must_use]
20    pub fn new(capacity: usize) -> Self {
21        Self {
22            capacity,
23            entries: Mutex::new(VecDeque::new()),
24        }
25    }
26
27    /// Returns the lowercase hexadecimal SHA-256 of all `bytes`.
28    ///
29    /// A cached digest is reused only for an exactly equal byte buffer.
30    /// Oversized inputs and an unavailable cache are hashed directly.
31    #[must_use]
32    pub fn hash(&self, bytes: &[u8]) -> String {
33        if bytes.len() > self.capacity {
34            return sha256(bytes);
35        }
36        if let Some(hash) = self
37            .entries
38            .lock()
39            .ok()
40            .and_then(|mut entries| lookup(&mut entries, bytes))
41        {
42            return hash;
43        }
44        let hash = sha256(bytes);
45        if let Ok(mut entries) = self.entries.lock() {
46            remember(&mut entries, bytes, &hash, self.capacity);
47        }
48        hash
49    }
50
51    /// Returns the actual input bytes retained, or `None` if the cache is unavailable.
52    #[must_use]
53    pub fn cached_bytes(&self) -> Option<usize> {
54        self.entries
55            .lock()
56            .ok()
57            .map(|entries| resident_bytes(&entries))
58    }
59}
60
61fn lookup(entries: &mut VecDeque<CachedDigest>, bytes: &[u8]) -> Option<String> {
62    let index = entries
63        .iter()
64        .position(|entry| entry.bytes.as_slice() == bytes)?;
65    let entry = entries.remove(index)?;
66    let hash = entry.hash.clone();
67    entries.push_back(entry);
68    Some(hash)
69}
70
71fn remember(entries: &mut VecDeque<CachedDigest>, bytes: &[u8], hash: &str, capacity: usize) {
72    if lookup(entries, bytes).is_some() {
73        return;
74    }
75    while resident_bytes(entries).saturating_add(bytes.len()) > capacity {
76        entries.pop_front();
77    }
78    entries.push_back(CachedDigest {
79        bytes: bytes.to_vec(),
80        hash: hash.to_string(),
81    });
82}
83
84fn resident_bytes(entries: &VecDeque<CachedDigest>) -> usize {
85    entries.iter().map(|entry| entry.bytes.len()).sum()
86}