Skip to main content

omega_cache/core/
entry.rs

1use crate::core::key::Key;
2use std::hash::Hash;
3use std::time::Instant;
4
5/// A container representing a single cached item.
6///
7/// `Entry` holds the mapping between a [Key] and its associated value,
8/// along with optional TTL (Time To Live) metadata to handle expiration.
9///
10/// ### Generic Constraints
11/// * `K`: The raw key type, which must implement [Eq] and [Hash].
12/// * `V`: The type of the value being stored.
13#[derive(Debug)]
14pub struct Entry<K, V>
15where
16    K: Eq + Hash,
17{
18    /// The wrapped key of the entry.
19    key: Key<K>,
20    /// The value stored in the cache.
21    value: V,
22    /// An optional timestamp indicating when this entry becomes invalid.
23    expired_at: Option<Instant>,
24}
25
26impl<K, V> Entry<K, V>
27where
28    K: Eq + Hash,
29{
30    /// Creates a new cache entry with a specified expiration.
31    ///
32    /// # Parameters
33    /// * `key`: The raw key to be wrapped in a [Key].
34    /// * `value`: The data to store.
35    /// * `expired_at`: An [Instant] in the future when the entry expires, or `None` for no limit.
36    #[inline]
37    pub fn new(key: K, value: V, expired_at: Option<Instant>) -> Self {
38        Self {
39            key: Key::new(key),
40            value,
41            expired_at,
42        }
43    }
44
45    /// Returns a reference to the entry's [Key].
46    #[inline]
47    pub fn key(&self) -> &Key<K> {
48        &self.key
49    }
50
51    /// Returns a reference to the stored value.
52    #[inline]
53    pub fn value(&self) -> &V {
54        &self.value
55    }
56
57    /// Checks if the entry has passed its expiration deadline.
58    ///
59    /// Returns `true` if `expired_at` is a time in the past relative to [Instant::now].
60    /// If no expiration was set, this always returns `false`.
61    ///
62    /// # Examples
63    ///
64    /// ```
65    /// use std::time::{Duration, Instant};
66    /// use omega_cache::core::entry::Entry;
67    /// // Entry that expired 1 second ago
68    /// let past = Instant::now() - Duration::from_secs(1);
69    /// let entry = Entry::new("key", "value", Some(past));
70    /// assert!(entry.is_expired());
71    /// ```
72    #[inline]
73    pub fn is_expired(&self) -> bool {
74        self.expired_at
75            .is_some_and(|expired_at| Instant::now() > expired_at)
76    }
77}