Skip to main content

Cache

Struct Cache 

Source
pub struct Cache<K, V> { /* private fields */ }
Expand description

A simple cache implementation with expiration and optional capacity limit.

This cache provides time-based expiration for items and an optional maximum capacity. It’s designed to be generic over both key and value types for maximum flexibility.

§Examples

use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
let _ = cache.insert("visits".to_string(), 1);
assert_eq!(cache.get(&"visits".to_string()), Some(&1));

Implementations§

Source§

impl<K: Hash + Eq + Clone, V: Clone> Cache<K, V>

Source

pub fn new(ttl: Duration) -> Self

Creates a new Cache with the specified time-to-live (TTL) for items.

§Arguments
  • ttl - The time-to-live for cached items.
§Panics

Panics if ttl is zero.

§Example
use staticweaver::cache::Cache;
use std::time::Duration;

let cache: Cache<String, String> = Cache::new(Duration::from_secs(60));
Source

pub fn iter(&self) -> impl Iterator<Item = (&K, &V)>

Returns an iterator over the key-value pairs in the cache.

Only entries that have not yet expired are yielded.

§Returns

An iterator over the key-value pairs in the cache.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, String> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("a".to_string(), "1".to_string());
let _ = cache.insert("b".to_string(), "2".to_string());
assert_eq!(cache.iter().count(), 2);
Source

pub fn with_capacity(ttl: Duration, capacity: usize) -> Self

Creates a new Cache with the specified TTL and initial capacity.

§Arguments
  • ttl - The time-to-live for cached items.
  • capacity - The initial capacity of the cache.
§Panics

Panics if ttl is zero.

§Example
use staticweaver::cache::Cache;
use std::time::Duration;

let cache: Cache<String, String> = Cache::with_capacity(Duration::from_secs(60), 100);
Source

pub fn stats(&self) -> CacheStats

Returns a snapshot of cumulative cache counters (hits, misses, evictions, ttl-expirations, inserts). Issue #40.

All counters are monotonically increasing u64s. Take two snapshots and subtract to get a per-window rate. Designed for cheap export to prometheus, metrics, or opentelemetry without forcing a dependency choice.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
assert_eq!(cache.stats().inserts, 0);
let _ = cache.insert("k".to_string(), 1);
assert_eq!(cache.stats().inserts, 1);
Source

pub fn insert(&mut self, key: K, value: V) -> Option<V>

Inserts a key-value pair into the cache.

If the cache is at capacity and the key doesn’t already exist, the least-recently-used entry is evicted to make room.

§Arguments
  • key - The key to insert.
  • value - The value to insert.
§Returns

The old value if the key was already present.

§Example
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache = Cache::new(Duration::from_secs(60));
cache.insert("key".to_string(), "value".to_string());
Source

pub fn get(&mut self, key: &K) -> Option<&V>

Retrieves a value from the cache if it exists and hasn’t expired.

§Arguments
  • key - The key to look up.
§Returns

An Option containing a reference to the value if it exists and hasn’t expired, or None otherwise.

§Example
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache = Cache::new(Duration::from_secs(60));
cache.insert("key".to_string(), "value".to_string());

assert_eq!(cache.get(&"key".to_string()), Some(&"value".to_string()));
Source

pub fn remove_expired(&mut self)

Removes expired items from the cache.

This method should be called periodically to clean up the cache.

Time complexity: O(n) where n is the number of items in the cache.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, String> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("k".to_string(), "v".to_string());
cache.remove_expired();
assert_eq!(cache.len(), 1);
Source

pub fn contains_key(&self, key: &K) -> bool

Checks if a key exists in the cache and hasn’t expired.

§Arguments
  • key - The key to check.
§Returns

true if the key exists and hasn’t expired, false otherwise.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, i32> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
assert!(cache.contains_key(&"n".to_string()));
assert!(!cache.contains_key(&"missing".to_string()));
Source

pub fn ttl(&self, key: &K) -> Option<Duration>

Gets the remaining time-to-live for an item.

§Arguments
  • key - The key to check.
§Returns

An Option containing the remaining TTL if the item exists and hasn’t expired, or None otherwise.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, i32> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
assert!(cache.ttl(&"n".to_string()).is_some());
assert!(cache.ttl(&"missing".to_string()).is_none());
Source

pub fn refresh(&mut self, key: &K) -> bool

Refreshes the expiration time for an item.

§Arguments
  • key - The key of the item to refresh.
§Returns

true if the item was found and refreshed, false otherwise.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, i32> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
assert!(cache.refresh(&"n".to_string()));
assert!(!cache.refresh(&"missing".to_string()));
Source

pub fn remove(&mut self, key: &K) -> Option<V>

Removes a key-value pair from the cache.

§Arguments
  • key - The key to remove.
§Returns

The removed value if the key was present, or None otherwise.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, String> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("k".to_string(), "v".to_string());
assert_eq!(cache.remove(&"k".to_string()), Some("v".to_string()));
assert_eq!(cache.remove(&"k".to_string()), None);
Source

pub fn update(&mut self, key: &K, value: V) -> bool

Updates the value for an existing key in the cache.

§Arguments
  • key - The key to update.
  • value - The new value to set.
§Returns

true if the key was found and updated, false otherwise.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, String> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("k".to_string(), "old".to_string());
assert!(cache.update(&"k".to_string(), "new".to_string()));
assert_eq!(cache.get(&"k".to_string()), Some(&"new".to_string()));
Source

pub fn set_capacity(&mut self, capacity: usize)

Sets a maximum capacity for the cache.

If the cache is already larger than this capacity, it will not remove items immediately, but it will prevent new items from being added until it’s below capacity (via LRU eviction on insert).

§Arguments
  • capacity - The maximum number of items the cache can hold.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, String> =
    Cache::new(Duration::from_secs(60));
cache.set_capacity(128);
Source

pub fn clear(&mut self)

Clears all items from the cache.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, i32> =
    Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
cache.clear();
assert!(cache.is_empty());
Source

pub fn len(&self) -> usize

Returns the number of items in the cache.

§Returns

The number of key-value pairs currently in the cache.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let mut cache: Cache<String, i32> =
    Cache::new(Duration::from_secs(60));
assert_eq!(cache.len(), 0);
let _ = cache.insert("a".to_string(), 1);
assert_eq!(cache.len(), 1);
Source

pub fn is_empty(&self) -> bool

Checks if the cache is empty.

§Returns

true if the cache is empty, false otherwise.

§Examples
use staticweaver::cache::Cache;
use std::time::Duration;

let cache: Cache<String, String> =
    Cache::new(Duration::from_secs(60));
assert!(cache.is_empty());

Trait Implementations§

Source§

impl<K: Clone, V: Clone> Clone for Cache<K, V>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K: Debug, V: Debug> Debug for Cache<K, V>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K: Hash + Eq + Clone, V: Clone> Default for Cache<K, V>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<K: Hash + Eq + Clone, V: Clone> FromIterator<(K, V)> for Cache<K, V>

Source§

fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<K: Hash + Eq + Clone, V: Clone> IntoIterator for Cache<K, V>

Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<K, V> Freeze for Cache<K, V>

§

impl<K, V> RefUnwindSafe for Cache<K, V>

§

impl<K, V> Send for Cache<K, V>
where K: Send, V: Send,

§

impl<K, V> Sync for Cache<K, V>
where K: Sync, V: Sync,

§

impl<K, V> Unpin for Cache<K, V>
where K: Unpin, V: Unpin,

§

impl<K, V> UnsafeUnpin for Cache<K, V>

§

impl<K, V> UnwindSafe for Cache<K, V>
where K: UnwindSafe, V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more