Skip to main content

kevy_map/
map.rs

1//! The KevyMap implementation: struct, allocation, probing, and the live
2//! lookup / insert / remove API. Helpers (`h2`, `prefetch_t0`, metadata
3//! constants) and the private `ProbeOutcome` enum are all map-scoped.
4//!
5//! Layout (single allocation):
6//!
7//! ```text
8//! +------------+------------+-----+---------------+---------+--------+
9//! | slot[0]    | slot[1]    | ... | slot[cap-1]   | padding | meta   |
10//! +------------+------------+-----+---------------+---------+--------+
11//! ^                                                          ^
12//! slots_ptr                                                  metadata_ptr
13//! ```
14//!
15//! Both pointers are precomputed at `alloc_table` time and never re-derived
16//! in the hot path. The single allocation cuts one alloc/dealloc pair vs
17//! the previous two-`Box<[…]>` layout, and keeps metadata + slots in
18//! adjacent pages (warmer TLB, contiguous OS-prefetch).
19
20use core::alloc::Layout;
21use core::fmt;
22use core::marker::PhantomData;
23use core::mem::MaybeUninit;
24use core::ptr::{self, NonNull};
25
26use kevy_hash::KevyHash;
27
28use crate::iter::{Iter, IterMut, Keys, Values};
29
30/// SIMD group width (16 metadata bytes loaded per probe iteration).
31pub(crate) const GROUP_WIDTH: usize = 16;
32
33/// Metadata byte for an empty slot (top bit set, value bits 1's — distinct
34/// from DELETED so the probe loop can stop at EMPTY but skip DELETED).
35pub(crate) const EMPTY: u8 = 0xFF;
36/// Metadata byte for a tombstone (top bit set, value bits 0).
37pub(crate) const DELETED: u8 = 0x80;
38/// Minimum table size. ≥ 16 (one SSE2 group) so the future SIMD path can run
39/// a full group scan unconditionally.
40pub(crate) const MIN_CAP: usize = 16;
41
42/// Top-7 bits of the hash, used as the per-slot metadata byte for occupied
43/// slots. The top bit is always 0 (so occupancy = `meta & 0x80 == 0`).
44#[inline]
45pub(crate) fn h2(hash: u64) -> u8 {
46    ((hash >> 57) & 0x7F) as u8
47}
48
49/// Issue a hint to fetch the cache line containing `ptr` into L1 ("T0" =
50/// "all levels"). Stable on x86_64 / aarch64; no-op elsewhere AND under
51/// `cfg(miri)` (miri cannot model inline asm / arch intrinsics, so the hint
52/// degrades to a no-op for unsafe-correctness testing — the semantic
53/// contract of `prefetch_t0` is "may do nothing", so this is sound).
54///
55/// `inline(always)` is the point: prefetch only helps when the load-latency
56/// window the call hides is bigger than the call site itself. A non-inlined
57/// call_site / ret pair (~10 ns out-of-order) wipes the benefit.
58#[allow(clippy::inline_always)]
59#[inline(always)]
60fn prefetch_t0(ptr: *const u8) {
61    #[cfg(all(target_arch = "x86_64", not(miri)))]
62    {
63        // SAFETY: _mm_prefetch reads no memory; any aligned/unaligned/
64        // out-of-bounds pointer is permitted by the ISA.
65        unsafe {
66            core::arch::x86_64::_mm_prefetch(ptr as *const i8, core::arch::x86_64::_MM_HINT_T0);
67        }
68    }
69    #[cfg(all(target_arch = "aarch64", not(miri)))]
70    {
71        // SAFETY: prfm reads no memory; any pointer permitted.
72        unsafe {
73            core::arch::asm!(
74                "prfm pldl1keep, [{p}]",
75                p = in(reg) ptr,
76                options(nostack, preserves_flags, readonly),
77            );
78        }
79    }
80    #[cfg(any(miri, not(any(target_arch = "x86_64", target_arch = "aarch64"))))]
81    {
82        let _ = ptr;
83    }
84}
85
86/// Compute the single-buffer layout for a table of `cap` slots: returns the
87/// combined `Layout` and the byte offset to the metadata array. Panics on
88/// arithmetic overflow (only reachable for cap ≈ usize::MAX which would OOM
89/// anyway).
90///
91/// Metadata size is `cap + GROUP_WIDTH` (hashbrown 0.15 layout): the first
92/// `cap` bytes are the real per-slot metadata, the trailing `GROUP_WIDTH`
93/// bytes mirror the leading ones so the branchless `set_meta` formula
94/// `index2 = ((i - GW) & mask) + GW` always lands inside the buffer (for
95/// `i = GROUP_WIDTH - 1` the formula evaluates to `cap + GROUP_WIDTH - 1`,
96/// the very last byte). That last byte is written by `set_meta` but never
97/// read by `Group::load` — SIMD loads from `group_start ∈ [0, cap)` reach
98/// at most `cap + GROUP_WIDTH - 2`.
99#[inline]
100pub(crate) fn table_layout<KV>(cap: usize) -> (Layout, usize) {
101    let slots = Layout::array::<MaybeUninit<KV>>(cap).expect("slots layout overflow");
102    let meta = Layout::array::<u8>(cap + GROUP_WIDTH).expect("metadata layout overflow");
103    let (combined, meta_offset) = slots.extend(meta).expect("layout extend overflow");
104    (combined.pad_to_align(), meta_offset)
105}
106
107/// An open-addressing Swiss-style hashtable keyed by [`KevyHash`].
108///
109/// Power-of-two capacity (`mask = cap - 1`); 7/8 load factor; linear probing
110/// over the metadata array; full slots' (K, V) live AoS in a parallel slot
111/// array of `MaybeUninit<(K, V)>` co-allocated with the metadata.
112///
113/// When `cap == 0` both pointers are dangling and no allocation is held.
114/// # Examples
115///
116/// Keys are byte strings or integers — whatever implements `KevyHash`.
117/// There is deliberately no `&str` impl: the keyspace deals in bytes, and a
118/// key that exists only as UTF-8 would need validating on every lookup.
119///
120/// ```
121/// let mut m: kevy_map::KevyMap<Vec<u8>, u32> = kevy_map::KevyMap::new();
122/// assert_eq!(m.insert(b"k".to_vec(), 1), None, "insert returns what it displaced");
123/// assert_eq!(m.insert(b"k".to_vec(), 2), Some(1));
124/// assert_eq!(m.get(b"k".as_slice()), Some(&2));
125/// assert_eq!(m.remove(b"k".as_slice()), Some(2));
126/// assert_eq!(m.get(b"k".as_slice()), None);
127/// assert!(m.is_empty());
128/// ```
129pub struct KevyMap<K, V> {
130    /// Slot array. `cap` initialised iff the corresponding metadata byte is
131    /// in `0x00..=0x7F`. Dangling when `cap == 0`.
132    pub(crate) slots_ptr: NonNull<MaybeUninit<(K, V)>>,
133    /// Metadata array (`cap + GROUP_WIDTH` bytes; trailing
134    /// `GROUP_WIDTH - 1` bytes mirror the leading ones for SIMD-safe
135    /// wraparound loads — the hashbrown layout). Dangling when `cap == 0`.
136    pub(crate) metadata_ptr: NonNull<u8>,
137    /// Allocated slot count. `0` when no allocation is held.
138    pub(crate) cap: usize,
139    /// `cap - 1` when `cap > 0`; `0` when `cap == 0`.
140    pub(crate) mask: usize,
141    /// Live entries.
142    pub(crate) occupied: usize,
143    /// Tombstones (not yet reclaimed).
144    pub(crate) deleted: usize,
145    /// `true` when the table buffer was obtained from
146    /// [`kevy_madvise::mmap_anon_aligned_2mb`] (large tables that wanted
147    /// THP-aligned storage); `false` when it came from the global allocator.
148    /// Drives the dispatch in [`Drop`] between `munmap_2mb` and `dealloc`.
149    pub(crate) mmap_backed: bool,
150    /// Marker so dropck and variance treat us as owning `(K, V)` like a
151    /// `Box<[MaybeUninit<(K, V)>]>` would.
152    pub(crate) _marker: PhantomData<(K, V)>,
153}
154
155// SAFETY: KevyMap owns its `(K, V)` entries (via the slot allocation). The
156// `NonNull<...>` fields are conceptually `Box<[…]>` and inherit the same
157// Send/Sync bounds: send-K + send-V ⇒ KevyMap is Send. Same for Sync.
158unsafe impl<K: Send, V: Send> Send for KevyMap<K, V> {}
159unsafe impl<K: Sync, V: Sync> Sync for KevyMap<K, V> {}
160
161/// `(metadata, slots)` parallel-slice pair returned by [`KevyMap::as_slices`].
162/// Aliased so the long `(&[u8], &[MaybeUninit<(K, V)>])` signature doesn't
163/// trip clippy's `type_complexity` lint on a member-by-member basis.
164type SlotSlices<'a, K, V> = (&'a [u8], &'a [MaybeUninit<(K, V)>]);
165
166/// Mutable-slot variant of [`SlotSlices`], returned by
167/// [`KevyMap::as_mut_slices`] for [`KevyMap::iter_mut`].
168type SlotSlicesMut<'a, K, V> = (&'a [u8], &'a mut [MaybeUninit<(K, V)>]);
169
170pub(crate) enum ProbeOutcome {
171    Found(usize),
172    NotFound { insert_at: usize, via_tombstone: bool },
173}
174
175impl<K, V> KevyMap<K, V> {
176    /// Construct an empty map without allocating.
177    /// # Examples
178    ///
179    /// ```
180    /// // The key must implement `KevyHash`, which is deliberately a small
181    /// // set: byte strings and integers, the things a KV engine keys on.
182    /// let m: kevy_map::KevyMap<Vec<u8>, u32> = kevy_map::KevyMap::new();
183    /// assert!(m.is_empty());
184    /// assert_eq!(m.len(), 0);
185    /// ```
186    pub fn new() -> Self {
187        Self {
188            slots_ptr: NonNull::dangling(),
189            metadata_ptr: NonNull::dangling(),
190            cap: 0,
191            mask: 0,
192            occupied: 0,
193            deleted: 0,
194            mmap_backed: false,
195            _marker: PhantomData,
196        }
197    }
198
199    /// Construct a map sized to hold `cap_hint` entries without growing
200    /// (accounting for the 7/8 load factor).
201    /// # Examples
202    ///
203    /// ```
204    /// // A hint, not a promise: capacity is rounded to the table's own
205    /// // shape, and `len` still starts at zero.
206    /// let m: kevy_map::KevyMap<u32, u32> = kevy_map::KevyMap::with_capacity(100);
207    /// assert_eq!(m.len(), 0);
208    /// ```
209    pub fn with_capacity(cap_hint: usize) -> Self {
210        if cap_hint == 0 {
211            return Self::new();
212        }
213        // ceil(cap_hint * 8 / 7) → smallest table where cap_hint fits below 7/8.
214        let needed = cap_hint.saturating_mul(8).div_ceil(7);
215        let cap = needed.next_power_of_two().max(MIN_CAP);
216        Self::alloc_table(cap)
217    }
218
219    // alloc_table + Drop live in `crate::alloc` so this file stays under
220    // the 500-LOC house rule.
221
222    /// Write `v` into metadata slot `i`, also updating the mirror byte
223    /// at `cap + i` when `i < GROUP_WIDTH`. Every metadata mutation goes
224    /// through this helper so the mirror stays consistent with the real
225    /// metadata.
226    ///
227    /// Branchless: the formula `index2 = ((i - GW) & mask) + GW`
228    /// (hashbrown 0.15's `set_ctrl`) yields the real mirror position
229    /// `cap + i` when `i < GW`, and yields `i` itself when `i >= GW`.
230    /// The second write is therefore either to the mirror byte or a
231    /// duplicate write to the same real byte (a no-op). No branch.
232    #[inline]
233    pub(crate) fn set_meta(&mut self, i: usize, v: u8) {
234        debug_assert!(i < self.cap);
235        // SAFETY: i ∈ [0, cap); i2 ∈ [GROUP_WIDTH, cap + GROUP_WIDTH);
236        // both in-bounds since metadata buffer length is cap + GROUP_WIDTH.
237        let i2 = (i.wrapping_sub(GROUP_WIDTH) & self.mask) + GROUP_WIDTH;
238        unsafe {
239            *self.metadata_ptr.as_ptr().add(i) = v;
240            *self.metadata_ptr.as_ptr().add(i2) = v;
241        }
242    }
243
244    /// Live entry count.
245    #[inline]
246    /// # Examples
247    ///
248    /// ```
249    /// let mut m = kevy_map::KevyMap::new();
250    /// m.insert(1u32, "a");
251    /// m.insert(1u32, "b");
252    /// assert_eq!(m.len(), 1, "the second insert REPLACED the first");
253    /// ```
254    pub fn len(&self) -> usize {
255        self.occupied
256    }
257
258    /// Whether the map has zero live entries.
259    #[inline]
260    pub fn is_empty(&self) -> bool {
261        self.occupied == 0
262    }
263
264    /// Allocated slot count (NOT live entries).
265    #[inline]
266    pub fn capacity(&self) -> usize {
267        self.cap
268    }
269
270    /// Drop every live entry and reset the metadata. Keeps the allocation.
271    /// # Examples
272    ///
273    /// ```
274    /// let mut m = kevy_map::KevyMap::new();
275    /// for i in 0..8u32 { m.insert(i, i); }
276    /// m.clear();
277    /// assert!(m.is_empty());
278    /// assert_eq!(m.get(&0), None);
279    /// ```
280    pub fn clear(&mut self) {
281        if self.cap == 0 {
282            return;
283        }
284        if core::mem::needs_drop::<(K, V)>() {
285            for i in 0..self.cap {
286                // SAFETY: i < cap ⇒ metadata pointer in-bounds.
287                let meta = unsafe { *self.metadata_ptr.as_ptr().add(i) };
288                if meta & 0x80 == 0 {
289                    // SAFETY: full slot ⇒ initialised.
290                    unsafe {
291                        ptr::drop_in_place(self.slots_ptr.as_ptr().add(i).cast::<(K, V)>());
292                    }
293                }
294            }
295        }
296        // Reset entire metadata buffer (real range + mirror tail) in one memset.
297        // SAFETY: metadata buffer is exactly cap + GROUP_WIDTH bytes wide.
298        unsafe {
299            ptr::write_bytes(self.metadata_ptr.as_ptr(), EMPTY, self.cap + GROUP_WIDTH);
300        }
301        self.occupied = 0;
302        self.deleted = 0;
303    }
304
305    /// `(&K, &V)` over all live entries; order is unspecified.
306    /// # Examples
307    ///
308    /// ```
309    /// let mut m = kevy_map::KevyMap::new();
310    /// for i in 0..4u32 { m.insert(i, i * 10); }
311    /// // Unordered, like any hash table: sort before comparing.
312    /// let mut got: Vec<_> = m.iter().map(|(k, v)| (*k, *v)).collect();
313    /// got.sort_unstable();
314    /// assert_eq!(got, vec![(0, 0), (1, 10), (2, 20), (3, 30)]);
315    /// ```
316    pub fn iter(&self) -> Iter<'_, K, V> {
317        let (metadata, slots) = self.as_slices();
318        Iter::new(metadata, slots)
319    }
320
321    /// `iter` that begins at bucket `start` (clamped to `capacity()`) and
322    /// walks to the end. To sweep the full ring beginning at a random offset
323    /// — the pattern the kevy-store eviction sampler uses — chain it with a
324    /// second `iter_from_bucket(0)` and `take(start)`.
325    pub fn iter_from_bucket(&self, start: usize) -> Iter<'_, K, V> {
326        let (metadata, slots) = self.as_slices();
327        Iter::with_start(metadata, slots, start)
328    }
329
330    /// `(&K, &mut V)` over all live entries; order is unspecified. Keys stay
331    /// shared (mutating a key in place would corrupt its bucket).
332    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
333        let (metadata, slots) = self.as_mut_slices();
334        IterMut::new(metadata, slots)
335    }
336
337    /// `&K` over all live entries.
338    /// # Examples
339    ///
340    /// ```
341    /// let mut m = kevy_map::KevyMap::new();
342    /// m.insert(b"a".to_vec(), 1u32);
343    /// m.insert(b"b".to_vec(), 2);
344    /// let mut ks: Vec<_> = m.keys().cloned().collect();
345    /// ks.sort_unstable();
346    /// assert_eq!(ks, vec![b"a".to_vec(), b"b".to_vec()]);
347    /// ```
348    pub fn keys(&self) -> Keys<'_, K, V> {
349        Keys::new(self.iter())
350    }
351
352    /// `&V` over all live entries.
353    pub fn values(&self) -> Values<'_, K, V> {
354        Values::new(self.iter())
355    }
356
357    /// Borrow the metadata and slots as parallel slices of length `cap`.
358    /// Used by [`KevyMap::iter`] (which only needs the real slot range,
359    /// not the mirror tail). When `cap == 0` returns two empty slices —
360    /// the dangling pointer is never dereferenced.
361    #[inline]
362    fn as_slices(&self) -> SlotSlices<'_, K, V> {
363        if self.cap == 0 {
364            return (&[], &[]);
365        }
366        // SAFETY: cap > 0 ⇒ both pointers are valid for `cap` reads; we hand
367        // out shared borrows tied to `&self`'s lifetime, so the allocation
368        // outlives the returned slices.
369        unsafe {
370            (
371                core::slice::from_raw_parts(self.metadata_ptr.as_ptr(), self.cap),
372                core::slice::from_raw_parts(self.slots_ptr.as_ptr(), self.cap),
373            )
374        }
375    }
376
377    /// [`KevyMap::as_slices`] with mutable slots (metadata stays shared —
378    /// [`KevyMap::iter_mut`] only reads it). The disjoint borrows are sound:
379    /// metadata and slots are separate allocations.
380    #[inline]
381    fn as_mut_slices(&mut self) -> SlotSlicesMut<'_, K, V> {
382        if self.cap == 0 {
383            return (&[], &mut []);
384        }
385        // SAFETY: cap > 0 ⇒ both pointers are valid; `&mut self` guarantees
386        // exclusive access for the lifetime of the returned slices.
387        unsafe {
388            (
389                core::slice::from_raw_parts(self.metadata_ptr.as_ptr(), self.cap),
390                core::slice::from_raw_parts_mut(self.slots_ptr.as_ptr(), self.cap),
391            )
392        }
393    }
394
395    /// Hint the CPU to fetch the bucket cache line that a probe at `hash`
396    /// would start at. The prefetch lever against the bucket-probe DRAM
397    /// miss: the command-batch driver calls this for command N+1 while
398    /// finishing command N, so by the time N+1 actually probes the
399    /// metadata, the line is in L1.
400    ///
401    /// No-op when the table is empty. Cheap when not empty (a single
402    /// `prefetcht0` on x86_64 / `prfm pldl1keep` on aarch64; a regular
403    /// volatile load on other arches via [`std::intrinsics`] — but we
404    /// only use stable intrinsics here, so non-x86/aarch64 architectures
405    /// degrade to a no-op rather than a fake hint).
406    ///
407    /// `inline(always)` is the point — see the `prefetch_t0` rationale.
408    #[allow(clippy::inline_always)]
409    #[inline(always)]
410    pub fn prefetch_for_hash(&self, hash: u64) {
411        if self.cap == 0 {
412            return;
413        }
414        let idx = (hash as usize) & self.mask;
415        // SAFETY: idx < cap ≤ metadata length ⇒ pointer in-bounds; prefetch
416        // reads never trap and never observe values.
417        let ptr = unsafe { self.metadata_ptr.as_ptr().add(idx) };
418        prefetch_t0(ptr);
419    }
420
421    /// 7/8 of the capacity — the inclusive max for `occupied + deleted`.
422    #[inline]
423    pub(crate) fn threshold(&self) -> usize {
424        self.cap - (self.cap / 8)
425    }
426}
427
428impl<K, V> Default for KevyMap<K, V> {
429    fn default() -> Self {
430        Self::new()
431    }
432}
433
434/// `m[&q]` panics on missing key (matches `std::HashMap::Index` semantics).
435impl<K, Q, V> core::ops::Index<&Q> for KevyMap<K, V>
436where
437    K: core::borrow::Borrow<Q>,
438    Q: KevyHash + Eq + ?Sized,
439{
440    type Output = V;
441    fn index(&self, key: &Q) -> &V {
442        self.get(key).expect("no entry found for key")
443    }
444}
445
446impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for KevyMap<K, V> {
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        f.debug_map().entries(self.iter()).finish()
449    }
450}
451
452impl<K: KevyHash + Eq, V> FromIterator<(K, V)> for KevyMap<K, V> {
453    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
454        let iter = iter.into_iter();
455        let mut m = match iter.size_hint() {
456            (lo, Some(hi)) if hi <= lo.saturating_mul(2) => Self::with_capacity(hi),
457            (lo, _) => Self::with_capacity(lo),
458        };
459        for (k, v) in iter {
460            m.insert(k, v);
461        }
462        m
463    }
464}
465
466impl<K: KevyHash + Eq, V> Extend<(K, V)> for KevyMap<K, V> {
467    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
468        for (k, v) in iter {
469            self.insert(k, v);
470        }
471    }
472}
473
474#[cfg(test)]
475#[path = "map_tests.rs"]
476mod tests;