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 std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
21use std::fmt;
22use std::marker::PhantomData;
23use std::mem::MaybeUninit;
24use std::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#[inline(always)]
55fn prefetch_t0(ptr: *const u8) {
56    #[cfg(all(target_arch = "x86_64", not(miri)))]
57    {
58        // SAFETY: _mm_prefetch reads no memory; any aligned/unaligned/
59        // out-of-bounds pointer is permitted by the ISA.
60        unsafe {
61            core::arch::x86_64::_mm_prefetch(
62                ptr as *const i8,
63                core::arch::x86_64::_MM_HINT_T0,
64            );
65        }
66    }
67    #[cfg(all(target_arch = "aarch64", not(miri)))]
68    {
69        // SAFETY: prfm reads no memory; any pointer permitted.
70        unsafe {
71            core::arch::asm!(
72                "prfm pldl1keep, [{p}]",
73                p = in(reg) ptr,
74                options(nostack, preserves_flags, readonly),
75            );
76        }
77    }
78    #[cfg(any(miri, not(any(target_arch = "x86_64", target_arch = "aarch64"))))]
79    {
80        let _ = ptr;
81    }
82}
83
84/// Compute the single-buffer layout for a table of `cap` slots: returns the
85/// combined `Layout` and the byte offset to the metadata array. Panics on
86/// arithmetic overflow (only reachable for cap ≈ usize::MAX which would OOM
87/// anyway).
88///
89/// Metadata size is `cap + GROUP_WIDTH` (hashbrown 0.15 layout): the first
90/// `cap` bytes are the real per-slot metadata, the trailing `GROUP_WIDTH`
91/// bytes mirror the leading ones so the branchless `set_meta` formula
92/// `index2 = ((i - GW) & mask) + GW` always lands inside the buffer (for
93/// `i = GROUP_WIDTH - 1` the formula evaluates to `cap + GROUP_WIDTH - 1`,
94/// the very last byte). That last byte is written by `set_meta` but never
95/// read by `Group::load` — SIMD loads from `group_start ∈ [0, cap)` reach
96/// at most `cap + GROUP_WIDTH - 2`.
97#[inline]
98pub(crate) fn table_layout<KV>(cap: usize) -> (Layout, usize) {
99    let slots = Layout::array::<MaybeUninit<KV>>(cap).expect("slots layout overflow");
100    let meta = Layout::array::<u8>(cap + GROUP_WIDTH).expect("metadata layout overflow");
101    let (combined, meta_offset) = slots.extend(meta).expect("layout extend overflow");
102    (combined.pad_to_align(), meta_offset)
103}
104
105/// An open-addressing Swiss-style hashtable keyed by [`KevyHash`].
106///
107/// Power-of-two capacity (`mask = cap - 1`); 7/8 load factor; linear probing
108/// over the metadata array; full slots' (K, V) live AoS in a parallel slot
109/// array of `MaybeUninit<(K, V)>` co-allocated with the metadata.
110///
111/// When `cap == 0` both pointers are dangling and no allocation is held.
112pub struct KevyMap<K, V> {
113    /// Slot array. `cap` initialised iff the corresponding metadata byte is
114    /// in `0x00..=0x7F`. Dangling when `cap == 0`.
115    pub(crate) slots_ptr: NonNull<MaybeUninit<(K, V)>>,
116    /// Metadata array (`cap + GROUP_WIDTH` bytes; trailing
117    /// `GROUP_WIDTH - 1` bytes mirror the leading ones for SIMD-safe
118    /// wraparound loads — the hashbrown layout). Dangling when `cap == 0`.
119    pub(crate) metadata_ptr: NonNull<u8>,
120    /// Allocated slot count. `0` when no allocation is held.
121    pub(crate) cap: usize,
122    /// `cap - 1` when `cap > 0`; `0` when `cap == 0`.
123    pub(crate) mask: usize,
124    /// Live entries.
125    pub(crate) occupied: usize,
126    /// Tombstones (not yet reclaimed).
127    pub(crate) deleted: usize,
128    /// Marker so dropck and variance treat us as owning `(K, V)` like a
129    /// `Box<[MaybeUninit<(K, V)>]>` would.
130    _marker: PhantomData<(K, V)>,
131}
132
133// SAFETY: KevyMap owns its `(K, V)` entries (via the slot allocation). The
134// `NonNull<...>` fields are conceptually `Box<[…]>` and inherit the same
135// Send/Sync bounds: send-K + send-V ⇒ KevyMap is Send. Same for Sync.
136unsafe impl<K: Send, V: Send> Send for KevyMap<K, V> {}
137unsafe impl<K: Sync, V: Sync> Sync for KevyMap<K, V> {}
138
139/// `(metadata, slots)` parallel-slice pair returned by [`KevyMap::as_slices`].
140/// Aliased so the long `(&[u8], &[MaybeUninit<(K, V)>])` signature doesn't
141/// trip clippy's `type_complexity` lint on a member-by-member basis.
142type SlotSlices<'a, K, V> = (&'a [u8], &'a [MaybeUninit<(K, V)>]);
143
144/// Mutable-slot variant of [`SlotSlices`], returned by
145/// [`KevyMap::as_mut_slices`] for [`KevyMap::iter_mut`].
146type SlotSlicesMut<'a, K, V> = (&'a [u8], &'a mut [MaybeUninit<(K, V)>]);
147
148pub(crate) enum ProbeOutcome {
149    Found(usize),
150    NotFound {
151        insert_at: usize,
152        via_tombstone: bool,
153    },
154}
155
156impl<K, V> KevyMap<K, V> {
157    /// Construct an empty map without allocating.
158    pub fn new() -> Self {
159        Self {
160            slots_ptr: NonNull::dangling(),
161            metadata_ptr: NonNull::dangling(),
162            cap: 0,
163            mask: 0,
164            occupied: 0,
165            deleted: 0,
166            _marker: PhantomData,
167        }
168    }
169
170    /// Construct a map sized to hold `cap_hint` entries without growing
171    /// (accounting for the 7/8 load factor).
172    pub fn with_capacity(cap_hint: usize) -> Self {
173        if cap_hint == 0 {
174            return Self::new();
175        }
176        // ceil(cap_hint * 8 / 7) → smallest table where cap_hint fits below 7/8.
177        let needed = cap_hint.saturating_mul(8).div_ceil(7);
178        let cap = needed.next_power_of_two().max(MIN_CAP);
179        Self::alloc_table(cap)
180    }
181
182    pub(crate) fn alloc_table(cap: usize) -> Self {
183        debug_assert!(cap.is_power_of_two());
184        debug_assert!(cap >= MIN_CAP);
185
186        let (layout, meta_offset) = table_layout::<(K, V)>(cap);
187        // SAFETY: layout has non-zero size (metadata alone is ≥ MIN_CAP +
188        // GROUP_WIDTH - 1 ≥ 31 bytes). alloc returns either a valid
189        // allocation of `layout` or null.
190        let base = unsafe { alloc(layout) };
191        if base.is_null() {
192            handle_alloc_error(layout);
193        }
194        // Initialise the metadata range (real + mirror tail) to EMPTY in a
195        // single memset. The slot array is left uninitialised — slots
196        // become initialised only when their metadata byte transitions
197        // out of the high-bit-set state (EMPTY/DELETED).
198        let meta_byte_ptr = unsafe { base.add(meta_offset) };
199        unsafe { ptr::write_bytes(meta_byte_ptr, EMPTY, cap + GROUP_WIDTH) };
200
201        let slots_ptr = base as *mut MaybeUninit<(K, V)>;
202        let metadata_ptr = meta_byte_ptr;
203
204        // single-buffer redo: hint THP on the entire buffer in
205        // one madvise call. The combined allocation is `meta_offset +
206        // cap + GROUP_WIDTH` bytes (== `layout.size()` minus padding).
207        // On 10M+ key tables the metadata alone is 16 MB — well over the
208        // 2 MB HP boundary, so the kernel's khugepaged can promote it in
209        // place. Cheap on the non-Linux paths (compile-time no-op).
210        kevy_madvise::advise_hugepage(base as *const u8, layout.size());
211
212        Self {
213            // SAFETY: alloc returned non-null; raw pointers are derived
214            // within the same allocation.
215            slots_ptr: unsafe { NonNull::new_unchecked(slots_ptr) },
216            metadata_ptr: unsafe { NonNull::new_unchecked(metadata_ptr) },
217            cap,
218            mask: cap - 1,
219            occupied: 0,
220            deleted: 0,
221            _marker: PhantomData,
222        }
223    }
224
225    /// Write `v` into metadata slot `i`, also updating the mirror byte
226    /// at `cap + i` when `i < GROUP_WIDTH`. Every metadata mutation goes
227    /// through this helper so the mirror stays consistent with the real
228    /// metadata.
229    ///
230    /// Branchless: the formula `index2 = ((i - GW) & mask) + GW`
231    /// (hashbrown 0.15's `set_ctrl`) yields the real mirror position
232    /// `cap + i` when `i < GW`, and yields `i` itself when `i >= GW`.
233    /// The second write is therefore either to the mirror byte or a
234    /// duplicate write to the same real byte (a no-op). No branch.
235    #[inline]
236    pub(crate) fn set_meta(&mut self, i: usize, v: u8) {
237        debug_assert!(i < self.cap);
238        // SAFETY: i ∈ [0, cap); i2 ∈ [GROUP_WIDTH, cap + GROUP_WIDTH);
239        // both in-bounds since metadata buffer length is cap + GROUP_WIDTH.
240        let i2 = (i.wrapping_sub(GROUP_WIDTH) & self.mask) + GROUP_WIDTH;
241        unsafe {
242            *self.metadata_ptr.as_ptr().add(i) = v;
243            *self.metadata_ptr.as_ptr().add(i2) = v;
244        }
245    }
246
247    /// Live entry count.
248    #[inline]
249    pub fn len(&self) -> usize {
250        self.occupied
251    }
252
253    /// Whether the map has zero live entries.
254    #[inline]
255    pub fn is_empty(&self) -> bool {
256        self.occupied == 0
257    }
258
259    /// Allocated slot count (NOT live entries).
260    #[inline]
261    pub fn capacity(&self) -> usize {
262        self.cap
263    }
264
265    /// Drop every live entry and reset the metadata. Keeps the allocation.
266    pub fn clear(&mut self) {
267        if self.cap == 0 {
268            return;
269        }
270        if std::mem::needs_drop::<(K, V)>() {
271            for i in 0..self.cap {
272                // SAFETY: i < cap ⇒ metadata pointer in-bounds.
273                let meta = unsafe { *self.metadata_ptr.as_ptr().add(i) };
274                if meta & 0x80 == 0 {
275                    // SAFETY: full slot ⇒ initialised.
276                    unsafe {
277                        ptr::drop_in_place(self.slots_ptr.as_ptr().add(i) as *mut (K, V));
278                    }
279                }
280            }
281        }
282        // Reset entire metadata buffer (real range + mirror tail) in one memset.
283        // SAFETY: metadata buffer is exactly cap + GROUP_WIDTH bytes wide.
284        unsafe {
285            ptr::write_bytes(self.metadata_ptr.as_ptr(), EMPTY, self.cap + GROUP_WIDTH);
286        }
287        self.occupied = 0;
288        self.deleted = 0;
289    }
290
291    /// `(&K, &V)` over all live entries; order is unspecified.
292    pub fn iter(&self) -> Iter<'_, K, V> {
293        let (metadata, slots) = self.as_slices();
294        Iter::new(metadata, slots)
295    }
296
297    /// `iter` that begins at bucket `start` (clamped to `capacity()`) and
298    /// walks to the end. To sweep the full ring beginning at a random offset
299    /// — the pattern the kevy-store eviction sampler uses — chain it with a
300    /// second `iter_from_bucket(0)` and `take(start)`.
301    pub fn iter_from_bucket(&self, start: usize) -> Iter<'_, K, V> {
302        let (metadata, slots) = self.as_slices();
303        Iter::with_start(metadata, slots, start)
304    }
305
306    /// `(&K, &mut V)` over all live entries; order is unspecified. Keys stay
307    /// shared (mutating a key in place would corrupt its bucket).
308    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
309        let (metadata, slots) = self.as_mut_slices();
310        IterMut::new(metadata, slots)
311    }
312
313    /// `&K` over all live entries.
314    pub fn keys(&self) -> Keys<'_, K, V> {
315        Keys::new(self.iter())
316    }
317
318    /// `&V` over all live entries.
319    pub fn values(&self) -> Values<'_, K, V> {
320        Values::new(self.iter())
321    }
322
323    /// Borrow the metadata and slots as parallel slices of length `cap`.
324    /// Used by [`KevyMap::iter`] (which only needs the real slot range,
325    /// not the mirror tail). When `cap == 0` returns two empty slices —
326    /// the dangling pointer is never dereferenced.
327    #[inline]
328    fn as_slices(&self) -> SlotSlices<'_, K, V> {
329        if self.cap == 0 {
330            return (&[], &[]);
331        }
332        // SAFETY: cap > 0 ⇒ both pointers are valid for `cap` reads; we hand
333        // out shared borrows tied to `&self`'s lifetime, so the allocation
334        // outlives the returned slices.
335        unsafe {
336            (
337                std::slice::from_raw_parts(self.metadata_ptr.as_ptr(), self.cap),
338                std::slice::from_raw_parts(self.slots_ptr.as_ptr(), self.cap),
339            )
340        }
341    }
342
343    /// [`KevyMap::as_slices`] with mutable slots (metadata stays shared —
344    /// [`KevyMap::iter_mut`] only reads it). The disjoint borrows are sound:
345    /// metadata and slots are separate allocations.
346    #[inline]
347    fn as_mut_slices(&mut self) -> SlotSlicesMut<'_, K, V> {
348        if self.cap == 0 {
349            return (&[], &mut []);
350        }
351        // SAFETY: cap > 0 ⇒ both pointers are valid; `&mut self` guarantees
352        // exclusive access for the lifetime of the returned slices.
353        unsafe {
354            (
355                std::slice::from_raw_parts(self.metadata_ptr.as_ptr(), self.cap),
356                std::slice::from_raw_parts_mut(self.slots_ptr.as_ptr(), self.cap),
357            )
358        }
359    }
360
361    /// Hint the CPU to fetch the bucket cache line that a probe at `hash`
362    /// would start at. The prefetch lever against the bucket-probe DRAM
363    /// miss: the command-batch driver calls this for command N+1 while
364    /// finishing command N, so by the time N+1 actually probes the
365    /// metadata, the line is in L1.
366    ///
367    /// No-op when the table is empty. Cheap when not empty (a single
368    /// `prefetcht0` on x86_64 / `prfm pldl1keep` on aarch64; a regular
369    /// volatile load on other arches via [`std::intrinsics`] — but we
370    /// only use stable intrinsics here, so non-x86/aarch64 architectures
371    /// degrade to a no-op rather than a fake hint).
372    #[inline(always)]
373    pub fn prefetch_for_hash(&self, hash: u64) {
374        if self.cap == 0 {
375            return;
376        }
377        let idx = (hash as usize) & self.mask;
378        // SAFETY: idx < cap ≤ metadata length ⇒ pointer in-bounds; prefetch
379        // reads never trap and never observe values.
380        let ptr = unsafe { self.metadata_ptr.as_ptr().add(idx) };
381        prefetch_t0(ptr);
382    }
383
384    /// 7/8 of the capacity — the inclusive max for `occupied + deleted`.
385    #[inline]
386    pub(crate) fn threshold(&self) -> usize {
387        self.cap - (self.cap / 8)
388    }
389}
390
391
392impl<K, V> Default for KevyMap<K, V> {
393    fn default() -> Self {
394        Self::new()
395    }
396}
397
398/// `m[&q]` panics on missing key (matches `std::HashMap::Index` semantics).
399impl<K, Q, V> std::ops::Index<&Q> for KevyMap<K, V>
400where
401    K: std::borrow::Borrow<Q>,
402    Q: KevyHash + Eq + ?Sized,
403{
404    type Output = V;
405    fn index(&self, key: &Q) -> &V {
406        self.get(key).expect("no entry found for key")
407    }
408}
409
410impl<K, V> Drop for KevyMap<K, V> {
411    fn drop(&mut self) {
412        if self.cap == 0 {
413            return;
414        }
415        if std::mem::needs_drop::<(K, V)>() {
416            for i in 0..self.cap {
417                // SAFETY: i < cap ⇒ in-bounds.
418                let meta = unsafe { *self.metadata_ptr.as_ptr().add(i) };
419                if meta & 0x80 == 0 {
420                    // SAFETY: full slot ⇒ initialised.
421                    unsafe {
422                        ptr::drop_in_place(self.slots_ptr.as_ptr().add(i) as *mut (K, V));
423                    }
424                }
425            }
426        }
427        // Free the single combined allocation. `slots_ptr` IS the base of
428        // the allocation (see alloc_table's layout computation: slots are
429        // at offset 0; metadata sits at meta_offset).
430        let (layout, _) = table_layout::<(K, V)>(self.cap);
431        // SAFETY: cap > 0 ⇒ slots_ptr is non-null and was returned by `alloc`
432        // with the same Layout (table_layout is deterministic on cap).
433        unsafe {
434            dealloc(self.slots_ptr.as_ptr() as *mut u8, layout);
435        }
436    }
437}
438
439impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for KevyMap<K, V> {
440    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441        f.debug_map().entries(self.iter()).finish()
442    }
443}
444
445impl<K: KevyHash + Eq, V> FromIterator<(K, V)> for KevyMap<K, V> {
446    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
447        let iter = iter.into_iter();
448        let mut m = match iter.size_hint() {
449            (lo, Some(hi)) if hi <= lo.saturating_mul(2) => Self::with_capacity(hi),
450            (lo, _) => Self::with_capacity(lo),
451        };
452        for (k, v) in iter {
453            m.insert(k, v);
454        }
455        m
456    }
457}
458
459impl<K: KevyHash + Eq, V> Extend<(K, V)> for KevyMap<K, V> {
460    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
461        for (k, v) in iter {
462            self.insert(k, v);
463        }
464    }
465}
466
467#[cfg(test)]
468#[path = "map_tests.rs"]
469mod tests;