Skip to main content

cuckoo_cache/
item.rs

1//! Read-only view of a stored cache item.
2
3use crate::CuckooCacheError;
4use keyvalue::{TinyItem, Value};
5
6/// A read-only view of an item stored in the cuckoo cache.
7pub struct Item {
8    raw: TinyItem,
9}
10
11impl Item {
12    pub(crate) fn new(raw: TinyItem) -> Self {
13        Self { raw }
14    }
15
16    /// Borrow the item's key.
17    pub fn key(&self) -> &[u8] {
18        self.raw.key()
19    }
20
21    /// Borrow the item's value.
22    pub fn value(&self) -> Value<'_> {
23        self.raw.value()
24    }
25
26    /// The item's expiration timestamp as seconds since cache creation.
27    /// Returns `u32::MAX` for items with no expiry.
28    pub fn expire(&self) -> u32 {
29        self.raw.expire()
30    }
31
32    /// Perform a wrapping addition on the value.
33    pub fn wrapping_add(&mut self, rhs: u64) -> Result<(), CuckooCacheError> {
34        self.raw
35            .wrapping_add(rhs)
36            .map_err(|_| CuckooCacheError::NotNumeric)
37    }
38
39    /// Perform a saturating subtraction on the value.
40    pub fn saturating_sub(&mut self, rhs: u64) -> Result<(), CuckooCacheError> {
41        self.raw
42            .saturating_sub(rhs)
43            .map_err(|_| CuckooCacheError::NotNumeric)
44    }
45}
46
47impl std::fmt::Debug for Item {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_struct("Item")
50            .field("expire", &self.expire())
51            .field("raw", &self.raw)
52            .finish()
53    }
54}