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
//! A cache based on the SIEVE eviction algorithm.
//!
//! # Usage
//!
//! ```rust
//! use sieve_cache::SieveCache;
//!
//! // Create a new cache with a capacity of 100000.
//! let mut cache: SieveCache<String, String> = SieveCache::new(100000).unwrap();
//!
//! // Insert key/value pairs into the cache.
//! cache.insert("foo".to_string(), "foocontent".to_string());
//! cache.insert("bar".to_string(), "barcontent".to_string());
//!
//! // Remove an entry from the cache.
//! cache.remove("bar");
//!
//! // Retrieve a value from the cache, returning `None` or a reference to the value.
//! assert_eq!(cache.get("foo"), Some(&"foocontent".to_string()));
//!
//! // Check if a key is in the cache.
//! assert_eq!(cache.contains_key("bar"), false);
//!
//! // Get a mutable reference to a value in the cache.
//! if let Some(value) = cache.get_mut("foo") {
//! *value = "newfoocontent".to_string();
//! }
//!
//! // Return the number of cached values.
//! assert_eq!(cache.len(), 1);
//!
//! // Return the capacity of the cache.
//! assert_eq!(cache.capacity(), 100000);
//! ```
use std::borrow::Borrow;
use std::hash::Hash;
use std::{collections::HashMap, ptr::NonNull};
struct Node<K: Eq + Hash + Clone, V> {
key: K,
value: V,
prev: Option<NonNull<Node<K, V>>>,
next: Option<NonNull<Node<K, V>>>,
visited: bool,
}
impl<K: Eq + Hash + Clone, V> Node<K, V> {
fn new(key: K, value: V) -> Self {
Self {
key,
value,
prev: None,
next: None,
visited: false,
}
}
}
/// A cache based on the SIEVE eviction algorithm.
pub struct SieveCache<K: Eq + Hash + Clone, V> {
map: HashMap<K, Box<Node<K, V>>>,
head: Option<NonNull<Node<K, V>>>,
tail: Option<NonNull<Node<K, V>>>,
hand: Option<NonNull<Node<K, V>>>,
capacity: usize,
len: usize,
}
impl<K: Eq + Hash + Clone, V> SieveCache<K, V> {
/// Create a new cache with the given capacity.
pub fn new(capacity: usize) -> Result<Self, &'static str> {
if capacity == 0 {
return Err("capacity must be greater than 0");
}
Ok(Self {
map: HashMap::with_capacity(capacity),
head: None,
tail: None,
hand: None,
capacity,
len: 0,
})
}
/// Return the capacity of the cache.
#[inline]
pub fn capacity(&self) -> usize {
self.capacity
}
/// Return the number of cached values.
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Return `true` when no values are currently cached.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Return `true` if there is a value in the cache mapped to by `key`.
#[inline]
pub fn contains_key<Q: ?Sized>(&mut self, key: &Q) -> bool
where
Q: Hash + Eq,
K: Borrow<Q>,
{
self.map.contains_key(key)
}
/// Get an immutable reference to the value in the cache mapped to by `key`.
///
/// If no value exists for `key`, this returns `None`.
pub fn get<Q: ?Sized>(&mut self, key: &Q) -> Option<&V>
where
Q: Hash + Eq,
K: Borrow<Q>,
{
let node_ = self.map.get_mut(key)?;
node_.visited = true;
Some(&node_.value)
}
/// Get a mutable reference to the value in the cache mapped to by `key`.
///
/// If no value exists for `key`, this returns `None`.
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
where
Q: Hash + Eq,
K: Borrow<Q>,
{
let node_ = self.map.get_mut(key)?;
node_.visited = true;
Some(&mut node_.value)
}
/// Map `key` to `value` in the cache, possibly evicting old entries.
///
/// This method returns `true` when this is a new entry, and `false` if an existing entry was
/// updated.
pub fn insert(&mut self, key: K, value: V) -> bool {
let node = self.map.get_mut(&key);
if let Some(node_) = node {
node_.value = value;
return true;
}
if self.len >= self.capacity {
self.evict();
}
let node = Box::new(Node::new(key.clone(), value));
self.add_node(NonNull::from(node.as_ref()));
self.map.insert(key, node);
debug_assert!(self.len < self.capacity);
self.len += 1;
false
}
/// Remove the cache entry mapped to by `key`.
///
/// This method returns the value removed from the cache. If `key` did not map to any value,
/// then this returns `None`.
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Eq + Hash,
{
let node_ = self.map.get_mut(key)?;
let node__ = NonNull::from(node_.as_ref());
let value = self.map.remove(key).map(|node| node.value);
self.remove_node(node__);
debug_assert!(self.len > 0);
self.len -= 1;
value
}
fn add_node(&mut self, mut node: NonNull<Node<K, V>>) {
unsafe {
node.as_mut().next = self.head;
node.as_mut().prev = None;
if let Some(mut head) = self.head {
head.as_mut().prev = Some(node);
}
}
self.head = Some(node);
if self.tail.is_none() {
self.tail = self.head;
}
}
fn remove_node(&mut self, node: NonNull<Node<K, V>>) {
unsafe {
if let Some(mut prev) = node.as_ref().prev {
prev.as_mut().next = node.as_ref().next;
} else {
self.head = node.as_ref().next;
}
if let Some(mut next) = node.as_ref().next {
next.as_mut().prev = node.as_ref().prev;
} else {
self.tail = node.as_ref().prev;
}
}
}
fn evict(&mut self) {
let mut node = self.hand.or(self.tail);
while node.is_some() {
let mut node_ = node.unwrap();
unsafe {
if !node_.as_ref().visited {
break;
}
node_.as_mut().visited = false;
if node_.as_ref().prev.is_some() {
node = node_.as_ref().prev;
} else {
node = self.tail;
}
}
}
if let Some(node_) = node {
unsafe {
self.hand = node_.as_ref().prev;
self.map.remove(&node_.as_ref().key);
}
self.remove_node(node_);
debug_assert!(self.len > 0);
self.len -= 1;
}
}
}
#[test]
fn test() {
let mut cache = SieveCache::new(3).unwrap();
cache.insert("foo".to_string(), "foocontent".to_string());
cache.insert("bar".to_string(), "barcontent".to_string());
cache.remove("bar");
cache.insert("bar2".to_string(), "bar2content".to_string());
cache.insert("bar3".to_string(), "bar3content".to_string());
assert_eq!(cache.get("foo"), Some(&"foocontent".to_string()));
assert_eq!(cache.get("bar"), None);
assert_eq!(cache.get("bar2"), Some(&"bar2content".to_string()));
assert_eq!(cache.get("bar3"), Some(&"bar3content".to_string()));
}