1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
//! Module providing abstractions to represent an LRUCache.
//!
//! ## Usage
//!
//! ```rust
//! use generational_cache::prelude::*;
//!
//! const CAPACITY: usize = 3;
//!
//! let mut cache = LRUCache::<_, i32, u64, AllocBTreeMap<_, _>>::with_backing_vector(Array::<_, CAPACITY>::new());
//!
//! cache.insert(-1, 1).unwrap();
//! cache.insert(-2, 2).unwrap();
//! cache.insert(-3, 3).unwrap();
//!
//! assert_eq!(cache.least_recent().unwrap(), (&-1, &1));
//! assert_eq!(cache.most_recent().unwrap(), (&-3, &3));
//!
//! assert_eq!(cache.insert(-4, 4).unwrap(), Eviction::Block { key: -1, value: 1});
//!
//! assert_eq!(cache.least_recent().unwrap(), (&-2, &2));
//! assert_eq!(cache.most_recent().unwrap(), (&-4, &4));
//!
//! assert_eq!(cache.insert(-2, 42).unwrap(), Eviction::Value(2));
//!
//! assert_eq!(cache.least_recent().unwrap(), (&-3, &3));
//! assert_eq!(cache.most_recent().unwrap(), (&-2, &42));
//!
//! assert_eq!(cache.remove(&-42).unwrap(), Lookup::Miss);
//! assert_eq!(cache.query(&-42).unwrap(), Lookup::Miss);
//!
//! assert_eq!(cache.query(&-3).unwrap(), Lookup::Hit(&3));
//!
//! assert_eq!(cache.least_recent().unwrap(), (&-4, &4));
//! assert_eq!(cache.most_recent().unwrap(), (&-3, &3));
//!
//! assert_eq!(cache.remove(&-2).unwrap(), Lookup::Hit(42));
//!
//! assert_eq!(cache.query(&-2).unwrap(), Lookup::Miss);
//!
//! // zero capacity LRUCache is unusable
//! let mut cache = LRUCache::<_, i32, u64, AllocBTreeMap<_, _>>::with_backing_vector(Array::<_, 0_usize>::new());
//!
//! match cache.insert(0, 0) {
//! Err(LRUCacheError::ListUnderflow) => {}
//! _ => unreachable!("Wrong error on list underflow."),
//! };
//!
//! ```
use crate::{
cache::{Cache, Eviction},
collections::list::{Link, LinkedList, LinkedListArenaEntry, ListError},
map::Map,
vector::Vector,
};
use core::{
fmt::{Debug, Display},
mem,
};
use super::Lookup;
extern crate alloc;
/// A cache block containing a key value pair.
#[derive(Clone, Copy)]
pub struct Block<K, T> {
pub key: K,
pub value: T,
}
/// Alias representing block entries for storage in a generational arena.
pub type LRUCacheBlockArenaEntry<K, T> = LinkedListArenaEntry<Block<K, T>>;
/// A generational [`Arena`](crate::arena::Arena) backed LRU cache implementation.
///
/// This [`Cache`] implementation always evicts the least-recently-used (LRU) key/value pair. It
/// uses a [`LinkedList`] for storing the underlying cache block entries to maintain the order
/// in which they were inserted into the cache.
///
/// It uses a generational [`Arena`](crate::arena::Arena) for allocating the underlying
/// [`LinkedList`] which stores the cache blocks. It uses a [`Map`] for maintaining the mapping
/// from keys to the nodes storing the respective cache blocks in the [`LinkedList`].
///
/// ### Type parameters
/// - `V: Vector<LRUCacheBlockArenaEntry<K, T>>`
/// Used as the backing vector for the underlying [`Arena`](crate::arena::Arena).
/// - `K`
/// The Key type.
/// - `V`
/// The Value type.
/// - `M: Map<K, Link>`
/// Used to store a mapping from the keys to links in the linked list.
///
pub struct LRUCache<V, K, T, M> {
block_list: LinkedList<V, Block<K, T>>,
block_refs: M,
capacity: usize,
}
impl<V, K, T, M> LRUCache<V, K, T, M>
where
V: Vector<LRUCacheBlockArenaEntry<K, T>>,
M: Map<K, Link>,
{
/// Returns the least recently used key/value pair.
pub fn least_recent(&self) -> Option<(&K, &T)> {
let block = self.block_list.peek_front()?;
Some((&block.key, &block.value))
}
/// Returns the most recently used key/value pair.
pub fn most_recent(&self) -> Option<(&K, &T)> {
let block = self.block_list.peek_back()?;
Some((&block.key, &block.value))
}
}
impl<V, K, T, M> LRUCache<V, K, T, M>
where
V: Vector<LRUCacheBlockArenaEntry<K, T>>,
M: Map<K, Link>,
{
/// Creates an [`LRUCache`] instance with the given the backing [`Vector`] and [`Map`]
/// implementation instances.
pub fn with_backing_vector_and_map(vector: V, map: M) -> Self {
let block_list = LinkedList::with_backing_vector(vector);
let capacity = block_list.capacity();
Self {
block_list,
block_refs: map,
capacity,
}
}
}
impl<V, K, T, M> LRUCache<V, K, T, M>
where
V: Vector<LRUCacheBlockArenaEntry<K, T>>,
M: Map<K, Link> + Default,
{
/// Creates an [`LRUCache`] instance with the given [`Vector`] implementation instance
/// and the default [`Map`] implementation value.
pub fn with_backing_vector(vector: V) -> Self {
Self::with_backing_vector_and_map(vector, M::default())
}
}
impl<V, K, T, M> Default for LRUCache<V, K, T, M>
where
V: Vector<LRUCacheBlockArenaEntry<K, T>> + Default,
M: Map<K, Link> + Default,
{
fn default() -> Self {
Self::with_backing_vector(V::default())
}
}
/// Error type associated with [`LRUCache`] operations.
#[derive(Debug)]
pub enum LRUCacheError<VE, ME> {
/// Used when there is an error on an operation in the underlying list.
ListError(ListError<VE>),
/// Used when attempting to remove elements from the underlying list when its empty.
ListUnderflow,
/// Used when the underlying map and list instances contain an inconsistent view
/// of the entries allocated in the LRUCache
MapListInconsistent,
/// Used when there is an error on an operation in the underlying map..
MapError(ME),
}
impl<VE, ME> Display for LRUCacheError<VE, ME>
where
VE: Debug,
ME: Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{self:?}")
}
}
#[allow(unused)]
impl<V, K, T, M> Cache<K, T> for LRUCache<V, K, T, M>
where
V: Vector<LRUCacheBlockArenaEntry<K, T>>,
M: Map<K, Link>,
K: Copy,
{
type Error = LRUCacheError<V::Error, M::Error>;
fn insert(&mut self, key: K, value: T) -> Result<Eviction<K, T>, Self::Error> {
if let Some(link) = self.block_refs.get(&key) {
self.block_list
.shift_push_back(link)
.ok_or(Self::Error::MapListInconsistent)?;
let block = self
.block_list
.get_mut(link)
.ok_or(Self::Error::MapListInconsistent)?;
return Ok(Eviction::Value(mem::replace(&mut block.value, value)));
}
let eviction = if self.is_maxed() {
let Block { key, value } = self
.block_list
.pop_front()
.ok_or(Self::Error::ListUnderflow)?;
self.block_refs.remove(&key);
Eviction::Block { key, value }
} else {
Eviction::None
};
let link = self
.block_list
.push_back(Block { key, value })
.map_err(Self::Error::ListError)?;
self.block_refs
.insert(key, link)
.map_err(Self::Error::MapError)?;
Ok(eviction)
}
fn remove(&mut self, key: &K) -> Result<Lookup<T>, Self::Error> {
match self.block_refs.remove(key) {
Some(link) => self
.block_list
.remove(&link)
.map(|x| Lookup::Hit(x.value))
.ok_or(Self::Error::MapListInconsistent),
_ => Ok(Lookup::Miss),
}
}
fn shrink(&mut self, new_capacity: usize) -> Result<(), Self::Error> {
if new_capacity >= self.capacity() {
return Ok(());
}
while self.len() > new_capacity {
let Block { key, value } = self
.block_list
.pop_front()
.ok_or(Self::Error::ListUnderflow)?;
self.block_refs.remove(&key);
}
self.capacity = new_capacity;
Ok(())
}
fn reserve(&mut self, additional: usize) -> Result<(), Self::Error> {
self.block_list
.reserve(additional)
.map_err(Self::Error::ListError)?;
self.capacity += additional;
Ok(())
}
fn query(&mut self, key: &K) -> Result<Lookup<&T>, Self::Error> {
match self.block_refs.get(key) {
Some(link) => {
self.block_list
.shift_push_back(link)
.ok_or(Self::Error::MapListInconsistent)?;
self.block_list
.get(link)
.map(|x| Lookup::Hit(&x.value))
.ok_or(Self::Error::MapListInconsistent)
}
_ => Ok(Lookup::Miss),
}
}
fn capacity(&self) -> usize {
self.capacity
}
fn len(&self) -> usize {
self.block_list.len()
}
fn is_empty(&self) -> bool {
self.block_list.is_empty()
}
fn clear(&mut self) -> Result<(), Self::Error> {
self.block_list.clear().map_err(Self::Error::ListError)?;
self.block_refs.clear().map_err(Self::Error::MapError)?;
Ok(())
}
}
#[doc(hidden)]
pub mod tests {
use super::{
Cache, Eviction, LRUCache, LRUCacheBlockArenaEntry, LRUCacheError, Link, Lookup, Map,
Vector,
};
pub fn _test_cache_correctness<VX, VY, M>(zero_capacity_vec: VX, test_vec: VY)
where
VX: Vector<LRUCacheBlockArenaEntry<usize, usize>>,
VY: Vector<LRUCacheBlockArenaEntry<usize, usize>>,
M: Map<usize, Link> + Default,
{
assert_eq!(
zero_capacity_vec.capacity(),
0,
"Zero capacity vector provider yielded vector of non zero capacity."
);
let mut cache = LRUCache::<_, _, _, M>::with_backing_vector(zero_capacity_vec);
assert!(cache.is_empty());
match cache.insert(0, 0) {
Err(LRUCacheError::ListUnderflow) => {}
_ => unreachable!("Wrong error on list underflow."),
};
let mut cache = LRUCache::<_, _, _, M>::with_backing_vector(test_vec);
let capacity = cache.capacity();
assert!(
capacity > 3,
"Too small capacity: {} to run meaningful tests.",
capacity
);
assert!(cache.is_empty());
for i in 0..cache.capacity() {
assert_eq!(cache.insert(i, i).unwrap(), Eviction::None);
}
assert_eq!(cache.least_recent().unwrap(), (&0, &0));
assert_eq!(
cache.insert(capacity, capacity).unwrap(),
Eviction::Block { key: 0, value: 0 }
);
assert_eq!(cache.query(&1).unwrap(), Lookup::Hit(&1));
assert_eq!(cache.least_recent().unwrap(), (&2, &2));
assert_eq!(cache.most_recent().unwrap(), (&1, &1));
assert_eq!(cache.remove(&(capacity + 1)).unwrap(), Lookup::Miss);
assert_eq!(cache.query(&(capacity + 1)).unwrap(), Lookup::Miss);
assert_eq!(
cache.insert(capacity + 1, capacity + 1).unwrap(),
Eviction::Block { key: 2, value: 2 }
);
assert_eq!(
cache.remove(&(capacity + 1)).unwrap(),
Lookup::Hit(capacity + 1)
);
assert_eq!(cache.remove(&(capacity + 1)).unwrap(), Lookup::Miss);
assert_eq!(cache.query(&(capacity + 1)).unwrap(), Lookup::Miss);
assert_eq!(
cache.insert(capacity, capacity + 2).unwrap(),
Eviction::Value(capacity)
);
assert_eq!(cache.most_recent().unwrap(), (&capacity, &(capacity + 2)));
cache.clear().unwrap();
assert!(cache.is_empty());
for i in 0..cache.capacity() {
assert_eq!(cache.insert(i, i).unwrap(), Eviction::None);
}
assert_eq!(cache.least_recent().unwrap(), (&0, &0));
const ADDITIONAL: usize = 5;
let result = cache.reserve(ADDITIONAL);
if result.is_ok() {
let old_len = cache.len();
for i in 0..ADDITIONAL {
assert_eq!(cache.insert(i + old_len, i).unwrap(), Eviction::None);
}
}
let old_capacity = cache.capacity();
cache.shrink(0).unwrap();
assert!(cache.is_maxed());
match cache.insert(0, 0) {
Err(LRUCacheError::ListUnderflow) => {}
_ => unreachable!("Wrong error on list underflow."),
};
assert!(cache.is_empty());
cache.reserve(old_capacity).unwrap();
cache.shrink(old_capacity).unwrap();
assert_eq!(cache.capacity(), old_capacity);
for i in 0..cache.capacity() {
assert_eq!(cache.insert(i, i).unwrap(), Eviction::None);
}
cache.clear().unwrap();
assert!(cache.is_empty());
}
}