kevy_store/lib.rs
1//! kevy-store — the keyspace.
2//!
3//! A single-threaded, multi-type keyspace with lazy expiration. Each Redis data
4//! type is backed by a modern `std` structure — behaviour-compatible, but **not**
5//! Redis's legacy encodings:
6//!
7//! | Type | Backing structure |
8//! |------|-------------------|
9//! | String | `Vec<u8>` |
10//! | Hash / Set | `HashMap` / `HashSet` (hashbrown Swiss table) |
11//! | List | `VecDeque` (ring buffer, O(1) ends) |
12//! | Sorted set | `HashMap` + `BTreeSet<(score, member)>` (a B-tree, not a skiplist) |
13//!
14//! Wrong-type access returns [`StoreError::WrongType`]. The API is `&mut self`
15//! and lock-free, so a thread-per-core runtime ([kevy-rt]) can own one shard per
16//! core with no locking. Part of the [kevy] key–value server.
17//!
18//! `maxmemory` enforcement + 8 eviction policies live in [`evict`]; toggle via
19//! [`Store::set_max_memory`]. With `maxmemory == 0` (the default) the hot-path
20//! cost collapses to a single predicted-not-taken branch, matching the
21//! "unlimited" mode in Redis byte-for-byte.
22//!
23//! [kevy]: https://crates.io/crates/kevy
24//! [kevy-rt]: https://crates.io/crates/kevy-rt
25//!
26//! # Example
27//!
28//! ```
29//! use kevy_store::Store;
30//!
31//! use std::borrow::Cow;
32//! let mut s = Store::new();
33//! s.set(b"greeting", b"hello".to_vec(), None, false, false);
34//! assert_eq!(s.get(b"greeting").unwrap(), Some(Cow::Borrowed(&b"hello"[..])));
35//!
36//! s.hset(b"user:1", &[(b"name".to_vec(), b"alice".to_vec())]).unwrap();
37//! assert_eq!(s.hget(b"user:1", b"name").unwrap(), Some(&b"alice"[..]));
38//!
39//! // A string command on a hash key is a type error, as in Redis.
40//! assert_eq!(s.get(b"user:1"), Err(kevy_store::StoreError::WrongType));
41//! ```
42#![forbid(unsafe_code)]
43
44mod accounting;
45mod clock;
46mod entry;
47pub mod evict;
48pub mod expire;
49pub use expire::ExpireStats;
50pub(crate) use entry::Entry;
51mod hash;
52mod keyspace;
53mod list;
54mod set;
55mod small_set;
56pub use small_set::{SmallSetData, SmallSetIter};
57mod small_hash;
58pub use small_hash::{SmallHashData, SmallHashIter};
59mod small_list;
60pub use small_list::{SmallListData, SmallListIter};
61mod small_zset;
62pub use small_zset::{SmallZSetData, SmallZSetIter};
63mod snapshot;
64pub use snapshot::SnapshotView;
65mod stream;
66mod string;
67mod util;
68mod value;
69mod zset;
70pub use stream::{
71 AutoclaimResult, ConsumerGroup, ConsumerState, EntryBatch, GroupCreateMode,
72 LoadedGroup, LoadedPelEntry, LoadedStreamEntry, PelEntry, PendingExtended,
73 PendingExtendedRow, PendingSummary, ReadGroupId, StreamData, StreamId, StreamIdError,
74 XAddIdSpec, XClaimOpts, now_unix_ms, parse_explicit_id, parse_range_end,
75 parse_range_start, parse_xadd_id,
76};
77pub use string::GetReply;
78pub use util::glob_match;
79pub use value::*;
80
81pub(crate) use clock::{deadline_at, now_ns, pack_deadline, remaining_ms};
82use kevy_map::KevyMap;
83
84/// Feed kevy's monotonic clock on `wasm32-unknown-unknown`, which has no
85/// `Instant`. The embedding host advances time (ns since an arbitrary fixed
86/// epoch, e.g. `Date.now() * 1e6`) before TTL-sensitive ops and once per
87/// reaper tick. No-op concept on native targets, where the OS clock is the
88/// source — hence wasm-only.
89#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
90pub use clock::set_clock_ns;
91/// Feed kevy's wall clock (Unix-epoch millis, e.g. `Date.now()`) on
92/// `wasm32-unknown-unknown`, where `SystemTime::now()` traps. Used by `XADD`
93/// auto-IDs and `EXPIREAT`/`PEXPIREAT`.
94#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
95pub use clock::set_wall_clock_ms;
96
97
98/// Outcome of [`Store::rename`] — three-way result so the dispatch
99/// layer can pick the right RESP frame (`+OK` / `-ERR no such key` /
100/// `:0` for `RENAMENX`-with-existing-dst).
101#[derive(Debug, PartialEq, Eq)]
102pub enum RenameOutcome {
103 /// Source removed, destination created (overwriting any prior dst).
104 Renamed,
105 /// Source key doesn't exist.
106 NoSuchSrc,
107 /// `RENAMENX` only — destination already exists, no rename done.
108 DstExists,
109}
110
111/// Operation errors surfaced to the command layer.
112#[derive(Debug, PartialEq, Eq)]
113pub enum StoreError {
114 /// Key holds a different type than the command expects.
115 WrongType,
116 /// Value is not a base-10 integer (INCR family).
117 NotInteger,
118 /// Result would overflow `i64`.
119 Overflow,
120 /// Index outside the collection (LSET).
121 OutOfRange,
122 /// Key does not exist where the command requires one (LSET).
123 NoSuchKey,
124 /// Value is not a valid float (INCRBYFLOAT).
125 NotFloat,
126 /// `maxmemory` would be exceeded and the active eviction policy is
127 /// [`EvictionPolicy::NoEviction`]. Surfaces as Redis's classic OOM error
128 /// at the RESP layer.
129 OutOfMemory,
130}
131
132/// Maxmemory eviction policy. Mirror of `kevy_config::EvictionPolicy` —
133/// duplicated here so `kevy-store` stays a leaf crate (no `kevy-config` dep).
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
135pub enum EvictionPolicy {
136 /// Refuse writes once `maxmemory` is hit. Default.
137 #[default]
138 NoEviction,
139 /// Approximated LRU across all keys.
140 AllKeysLru,
141 /// Approximated LFU across all keys.
142 AllKeysLfu,
143 /// Random key across all keys.
144 AllKeysRandom,
145 /// Approximated LRU across keys with a TTL.
146 VolatileLru,
147 /// Approximated LFU across keys with a TTL.
148 VolatileLfu,
149 /// Random key from those with a TTL.
150 VolatileRandom,
151 /// Key with the shortest remaining TTL.
152 VolatileTtl,
153}
154
155impl EvictionPolicy {
156 /// Whether the policy ranks candidates by LRU clock (read-touches matter).
157 #[inline]
158 pub fn uses_lru(self) -> bool {
159 matches!(self, Self::AllKeysLru | Self::VolatileLru)
160 }
161
162 /// Whether the policy ranks candidates by LFU counter (read-touches and
163 /// log-counter increments matter).
164 #[inline]
165 pub fn uses_lfu(self) -> bool {
166 matches!(self, Self::AllKeysLfu | Self::VolatileLfu)
167 }
168
169 /// Whether the policy restricts eviction to keys that carry a TTL.
170 #[inline]
171 pub fn is_volatile(self) -> bool {
172 matches!(
173 self,
174 Self::VolatileLru | Self::VolatileLfu | Self::VolatileRandom | Self::VolatileTtl
175 )
176 }
177}
178
179/// A single-database keyspace.
180///
181/// The keyspace map is a [`KevyMap`] — a pure-Rust open-addressing Swiss
182/// table tuned for kevy's per-shard, single-trust-domain keyspace. The
183/// hasher is [`kevy_hash::KevyHash`] (one-call inlinable; no DoS hardening
184/// since the shard is single-threaded with no cross-trust keys). Owning the
185/// table also exposes bucket addresses for software prefetch on the batch
186/// driver.
187#[derive(Default)]
188pub struct Store {
189 pub(crate) map: KevyMap<SmallBytes, Entry>,
190 /// Coarse cached monotonic clock (ns since [`epoch`]), refreshed by the
191 /// reactor loop / reaper tick via [`Self::refresh_clock`]. Lazy expiry on
192 /// the read path (`live_entry`) compares deadlines against this instead of
193 /// calling `Instant::now()` per access — the Redis cached-`mstime` model.
194 /// `0` (the `Default`) reads as "epoch" → keys look live until the first
195 /// refresh, the safe direction (expires at most one refresh-interval late,
196 /// never early — writes stamp deadlines from a *fresh* clock).
197 pub(crate) cached_ns: u64,
198 /// Whether lazy expiry trusts `Self::cached_ns` (set by a reactor/reaper
199 /// that calls [`Self::refresh_clock`]) instead of reading a fresh clock per
200 /// access. Enabled by the server reactor and the embedded background
201 /// reaper; left `false` (the `Default`) for manual-reaper / bare-`Store`
202 /// use, where nothing refreshes the cache so each access reads fresh —
203 /// preserving "lazy expiry works without an explicit tick".
204 pub(crate) cached_clock: bool,
205 /// Live byte estimate (dynamic per-entry weights + [`ENTRY_OVERHEAD`] per
206 /// key). Compared against [`Self::maxmemory`] to drive eviction.
207 pub(crate) used_memory: u64,
208 /// Soft byte ceiling. `0` = unlimited; the entire accounting + eviction
209 /// machinery short-circuits to a single not-taken branch in that case.
210 pub(crate) maxmemory: u64,
211 /// Active eviction policy. Only consulted when `used_memory > maxmemory`.
212 pub(crate) eviction_policy: EvictionPolicy,
213 /// Total keys evicted by [`Self::try_evict_after_write`] — surfaced via
214 /// `INFO memory` / `MEMORY STATS`.
215 pub(crate) evictions_total: u64,
216 /// Monotonic access counter; the upper 32 bits are unused, the lower 32
217 /// stamp `Entry::lru_clock` on each access while eviction is enabled.
218 pub(crate) clock_counter: u64,
219 /// `used_memory` peak across the shard's lifetime; surfaced as
220 /// `used_memory_peak` in `INFO memory`.
221 pub(crate) used_memory_peak: u64,
222 /// Keys expired since startup (lazy reap path AND
223 /// [`Self::tick_expire`]). Surfaced via `INFO keyspace` / `MEMORY STATS`
224 /// once those fields land.
225 pub(crate) expired_keys_total: u64,
226 /// Count of live keys carrying a TTL — the size of Redis's "expire set"
227 /// (`INFO keyspace`'s `expires=`). Maintained in O(1) at every TTL
228 /// transition (`insert_entry` / `remove_entry` deltas + the in-place
229 /// EXPIRE / PERSIST / SET sites) so the gauge never pays an O(n) keyspace
230 /// scan; [`Self::ttl_pending_count`] is the O(n) ground truth used to
231 /// assert this counter never drifts.
232 pub(crate) expires: u64,
233 /// `WATCH` version counters — present only for keys that have been
234 /// `WATCH`-ed at least once. [`Self::record_watch`] inserts the entry
235 /// (version 0 = "never written since first watch"); every subsequent
236 /// write on this shard calls [`Self::bump_if_watched`] which increments
237 /// only if the key is present in the map. Keys never `WATCH`-ed pay
238 /// one empty-map hashmap lookup per write (~10 ns).
239 ///
240 /// The map grows monotonically — entries are never evicted, even
241 /// when no conn is currently watching the key. For high-key-churn
242 /// workloads this can become a memory item; v1.x acceptable since
243 /// the entry is `Vec<u8>` + `u64` (~ 30 B + key length) and only
244 /// touched on writes / WATCH calls.
245 pub(crate) watch_versions: std::collections::HashMap<Vec<u8>, u64>,
246 /// Optional handle to the runtime's bio thread (v1.25 A.3). Set by
247 /// `kevy-rt::Runtime::run` via [`Self::set_bio_drop_sender`] before
248 /// the shard reactor loop starts. `None` = inline drop (bare-Store
249 /// embedders, snapshots-loader programs, the test harness — anything
250 /// without a kevy-rt runtime around it). Reads on the hot path are
251 /// one `Option::as_ref` branch; the steady-state inline-drop path
252 /// pays nothing beyond that branch.
253 pub(crate) bio_drop_sender: Option<value::BioDropSender>,
254 /// v1.25 A.2 batch-send buffer. Heavy `Value`s displaced by SET
255 /// overwrites accumulate here instead of paying one mpsc send per
256 /// drop; flushed in one `mpsc::Sender::send` at the end of every
257 /// reactor iteration (via [`Self::flush_pending_drops`], invoked
258 /// from `kevy-rt`'s epoll + io_uring reactor loops before the AOF
259 /// fsync window). Amortising the channel cost over N drops lets
260 /// the heap-heavy threshold sit at 1 KB — small enough that the
261 /// Axis I 256 B – 16 KB SET tail benefits, big enough that
262 /// sub-µs small-class drops still go inline (the push + flush
263 /// branch would cost more than the inline free).
264 ///
265 /// **Latency window**: drops sit in this buffer ≤ one reactor
266 /// iteration (10s of µs at busy-poll, ≤ park-timeout at idle —
267 /// 50 ms by default). On a reactor with no traffic the buffer
268 /// stays small (no new SETs to displace anything); on a reactor
269 /// with sustained writes the per-iter flush fires fast enough
270 /// that worst-case stall is bounded by `MAX_PENDING_DROPS`.
271 ///
272 /// **Bounded growth**: at `MAX_PENDING_DROPS` items the
273 /// `maybe_offload_drop` path force-flushes — protects against
274 /// pathological "thousand SETs in one iter never flush" cases
275 /// (would otherwise hold thousands of Box<Value>s in RAM until
276 /// the iter ends).
277 pub(crate) pending_drops: Vec<Box<Value>>,
278}
279
280/// Maximum [`Store::pending_drops`] depth before forcing a flush
281/// inside `maybe_offload_drop` (rather than waiting for the reactor's
282/// per-iter `flush_pending_drops`). Caps memory held in the batch
283/// buffer at ≤ 64 × sizeof(Box<Value>) (≤ 512 B of pointers + whatever
284/// the boxed payloads weigh — which we WANT to ship anyway, since
285/// holding the bio-bound batch defeats the point of off-reactor frees).
286/// 64 picked as: amortises mpsc send cost (~few hundred ns) across
287/// enough drops that per-drop overhead is ≤ 10 ns, while staying small
288/// enough that worst-case bunch-up latency at the bio thread is bounded.
289pub(crate) const MAX_PENDING_DROPS: usize = 64;
290
291impl Store {
292 pub fn new() -> Self {
293 Store::default()
294 }
295
296 /// Refresh the coarse cached clock (`Self::cached_ns`) from a single
297 /// `Instant::now()`. Call once per reactor-loop batch / reaper tick; the
298 /// per-access read path then skips its own clock read. Lazy expiry is
299 /// coarse to this cadence (a key expires ≤ one refresh-interval late,
300 /// never early — writes stamp deadlines from a fresh clock).
301 #[inline]
302 pub fn refresh_clock(&mut self) {
303 self.cached_ns = now_ns();
304 }
305
306 /// Enable/disable trusting the cached clock for lazy expiry (see
307 /// `Self::cached_ns`). Call with `true` only when something refreshes the
308 /// clock regularly (the server reactor per batch, the embedded background
309 /// reaper per tick); leave `false` for manual-reaper mode. Seeds the cache
310 /// when enabling so the first access is accurate.
311 #[inline]
312 pub fn set_cached_clock(&mut self, on: bool) {
313 self.cached_clock = on;
314 if on {
315 self.refresh_clock();
316 }
317 }
318
319 /// Install (or clear, with `maxmemory == 0`) the eviction limit and
320 /// policy. Cheap; safe to call repeatedly (e.g. on `CONFIG SET`).
321 #[inline]
322 pub fn set_max_memory(&mut self, maxmemory: u64, policy: EvictionPolicy) {
323 self.maxmemory = maxmemory;
324 self.eviction_policy = policy;
325 }
326
327 /// Install the runtime's bio-drop channel (v1.25 A.3 + A.2). Called
328 /// once from `kevy-rt::Runtime::run` per shard before the reactor
329 /// loop starts. After install, [`Self::maybe_offload_drop`] (invoked
330 /// from the SET overwrite fast path) accumulates oversize `Value`s
331 /// into a per-shard batch; the reactor calls
332 /// [`Self::flush_pending_drops`] at the end of every iter to ship
333 /// the batch in one mpsc send. Bounded the Axis I 10 KB SET p999/max
334 /// blow-up that synchronous `Box::<[u8]>::drop` of a jemalloc
335 /// large-class slot caused (see `kevy_rt::bio`).
336 #[inline]
337 pub fn set_bio_drop_sender(&mut self, sender: value::BioDropSender) {
338 self.bio_drop_sender = Some(sender);
339 }
340
341 /// Accumulate `old` into the per-shard bio-drop batch buffer
342 /// ([`Store::pending_drops`]) if it's heap-heavy AND a bio channel
343 /// is installed. Otherwise drop inline. The hot path is one branch
344 /// on `bio_drop_sender.is_none()` followed by the variant-cheap
345 /// [`Value::is_heap_heavy`] check; for the `Value::Str(SmallBytes)`
346 /// steady state of typical bench shapes the inline-drop path is
347 /// preserved unchanged.
348 ///
349 /// **v1.25 A.2 batch model**: per-send mpsc cost (atomic +
350 /// cross-thread cacheline) is amortised across the batch by
351 /// [`Self::flush_pending_drops`], which the reactor calls once per
352 /// iter. Force-flushes here when the buffer hits
353 /// [`MAX_PENDING_DROPS`] to bound RAM in-flight.
354 #[inline]
355 pub(crate) fn maybe_offload_drop(&mut self, old: Value) {
356 if self.bio_drop_sender.is_none() {
357 // No channel (bare Store / embedded reaper / tests): the
358 // Value falls out of scope and drops inline. Same
359 // behaviour as v1.24.
360 drop(old);
361 return;
362 }
363 if !old.is_heap_heavy() {
364 // Under-threshold: jemalloc small-class free is sub-µs.
365 // The Vec::push + force-flush branch costs more than the
366 // inline free for this size — leave it inline.
367 drop(old);
368 return;
369 }
370 self.pending_drops.push(Box::new(old));
371 if self.pending_drops.len() >= MAX_PENDING_DROPS {
372 self.flush_pending_drops();
373 }
374 }
375
376 /// Ship the per-shard bio-drop batch buffer to the bio thread in
377 /// one mpsc send. Called from `kevy-rt`'s reactor loop at the end
378 /// of every iteration (both the epoll `Shard::run` and the io_uring
379 /// `Shard::run_uring` paths, just before the AOF fsync window so a
380 /// pending fsync stall doesn't pin a batch-ful of heavy values in
381 /// per-shard memory).
382 ///
383 /// Empty-buffer fast path: zero work, predictable not-taken
384 /// branch. Reactor calls this unconditionally per iter; the steady-
385 /// state cost for a no-SET-overwrite iter is one length check.
386 ///
387 /// `SendError` here means the bio thread has exited (shutdown
388 /// territory — `Runtime::run` has dropped its sender AFTER the
389 /// shard threads joined). Drop the batch inline; the `SendError`
390 /// payload carries the `Vec` back so its `Box<Value>`s run their
391 /// Drop here, preserving correctness.
392 #[inline]
393 pub fn flush_pending_drops(&mut self) {
394 if self.pending_drops.is_empty() {
395 return;
396 }
397 let tx = match self.bio_drop_sender.as_ref() {
398 Some(tx) => tx,
399 // Shouldn't happen — caller (`maybe_offload_drop`) only
400 // pushes when the sender exists. Defensive: if a future
401 // refactor invokes `flush_pending_drops` from somewhere
402 // unconditional, drop the batch inline.
403 None => {
404 self.pending_drops.clear();
405 return;
406 }
407 };
408 let batch = std::mem::take(&mut self.pending_drops);
409 if let Err(_send_err) = tx.send(batch) {
410 // Bio thread is gone (shutdown). The SendError carries
411 // the Vec, which drops here — every Box<Value> runs its
412 // Drop inline. Benign one-time stall during tear-down.
413 }
414 }
415
416 /// Live byte estimate (see field doc).
417 #[inline]
418 pub fn used_memory(&self) -> u64 {
419 self.used_memory
420 }
421
422 /// `used_memory` high-water mark since startup.
423 #[inline]
424 pub fn used_memory_peak(&self) -> u64 {
425 self.used_memory_peak
426 }
427
428 /// Configured `maxmemory` (0 = unlimited).
429 #[inline]
430 pub fn maxmemory(&self) -> u64 {
431 self.maxmemory
432 }
433
434 /// Configured eviction policy.
435 #[inline]
436 pub fn eviction_policy(&self) -> EvictionPolicy {
437 self.eviction_policy
438 }
439
440 /// Total keys evicted since startup.
441 #[inline]
442 pub fn evictions_total(&self) -> u64 {
443 self.evictions_total
444 }
445
446 /// Live keys carrying a TTL (`INFO keyspace`'s `expires=`). O(1) — reads
447 /// the maintained counter, not an O(n) scan (cf. [`Self::ttl_pending_count`]).
448 #[inline]
449 pub fn expires_count(&self) -> usize {
450 self.expires as usize
451 }
452
453 /// Apply a signed delta to the [`Self::expires`] counter, clamped at 0.
454 /// Centralises the saturating arithmetic for every TTL-transition site.
455 #[inline]
456 pub(crate) fn adjust_expires(&mut self, delta: i64) {
457 if delta != 0 {
458 self.expires = (self.expires as i64 + delta).max(0) as u64;
459 }
460 }
461
462 /// `WATCH` — record this key in the version tracker and return its
463 /// current version. Subsequent writes on this shard bump the version
464 /// via [`Self::bump_if_watched`]. Caller (the conn's origin shard)
465 /// stores the returned version; `EXEC` later asks every owning shard
466 /// "is the version still N?" via [`Self::key_version`].
467 ///
468 /// Keys that have never been written stay at version 0 — the first
469 /// write after a `WATCH` bumps to 1, which is what makes the "dirty"
470 /// comparison work (stored 0 ≠ current 1 ⇒ abort EXEC).
471 pub fn record_watch(&mut self, key: &[u8]) -> u64 {
472 *self
473 .watch_versions
474 .entry(key.to_vec())
475 .or_insert(0)
476 }
477
478 /// Read-only version lookup used by `EXEC`'s pre-execution check.
479 /// Returns `0` for keys never `WATCH`-ed (matches the initial value
480 /// `record_watch` would have inserted, so a `WATCH` → no-write →
481 /// `EXEC` sequence sees the stored 0 == current 0 and proceeds).
482 #[inline]
483 pub fn key_version(&self, key: &[u8]) -> u64 {
484 self.watch_versions.get(key).copied().unwrap_or(0)
485 }
486
487 /// Bump the version of `key` if (and only if) it has been `WATCH`-ed at
488 /// least once. Write-side call after every mutation. The empty check
489 /// runs BEFORE the key is hashed — the common nothing-watched case
490 /// pays one branch, not a guaranteed-miss probe.
491 #[inline]
492 pub fn bump_if_watched(&mut self, key: &[u8]) {
493 if self.watch_versions.is_empty() {
494 return;
495 }
496 if let Some(v) = self.watch_versions.get_mut(key) {
497 *v = v.wrapping_add(1);
498 }
499 }
500
501 /// Invalidate every watched key in one shot. Called from `FLUSHDB`
502 /// / `FLUSHALL` execution paths — every WATCH against this shard
503 /// must invalidate so a pending `EXEC` aborts.
504 pub fn bump_all_watched(&mut self) {
505 for v in self.watch_versions.values_mut() {
506 *v = v.wrapping_add(1);
507 }
508 }
509
510 /// Cached weight of `key` (dynamic part + [`ENTRY_OVERHEAD`]). Returns
511 /// `None` when the key is absent or expired (no implicit reap).
512 pub fn estimate_key_bytes(&self, key: &[u8]) -> Option<u64> {
513 self.map.get(key).map(|e| e.weight() + ENTRY_OVERHEAD)
514 }
515
516 /// O(1) precondition check the dispatch layer calls before every write
517 /// command. Returns `Err(OutOfMemory)` only when `maxmemory > 0`, the
518 /// budget is already over, AND the policy is `NoEviction` (Redis
519 /// behaviour). All other policies let the write proceed and recover via
520 /// [`Self::try_evict_after_write`].
521 #[inline]
522 pub fn precheck_for_write(&self) -> Result<(), StoreError> {
523 if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
524 return Ok(());
525 }
526 if self.eviction_policy == EvictionPolicy::NoEviction {
527 return Err(StoreError::OutOfMemory);
528 }
529 Ok(())
530 }
531
532 /// Run after every write command. No-op when disabled or under budget;
533 /// otherwise samples per [`Self::eviction_policy`] and removes keys until
534 /// back under `maxmemory` or no eligible candidate remains. Returns the
535 /// number of keys evicted (0 on the common fast path).
536 #[inline]
537 pub fn try_evict_after_write(&mut self) -> usize {
538 if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
539 return 0;
540 }
541 evict::evict_until_under_limit(self)
542 }
543
544}
545
546/// Apply a signed delta to a `u64` (saturating both directions). Used by
547/// `Store::account_delta` / `reweigh_entry` so the in-place mutators don't
548/// have to repeat the same overflow-guarded match.
549#[inline]
550pub(crate) fn apply_delta(v: &mut u64, delta: i64) {
551 if delta >= 0 {
552 *v = v.saturating_add(delta as u64);
553 } else {
554 *v = v.saturating_sub((-delta) as u64);
555 }
556}
557
558/// Heap bytes a `SmallBytes`-encoded key would own (`&[u8]` mirror of
559/// `SmallBytes::heap_bytes`; 22-byte inline boundary per `kevy-bytes`).
560#[inline]
561pub(crate) fn key_heap_bytes_for(key: &[u8]) -> u64 {
562 if key.len() <= 22 { 0 } else { key.len() as u64 }
563}
564
565#[cfg(test)]
566mod tests;
567#[cfg(test)]
568mod tests_memory;
569#[cfg(test)]
570mod tests_snapshot;