FifoCache

Struct FifoCache 

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

A FIFO cache with TTL support.

This cache maintains insertion order and evicts the oldest entries when the maximum size is reached. Entries also expire after the specified TTL.

Note that:

  • reinserting an existing entry will not move it back to the front
  • the maximum capacity may very briefly be exceeded by 1

Implementations§

Source§

impl<K, V> FifoCache<K, V>
where K: Clone + Eq + Hash, V: Clone,

Source

pub fn new(max_size: usize, default_ttl: Duration) -> Self

Creates a new FIFO cache with the specified maximum size and default TTL.

§Arguments
  • max_size - Maximum number of entries the cache can hold
  • default_ttl - Default time-to-live for cache entries
Examples found in repository?
examples/basic_usage.rs (lines 7-11)
5fn main() {
6  // Create a cache with capacity 1000 and 5-minute TTL
7  let mut cache = FifoCache::new(
8    1000,
9    #[cfg(feature = "ttl")]
10    Duration::from_secs(300)
11  );
12  
13  // Insert some values
14  cache.insert("user:123", "John Doe");
15  cache.insert("user:456", "Jane Smith");
16  cache.insert("config:timeout", "30");
17  
18  // Retrieve values
19  if let Some(name) = cache.get(&"user:123") {
20    println!("Found user: {}", name);
21  }
22  
23  // Cache will automatically evict oldest entries when full
24  // and expire entries after 5 minutes
25  
26  println!("Cache size: {}/{}", cache.len(), cache.max_size());
27  
28  #[cfg(feature = "ttl")]
29  // Manual cleanup of expired entries
30  cache.cleanup_expired();
31}
Source

pub fn get<Q>(&self, key: &Q) -> Option<&V>
where K: Borrow<Q>, Q: ?Sized + Hash + Eq,

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

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

Some(&V) if the key exists and hasn’t expired, None otherwise.

§Example

With TTL enabled:

use fifo_cache::FifoCache;
use std::time::Duration;

let mut cache = FifoCache::new(100, Duration::from_secs(60));
cache.insert("my_key", "my_value");
let value = cache.get(&"my_key");
assert_eq!(value, Some(&"my_value"));

Without TTL:

use fifo_cache::FifoCache;

let mut cache = FifoCache::new(100);
cache.insert("my_key", "my_value");
assert_eq!(cache.get(&"my_key"), Some(&"my_value"));
Examples found in repository?
examples/basic_usage.rs (line 19)
5fn main() {
6  // Create a cache with capacity 1000 and 5-minute TTL
7  let mut cache = FifoCache::new(
8    1000,
9    #[cfg(feature = "ttl")]
10    Duration::from_secs(300)
11  );
12  
13  // Insert some values
14  cache.insert("user:123", "John Doe");
15  cache.insert("user:456", "Jane Smith");
16  cache.insert("config:timeout", "30");
17  
18  // Retrieve values
19  if let Some(name) = cache.get(&"user:123") {
20    println!("Found user: {}", name);
21  }
22  
23  // Cache will automatically evict oldest entries when full
24  // and expire entries after 5 minutes
25  
26  println!("Cache size: {}/{}", cache.len(), cache.max_size());
27  
28  #[cfg(feature = "ttl")]
29  // Manual cleanup of expired entries
30  cache.cleanup_expired();
31}
Source

pub fn insert(&mut self, key: K, value: V)

Inserts a key-value pair into the cache.

If the key already exists, its value is updated and TTL is refreshed. If the cache is at capacity, the oldest entry is evicted.

§Arguments
  • key - The key to insert
  • value - The value to associate with the key
Examples found in repository?
examples/basic_usage.rs (line 14)
5fn main() {
6  // Create a cache with capacity 1000 and 5-minute TTL
7  let mut cache = FifoCache::new(
8    1000,
9    #[cfg(feature = "ttl")]
10    Duration::from_secs(300)
11  );
12  
13  // Insert some values
14  cache.insert("user:123", "John Doe");
15  cache.insert("user:456", "Jane Smith");
16  cache.insert("config:timeout", "30");
17  
18  // Retrieve values
19  if let Some(name) = cache.get(&"user:123") {
20    println!("Found user: {}", name);
21  }
22  
23  // Cache will automatically evict oldest entries when full
24  // and expire entries after 5 minutes
25  
26  println!("Cache size: {}/{}", cache.len(), cache.max_size());
27  
28  #[cfg(feature = "ttl")]
29  // Manual cleanup of expired entries
30  cache.cleanup_expired();
31}
Source

pub fn insert_lazy<Kinto: Into<K>, Vinto: Into<V>>( &mut self, key: Kinto, value: Vinto, )

Inserts a key-value pair into the cache using types that can be converted into the key and value types.

This is a convenience wrapper around insert that accepts any types implementing Into<K> and Into<V>. Note that using only insert_lazy prevents type inference, so you’ll need to explicitly specify the cache types:

use fifo_cache::FifoCache;
use std::time::Duration;
 
// With insert - types are inferred
let mut cache = FifoCache::new(100, Duration::from_secs(60));
cache.insert("key", "value");  // FifoCache<&str, &str>

// With insert_lazy - types must be specified  
let mut cache: FifoCache<String, String> = FifoCache::new(100, Duration::from_secs(60));
cache.insert_lazy("key", "value");  // &str -> String conversion
Source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
where K: Borrow<Q>, Q: ?Sized + Hash + Eq,

Removes a key from the cache.

§Arguments
  • key - The key to remove
§Returns

Some(V) if the key existed, None otherwise.

Source

pub fn len(&self) -> usize

Returns the current number of entries in the cache.

Examples found in repository?
examples/basic_usage.rs (line 26)
5fn main() {
6  // Create a cache with capacity 1000 and 5-minute TTL
7  let mut cache = FifoCache::new(
8    1000,
9    #[cfg(feature = "ttl")]
10    Duration::from_secs(300)
11  );
12  
13  // Insert some values
14  cache.insert("user:123", "John Doe");
15  cache.insert("user:456", "Jane Smith");
16  cache.insert("config:timeout", "30");
17  
18  // Retrieve values
19  if let Some(name) = cache.get(&"user:123") {
20    println!("Found user: {}", name);
21  }
22  
23  // Cache will automatically evict oldest entries when full
24  // and expire entries after 5 minutes
25  
26  println!("Cache size: {}/{}", cache.len(), cache.max_size());
27  
28  #[cfg(feature = "ttl")]
29  // Manual cleanup of expired entries
30  cache.cleanup_expired();
31}
Source

pub fn is_empty(&self) -> bool

Returns true if the cache is empty.

Source

pub fn cleanup_expired(&mut self)

Removes all expired entries from the cache.

Examples found in repository?
examples/basic_usage.rs (line 30)
5fn main() {
6  // Create a cache with capacity 1000 and 5-minute TTL
7  let mut cache = FifoCache::new(
8    1000,
9    #[cfg(feature = "ttl")]
10    Duration::from_secs(300)
11  );
12  
13  // Insert some values
14  cache.insert("user:123", "John Doe");
15  cache.insert("user:456", "Jane Smith");
16  cache.insert("config:timeout", "30");
17  
18  // Retrieve values
19  if let Some(name) = cache.get(&"user:123") {
20    println!("Found user: {}", name);
21  }
22  
23  // Cache will automatically evict oldest entries when full
24  // and expire entries after 5 minutes
25  
26  println!("Cache size: {}/{}", cache.len(), cache.max_size());
27  
28  #[cfg(feature = "ttl")]
29  // Manual cleanup of expired entries
30  cache.cleanup_expired();
31}
Source

pub fn clear(&mut self)

Clears all entries from the cache.

Source

pub fn max_size(&self) -> usize

Returns the maximum capacity of the cache.

Examples found in repository?
examples/basic_usage.rs (line 26)
5fn main() {
6  // Create a cache with capacity 1000 and 5-minute TTL
7  let mut cache = FifoCache::new(
8    1000,
9    #[cfg(feature = "ttl")]
10    Duration::from_secs(300)
11  );
12  
13  // Insert some values
14  cache.insert("user:123", "John Doe");
15  cache.insert("user:456", "Jane Smith");
16  cache.insert("config:timeout", "30");
17  
18  // Retrieve values
19  if let Some(name) = cache.get(&"user:123") {
20    println!("Found user: {}", name);
21  }
22  
23  // Cache will automatically evict oldest entries when full
24  // and expire entries after 5 minutes
25  
26  println!("Cache size: {}/{}", cache.len(), cache.max_size());
27  
28  #[cfg(feature = "ttl")]
29  // Manual cleanup of expired entries
30  cache.cleanup_expired();
31}
Source

pub fn set_max_size(&mut self, max_size: usize, prune: bool)

Sets the maximum capacity of the cache.

§Arguments
  • max_size - The new maximum number of entries the cache can hold
  • prune - Whether or not to immediately prune the excess number of entries, in case the update causes the cache to be above capacity
Source

pub fn default_ttl(&self) -> Duration

Returns the default TTL for cache entries.

Source

pub fn set_default_ttl(&mut self, default_ttl: Duration)

Sets the default TTL for cache entries. Note that this will only affect entries that get inserted or updated after the change. Existing entries will keep their TTL until they expire.

§Arguments
  • default_ttl - The new default time-to-live for cache entries

Trait Implementations§

Source§

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

Source§

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

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

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

Source§

fn default() -> Self

Creates a cache with capacity 1000 and TTL of 5 minutes. This is extremely arbitrary and you most likely want to use your own, use-case-adjusted settings rather than this default.

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

impl<K, V> UnwindSafe for FifoCache<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> 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, 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.