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
#![no_std]
use core::borrow::Borrow;
/// Key equivalence trait, to support `Borrow` types as keys.
trait Equivalent<K: ?Sized> {
/// Returns `true` if two values are equivalent, `false` if otherwise.
fn equivalent(&self, k: &K) -> bool;
}
impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
where
Q: Eq,
K: Borrow<Q>,
{
fn equivalent(&self, k: &K) -> bool {
self == k.borrow()
}
}
/// A single key/value slot used in the cache.
#[derive(Clone, PartialEq)]
enum KeyValueSlot<K, V> {
Used((K, V)),
Empty,
}
impl<K, V> KeyValueSlot<K, V> {
/// Check a used slot key for equivalence.
#[cfg_attr(feature = "inline-more", inline)]
fn is_key<Q>(&self, k: &Q) -> bool
where
Q: Equivalent<K> + ?Sized,
{
if let KeyValueSlot::Used(kv) = self {
k.equivalent(&kv.0)
} else {
false
}
}
/// Get the value of a used slot.
#[cfg_attr(feature = "inline-more", inline)]
fn get_value(&self) -> Option<&V> {
if let KeyValueSlot::Used(kv) = self {
Some(&kv.1)
} else {
None
}
}
/// Get the value of a used slot (for mutation).
#[cfg_attr(feature = "inline-more", inline)]
fn get_value_mut(&mut self) -> Option<&mut V> {
if let KeyValueSlot::Used(kv) = self {
Some(&mut kv.1)
} else {
None
}
}
/// Update the value of a used slot.
#[cfg_attr(feature = "inline-more", inline)]
fn update_value(&mut self, v: V) {
if let KeyValueSlot::Used(kv) = self {
kv.1 = v
}
}
}
/// A small, fixed-size, heap-allocated key/value cache with retention management.
pub struct MemoCache<K, V, const SIZE: usize> {
buffer: [KeyValueSlot<K, V>; SIZE],
cursor: usize,
}
impl<K, V, const SIZE: usize> MemoCache<K, V, SIZE>
where
K: Clone + Eq,
V: Clone,
{
/// Create a new cache.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let c = MemoCache::<u32, String, 4>::new();
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn new() -> Self {
Self {
buffer: [const { KeyValueSlot::Empty }; SIZE],
cursor: 0,
}
}
/// Get the (fixed) capacity of the cache.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let c = MemoCache::<u32, String, 8>::new();
///
/// assert_eq!(c.capacity(), 8);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub const fn capacity(&self) -> usize {
SIZE
}
/// Replace slot under cursor and shift cursor position. Returns a reference to the replaced slot value.
fn replace_and_shift(&mut self, k: K, v: V) -> &V {
let s = self
.buffer
.get_mut(self.cursor)
.expect("invalid cursor value");
*s = KeyValueSlot::Used((k, v));
// Move the cursor over the buffer elements sequentially, creating FIFO behavior.
self.cursor = (self.cursor + 1) % SIZE;
// SAFETY: The slot was filled with a key/value above.
unsafe { s.get_value().unwrap_unchecked() }
}
/// Insert a key/value pair.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let mut c = MemoCache::<u32, &str, 4>::new();
///
/// assert_eq!(c.get(&42), None);
///
/// c.insert(42, "The Answer");
///
/// assert_eq!(c.get(&42), Some(&"The Answer"));
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&mut self, k: K, v: V) {
match self.buffer.iter_mut().find(|e| e.is_key(&k)) {
Some(s) => s.update_value(v),
None => {
self.replace_and_shift(k, v);
}
}
}
/// Returns `true` if the cache contains a value for the specified key.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let mut c = MemoCache::<u32, &str, 4>::new();
///
/// assert_eq!(c.contains_key(&42), false);
///
/// c.insert(42, "The Answer");
///
/// assert_eq!(c.contains_key(&42), true);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn contains_key<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Eq + ?Sized,
{
self.buffer.iter().any(|e| e.is_key(k))
}
/// Lookup a cache entry by key.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let mut c = MemoCache::<u32, &str, 4>::new();
///
/// assert_eq!(c.get(&42), None);
///
/// c.insert(42, "The Answer");
///
/// assert_eq!(c.get(&42), Some(&"The Answer"));
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn get<Q>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Eq + ?Sized,
{
self.buffer
.iter()
.find(|e| e.is_key(k))
.map(|e| e.get_value().unwrap())
}
/// Lookup a cache entry by key (for mutation).
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let mut c = MemoCache::<u32, &str, 4>::new();
///
/// c.insert(42, "The Answer");
///
/// if let Some(v) = c.get_mut(&42) {
/// *v = "Another Answer";
/// }
///
/// assert_eq!(c.get(&42), Some(&"Another Answer"));
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Eq + ?Sized,
{
self.buffer
.iter_mut()
.find(|e| e.is_key(k))
.map(|e| e.get_value_mut().unwrap())
}
/// Get the index for a given key, if found.
#[cfg_attr(feature = "inline-more", inline)]
fn get_key_index<Q>(&self, k: &Q) -> Option<usize>
where
K: Borrow<Q>,
Q: Eq + ?Sized,
{
self.buffer.iter().position(|e| e.is_key(k))
}
/// Get a value, or, if it does not exist in the cache, insert it using the value computed by `f`.
/// Returns a reference to the found, or newly inserted value associated with the given key.
/// If a value is inserted, the key is cloned.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let mut c = MemoCache::<u32, &str, 4>::new();
///
/// assert_eq!(c.get(&42), None);
///
/// let v = c.get_or_insert_with(&42, |_| "The Answer");
///
/// assert_eq!(v, &"The Answer");
/// assert_eq!(c.get(&42), Some(&"The Answer"));
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_or_insert_with<F>(&mut self, k: &K, f: F) -> &V
where
F: FnOnce(&K) -> V,
{
if let Some(i) = self.get_key_index(k) {
// SAFETY: The key index was retrieved from a found key.
unsafe { self.buffer[i].get_value().unwrap_unchecked() }
} else {
self.replace_and_shift(k.clone(), f(k))
}
}
/// Clear the cache.
///
/// # Examples
///
/// ```
/// use memo_cache::MemoCache;
///
/// let mut c = MemoCache::<u32, &str, 4>::new();
///
/// assert_eq!(c.get(&42), None);
///
/// c.insert(42, "The Answer");
///
/// assert_eq!(c.get(&42), Some(&"The Answer"));
///
/// c.clear();
///
/// assert_eq!(c.get(&42), None);
///
#[cfg_attr(feature = "inline-more", inline)]
pub fn clear(&mut self) {
self.buffer
.iter_mut()
.for_each(|e| *e = KeyValueSlot::Empty);
self.cursor = 0;
}
}
impl<K, V, const SIZE: usize> Default for MemoCache<K, V, SIZE>
where
K: Clone + Eq,
V: Clone,
{
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests_internal {
use super::*;
#[test]
fn test_new_state() {
const SIZE: usize = 8;
let c = MemoCache::<i32, i32, SIZE>::new();
// Verify cache size.
assert_eq!(c.buffer.len(), SIZE);
assert_eq!(c.capacity(), SIZE);
// All slots should be empty.
assert!(c.buffer.iter().all(|s| s == &KeyValueSlot::Empty));
}
#[test]
fn test_cursor_state() {
let mut c = MemoCache::<i32, i32, 2>::new();
assert_eq!(c.cursor, 0);
c.insert(1, 2);
assert_eq!(c.cursor, 1);
c.insert(3, 4);
assert_eq!(c.cursor, 0);
c.insert(5, 6);
assert_eq!(c.cursor, 1);
c.insert(7, 8);
assert_eq!(c.cursor, 0);
}
}