TTL Cache (Rust)
Topics: RwLock, threads, generics, expiry
Problem
Implement a thread-safe in-memory cache where entries expire automatically after a TTL.
pub struct Cache<K, V> { /* … */ }
impl<K, V> Cache<K, V>
where K: Eq + Hash + Clone + Send + Sync + 'static, V: Send + Sync + 'static {
pub fn new(ttl: Duration) -> Self;
pub fn set(&self, key: K, val: V);
pub fn get(&self, key: &K) -> Option<V> where V: Clone;
pub fn delete(&self, key: &K);
}
set stores a value; if the key already exists, it updates the value and resets the TTL.
get returns Some(value) if present and unexpired, otherwise None.
delete removes an entry immediately.
- Entries expire after the TTL without a background polling loop — schedule a per-entry expiry
instead.
Key concepts
RwLock: read lock for get, write lock for set/delete.
- Expiry thread =
time.AfterFunc: each set spawns a thread that sleeps the TTL and then
removes the entry — no polling.
- Monotonic version stamp: every
set stamps the entry with a globally unique, increasing
version; the expiry thread deletes only if that version is still current, so an update, a delete,
or a re-insert is never removed by a stale timer.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.