Cache

Struct Cache 

Source
pub struct Cache { /* private fields */ }
Expand description

A thread-safe, in-memory cache with optional TTL and LRU eviction.

§Features

  • Thread-safe: Can be safely shared across threads using Arc<Cache> or cloning.
  • TTL support: Entries can have optional time-to-live.
  • LRU eviction: When capacity is reached, least recently used entries are evicted.
  • Statistics: Track hits, misses, evictions, and more.

§Example

use in_memory_cache::{Cache, CacheConfig};
use std::time::Duration;

// Create a cache with max 1000 entries and 5 minute default TTL
let config = CacheConfig::new()
    .max_capacity(1000)
    .default_ttl(Duration::from_secs(300))
    .build();

let cache = Cache::new(config);

// Basic operations
cache.set("user:123", "Alice");
if let Some(value) = cache.get("user:123") {
    println!("Found: {:?}", value);
}

// With explicit TTL
cache.set_with_ttl("session:abc", "data", Duration::from_secs(60));

// Check statistics
let stats = cache.stats();
println!("Hit rate: {:.1}%", stats.hit_rate);

Implementations§

Source§

impl Cache

Source

pub fn new(config: CacheConfig) -> Self

Create a new cache with the given configuration.

§Arguments
  • config - Configuration options for the cache.
§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
Source

pub fn get(&self, key: &str) -> Option<Bytes>

Get a value from the cache.

Returns None if the key doesn’t exist or has expired. Accessing a key updates its last-accessed time for LRU tracking.

§Arguments
  • key - The key to look up.
§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
cache.set("key", "value");

match cache.get("key") {
    Some(value) => println!("Found: {:?}", value),
    None => println!("Not found"),
}
Source

pub fn set(&self, key: impl Into<String>, value: impl Into<Bytes>)

Set a value in the cache.

If a default_ttl is configured, entries will use that TTL. Otherwise, entries will not expire.

§Arguments
  • key - The key to store the value under.
  • value - The value to store (anything that can be converted to Bytes).
§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
cache.set("string_key", "string value");
cache.set("bytes_key", vec![1, 2, 3, 4]);
Source

pub fn set_with_ttl( &self, key: impl Into<String>, value: impl Into<Bytes>, ttl: Duration, )

Set a value in the cache with a specific TTL.

The entry will be removed after the specified duration.

§Arguments
  • key - The key to store the value under.
  • value - The value to store.
  • ttl - How long the entry should live.
§Example
use in_memory_cache::{Cache, CacheConfig};
use std::time::Duration;

let cache = Cache::new(CacheConfig::default());
cache.set_with_ttl("session", "data", Duration::from_secs(3600));
Source

pub fn delete(&self, key: &str) -> bool

Delete a key from the cache.

Returns true if the key existed and was removed.

§Arguments
  • key - The key to delete.
§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
cache.set("key", "value");
assert!(cache.delete("key"));
assert!(!cache.delete("key")); // Already deleted
Source

pub fn contains(&self, key: &str) -> bool

Check if a key exists in the cache.

Returns false if the key doesn’t exist or has expired. Note: This does NOT update the LRU access time.

§Arguments
  • key - The key to check.
§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
assert!(!cache.contains("key"));
cache.set("key", "value");
assert!(cache.contains("key"));
Source

pub fn len(&self) -> usize

Get the number of entries in the cache.

Note: This may include expired entries that haven’t been cleaned up yet by lazy expiration or background cleanup.

§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
assert_eq!(cache.len(), 0);
cache.set("key", "value");
assert_eq!(cache.len(), 1);
Source

pub fn is_empty(&self) -> bool

Check if the cache is empty.

§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
assert!(cache.is_empty());
cache.set("key", "value");
assert!(!cache.is_empty());
Source

pub fn clear(&self)

Remove all entries from the cache.

§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
cache.set("key1", "value1");
cache.set("key2", "value2");
cache.clear();
assert!(cache.is_empty());
Source

pub fn stats(&self) -> StatsSnapshot

Get a snapshot of the cache statistics.

Returns a point-in-time snapshot of hits, misses, evictions, etc.

§Example
use in_memory_cache::{Cache, CacheConfig};

let cache = Cache::new(CacheConfig::default());
cache.set("key", "value");
let _ = cache.get("key");        // Hit
let _ = cache.get("missing");    // Miss

let stats = cache.stats();
println!("Hits: {}, Misses: {}", stats.hits, stats.misses);
Source

pub fn cleanup_expired(&self) -> usize

Manually trigger cleanup of expired entries.

Returns the number of entries that were removed. This is useful if you want to control when cleanup happens instead of relying on lazy expiration or background cleanup.

§Example
use in_memory_cache::{Cache, CacheConfig};
use std::time::Duration;

let cache = Cache::new(CacheConfig::default());
cache.set_with_ttl("key", "value", Duration::from_millis(1));
std::thread::sleep(Duration::from_millis(10));
let removed = cache.cleanup_expired();
println!("Removed {} expired entries", removed);
Source

pub fn stats_ref(&self) -> Arc<CacheStats>

Get a reference to the internal statistics counter.

This is useful for integrating with external metrics systems.

Trait Implementations§

Source§

impl Clone for Cache

Source§

fn clone(&self) -> Cache

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Cache

Source§

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

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

impl Default for Cache

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl Freeze for Cache

§

impl RefUnwindSafe for Cache

§

impl Send for Cache

§

impl Sync for Cache

§

impl Unpin for Cache

§

impl UnwindSafe for Cache

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.

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.

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.