blob: 90986d063d142730e711e34066a3f76f7dafb4fc [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Shared non-generic open-addressed table mechanics (`vx_std::collections::raw_table`).
//!
//! Both [`RawU64Map`] and [`RawBytesMap`] begin every bucket slot with the
//! exact same 16-byte [`SlotPrefix`] (`state`, `hash`), allowing table
//! allocation, SipHash-1-3 seeded hashing, rehashing, slot migration,
//! backward-shift deletion, value overwrite, and occupied-slot iteration to be
//! implemented and verified once with zero code duplication.
use core::mem::{align_of, size_of};
use core::ptr;
use vx_alloc::alloc::{AllocError, is_valid_layout, raw_alloc_zeroed, raw_dealloc};
use vx_core::hash::SipHasher13;
/// Initial power-of-2 bucket count allocated on first insert.
pub(crate) const INITIAL_MAP_CAP: usize = 8;
/// Common alignment of every slot header (`SlotPrefix` / `U64SlotHeader` / `BytesSlotHeader`).
pub(crate) const HEADER_ALIGN: usize = 8;
/// Mixing constant XORed into the second SipHash-1-3 key word so a single
/// 64-bit FLS seed expands cleanly into a distinct 128-bit `(k0, k1)` key pair.
const SIP_KEY1_MIX: u64 = 0x9e37_79b9_7f4a_7c15;
unsafe extern "C" {
/// Per-fiber / per-process 64-bit hash seed from `tpidr_el0` FLS.
pub(crate) fn __vx_hash_seed() -> u64;
}
/// Bucket occupancy state stored at byte offset 0 of every map slot.
///
/// `Empty = 0` matches zero-initialized memory returned by `raw_alloc_zeroed`.
#[repr(u64)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum SlotState {
Empty = 0,
Occupied = 1,
}
/// Common 16-byte prefix at offset 0 of every slot in both `RawU64Map` and
/// `RawBytesMap`.
#[repr(C)]
pub(crate) struct SlotPrefix {
pub state: SlotState,
pub hash: u64,
}
const _: () = assert!(size_of::<SlotPrefix>() == 16);
const _: () = assert!(align_of::<SlotPrefix>() == HEADER_ALIGN);
/// Maximum number of occupied entries allowed for power-of-2 capacity `cap`
/// while staying strictly at or below 70% load (`11/16 = 68.75% <= 70%`, zero
/// `mul`/`udiv`, guaranteed `< cap` for every power of 2 `>= 8`).
#[inline(always)]
pub(crate) const fn map_max_load(cap: usize) -> usize {
(cap >> 1) + (cap >> 3) + (cap >> 4)
}
/// Align `x` up to power-of-2 `align`, returning `None` on overflow.
#[inline(always)]
const fn checked_align_up(x: usize, align: usize) -> Option<usize> {
let mask = align - 1;
match x.checked_add(mask) {
Some(v) => Some(v & !mask),
None => None,
}
}
/// Compute `(val_offset, slot_stride, slot_align)` for slots with a
/// `header_size`-byte header and values of `(val_size, val_align)`.
#[inline(always)]
pub(crate) const fn compute_slot_layout(
header_size: usize,
val_size: usize,
val_align: usize,
) -> Option<(usize, usize, usize)> {
if val_align == 0 || (val_align & (val_align - 1)) != 0 {
return None;
}
let slot_align = if val_align > HEADER_ALIGN { val_align } else { HEADER_ALIGN };
let Some(val_offset) = checked_align_up(header_size, val_align) else {
return None;
};
let Some(raw_end) = val_offset.checked_add(val_size) else {
return None;
};
match checked_align_up(raw_end, slot_align) {
Some(s) if s > 0 && is_valid_layout(s, slot_align) => Some((val_offset, s, slot_align)),
_ => None,
}
}
/// Compute the smallest power-of-2 bucket count `>= INITIAL_MAP_CAP` whose
/// max load (`11/16`) is `>= needed`, or `None` on overflow.
#[curry::verified]
pub(crate) fn map_cap_for_entries(needed: usize) -> Option<usize> {
let mut cap = INITIAL_MAP_CAP;
while map_max_load(cap) < needed {
cap = cap.checked_mul(2)?;
}
Some(cap)
}
/// Compute the seeded SipHash-1-3 digest of `bytes` using 64-bit `seed`.
#[curry::verified]
pub fn hash_bytes_seeded(seed: u64, bytes: &[u8]) -> u64 {
let mut hasher = SipHasher13::new_with_keys(seed, seed ^ SIP_KEY1_MIX);
hasher.write_bytes(bytes);
hasher.finish_hash()
}
/// Compute the seeded SipHash-1-3 digest of a 64-bit integer `key` using `seed`.
#[curry::verified]
pub fn hash_u64_seeded(seed: u64, key: u64) -> u64 {
let bytes = key.to_le_bytes();
hash_bytes_seeded(seed, &bytes)
}
/// Insert one already-occupied slot `src_slot` into freshly zeroed `new_table`
/// of power-of-2 capacity `new_cap`.
///
/// # Safety
///
/// `src_slot` must begin with an initialized `SlotPrefix` and be readable for
/// `slot_stride` bytes; `new_table` must be a freshly zeroed, disjoint buffer
/// of `new_cap * slot_stride` bytes with at least one empty bucket.
#[curry::verified]
unsafe fn place_moved_slot(
new_table: *mut u8,
new_cap: usize,
slot_stride: usize,
src_slot: *const u8,
) {
let mask = new_cap - 1;
// SAFETY: `src_slot` starts with an initialized 8-byte-aligned `SlotPrefix`.
let hash = unsafe { (*(src_slot as *const SlotPrefix)).hash };
let mut idx = (hash as usize) & mask;
let mut steps: usize = 0;
while steps < new_cap {
// SAFETY: `idx < new_cap` and `new_table` holds `new_cap` slots of `slot_stride`.
let dst_slot = unsafe { new_table.add(idx * slot_stride) };
let dst_hdr = unsafe { &*(dst_slot as *const SlotPrefix) };
if dst_hdr.state == SlotState::Empty {
// SAFETY: `src_slot` (old table) and `dst_slot` (new table) are disjoint.
unsafe {
ptr::copy_nonoverlapping(src_slot, dst_slot, slot_stride);
}
return;
}
idx = (idx + 1) & mask;
steps += 1;
}
}
/// Move all occupied buckets from `old_table` (`old_cap` slots) into freshly
/// zeroed `new_table` (`new_cap` slots).
///
/// # Safety
///
/// `old_table` must hold `old_cap` valid slots of `slot_stride` bytes, and
/// `new_table` must be a disjoint freshly zeroed buffer of `new_cap` slots
/// (`new_cap > live_entries`).
#[curry::verified]
unsafe fn migrate_slots(
old_table: *const u8,
old_cap: usize,
new_table: *mut u8,
new_cap: usize,
slot_stride: usize,
) {
let mut i: usize = 0;
while i < old_cap {
// SAFETY: `i < old_cap` and `old_table` holds `old_cap` slots.
let src_slot = unsafe { old_table.add(i * slot_stride) };
let src_hdr = unsafe { &*(src_slot as *const SlotPrefix) };
if src_hdr.state == SlotState::Occupied {
// SAFETY: `new_table` is freshly zeroed with `new_cap > live_entries`.
unsafe {
place_moved_slot(new_table, new_cap, slot_stride, src_slot);
}
}
i += 1;
}
}
/// Shared 64-byte header for both [`RawU64Map`] and [`RawBytesMap`].
///
/// All fields are crate-private; external callers interact strictly through
/// [`RawU64Map`], [`RawBytesMap`], [`HashMap`], or [`HashSet`].
#[repr(C)]
pub struct RawTable {
pub(crate) table: *mut u8,
pub(crate) cap: usize,
pub(crate) len: usize,
pub(crate) seed: u64,
pub(crate) val_size: usize,
pub(crate) val_offset: usize,
pub(crate) slot_stride: usize,
pub(crate) slot_align: usize,
}
const _: () = assert!(size_of::<RawTable>() == 64);
const _: () = assert!(align_of::<RawTable>() == 8);
const _: () = assert!(core::mem::offset_of!(RawTable, table) == 0);
const _: () = assert!(core::mem::offset_of!(RawTable, cap) == 8);
const _: () = assert!(core::mem::offset_of!(RawTable, len) == 16);
const _: () = assert!(core::mem::offset_of!(RawTable, seed) == 24);
const _: () = assert!(core::mem::offset_of!(RawTable, val_size) == 32);
const _: () = assert!(core::mem::offset_of!(RawTable, val_offset) == 40);
const _: () = assert!(core::mem::offset_of!(RawTable, slot_stride) == 48);
const _: () = assert!(core::mem::offset_of!(RawTable, slot_align) == 56);
impl RawTable {
/// Construct an empty [`RawTable`] with precomputed slot geometry.
#[inline(always)]
pub(crate) const fn empty(
val_size: usize,
val_offset: usize,
slot_stride: usize,
slot_align: usize,
) -> Self {
Self {
table: ptr::null_mut(),
cap: 0,
len: 0,
seed: 0,
val_size,
val_offset,
slot_stride,
slot_align,
}
}
/// Compute the byte pointer to bucket `idx`.
///
/// # Safety
///
/// `self.table` must be non-null and `idx < self.cap`.
#[inline(always)]
pub(crate) unsafe fn slot_ptr(&self, idx: usize) -> *mut u8 {
// SAFETY: Caller guarantees `idx < self.cap` and `self.table` is valid for `self.cap` slots.
unsafe { self.table.add(idx * self.slot_stride) }
}
/// Probe for the first empty bucket starting from `hash`.
#[curry::verified]
pub(crate) fn find_empty_slot(&self, hash: u64) -> Option<usize> {
if self.table.is_null() || self.cap == 0 {
return None;
}
let mask = self.cap - 1;
let mut idx = (hash as usize) & mask;
let mut steps: usize = 0;
while steps < self.cap {
// SAFETY: `idx < self.cap` and `self.table` holds `self.cap` slots.
let hdr = unsafe { &*(self.slot_ptr(idx) as *const SlotPrefix) };
if hdr.state == SlotState::Empty {
return Some(idx);
}
idx = (idx + 1) & mask;
steps += 1;
}
None
}
/// Rehash all live entries into a freshly allocated zeroed table of
/// power-of-2 capacity `new_cap`.
///
/// Lazily initializes `self.seed` from `__vx_hash_seed()` on first
/// allocation (`self.cap == 0`). On `Err(AllocError)`, existing state is
/// untouched and zero memory is leaked.
#[curry::verified]
pub(crate) fn rehash(&mut self, new_cap: usize) -> Result<(), AllocError> {
if new_cap < INITIAL_MAP_CAP || (new_cap & (new_cap - 1)) != 0 {
return Err(AllocError);
}
if self.len > map_max_load(new_cap) || self.slot_stride == 0 {
return Err(AllocError);
}
let new_bytes = match new_cap.checked_mul(self.slot_stride) {
Some(b) if is_valid_layout(b, self.slot_align) => b,
_ => return Err(AllocError),
};
// SAFETY: `(new_bytes, self.slot_align)` was validated above.
let new_table = unsafe { raw_alloc_zeroed(new_bytes, self.slot_align)? }.as_ptr();
let old_table = self.table;
let old_cap = self.cap;
if !old_table.is_null() && old_cap > 0 {
// SAFETY: `old_table` holds `old_cap` slots and `new_table` is freshly zeroed.
unsafe {
migrate_slots(old_table, old_cap, new_table, new_cap, self.slot_stride);
}
if let Some(old_bytes) = old_cap.checked_mul(self.slot_stride) {
// SAFETY: `old_table` was allocated with `(old_bytes, self.slot_align)`.
unsafe {
raw_dealloc(old_table, old_bytes, self.slot_align);
}
}
} else {
// SAFETY: `__vx_hash_seed` is the link-time FLS hash-seed accessor.
self.seed = unsafe { __vx_hash_seed() };
}
self.table = new_table;
self.cap = new_cap;
Ok(())
}
/// Ensure space for at least one additional entry while keeping load `<= 68.75%`.
#[curry::verified]
pub(crate) fn ensure_insert_capacity(&mut self) -> Result<(), AllocError> {
if self.len < map_max_load(self.cap) {
return Ok(());
}
let new_cap = if self.cap == 0 {
INITIAL_MAP_CAP
} else {
match self.cap.checked_mul(2) {
Some(c) => c,
None => return Err(AllocError),
}
};
self.rehash(new_cap)
}
/// Ensure space for at least `additional` more entries without exceeding max load.
#[curry::verified]
pub(crate) fn reserve_for(&mut self, additional: usize) -> Result<(), AllocError> {
if additional == 0 {
return Ok(());
}
let Some(needed) = self.len.checked_add(additional) else {
return Err(AllocError);
};
if needed <= map_max_load(self.cap) {
return Ok(());
}
let Some(new_cap) = map_cap_for_entries(needed) else {
return Err(AllocError);
};
self.rehash(new_cap)
}
/// Overwrite the value bytes of occupied bucket `idx`, optionally moving
/// the previous value bytes into `old_val_out`.
///
/// # Safety
///
/// `idx < self.cap` must be an occupied slot; when `self.val_size > 0`,
/// `val_src` (and non-null `old_val_out`) must be valid for `self.val_size`
/// bytes and disjoint from `self.table`.
#[curry::verified]
pub(crate) unsafe fn overwrite_slot(
&mut self,
idx: usize,
val_src: *const u8,
old_val_out: *mut u8,
) {
if self.val_size == 0 {
return;
}
// SAFETY: Caller guarantees `idx < self.cap` and disjoint value buffers.
let val_dst = unsafe { self.slot_ptr(idx).add(self.val_offset) };
if !old_val_out.is_null() {
unsafe {
ptr::copy_nonoverlapping(val_dst, old_val_out, self.val_size);
}
}
unsafe {
ptr::copy_nonoverlapping(val_src, val_dst, self.val_size);
}
}
/// Repair the linear-probing cluster after vacating bucket `start_hole` via
/// backward-shift deletion (zero tombstones).
#[curry::verified]
pub(crate) fn backward_shift(&mut self, start_hole: usize) {
let mask = self.cap - 1;
let mut hole = start_hole;
let mut cur = (hole + 1) & mask;
let mut steps: usize = 0;
while steps < self.cap {
// SAFETY: `cur < self.cap` and `hole < self.cap` are distinct slots.
let cur_slot = unsafe { self.slot_ptr(cur) };
let cur_hdr = unsafe { &*(cur_slot as *const SlotPrefix) };
if cur_hdr.state == SlotState::Empty {
break;
}
let ideal = (cur_hdr.hash as usize) & mask;
let d_hole = hole.wrapping_sub(ideal) & mask;
let d_cur = cur.wrapping_sub(ideal) & mask;
if d_hole < d_cur {
// SAFETY: `cur != hole`, so the two slots are non-overlapping.
let hole_slot = unsafe { self.slot_ptr(hole) };
unsafe {
ptr::copy_nonoverlapping(cur_slot, hole_slot, self.slot_stride);
}
hole = cur;
}
cur = (cur + 1) & mask;
steps += 1;
}
// SAFETY: Mark the final vacated bucket empty.
let final_hdr = unsafe { &mut *(self.slot_ptr(hole) as *mut SlotPrefix) };
final_hdr.state = SlotState::Empty;
final_hdr.hash = 0;
}
/// Advance `*cursor` to the next occupied bucket in `[0, self.cap)`,
/// returning a mutable pointer to its stored value bytes (and setting
/// `*cursor = idx + 1`), or null if no occupied buckets remain.
///
/// Used by `HashMap<K, V>`'s `#[inline(always)]` drain loop to drop
/// non-`Copy` `Drop` values cleanly before `clear` or `free_all`.
#[curry::verified]
pub(crate) fn next_occupied_val_ptr(&self, cursor: &mut usize) -> *mut u8 {
if self.table.is_null() || self.cap == 0 {
*cursor = self.cap;
return ptr::null_mut();
}
let mut i = *cursor;
while i < self.cap {
// SAFETY: `i < self.cap` and `self.table` holds `self.cap` slots.
let slot = unsafe { self.slot_ptr(i) };
let hdr = unsafe { &*(slot as *const SlotPrefix) };
if hdr.state == SlotState::Occupied {
*cursor = i + 1;
// SAFETY: `slot + val_offset` lies inside occupied slot `i`.
return unsafe { slot.add(self.val_offset) };
}
i += 1;
}
*cursor = self.cap;
ptr::null_mut()
}
/// Free the bucket array itself (if allocated) and reset `table`, `cap`, `len`.
///
/// Caller must already have freed any per-slot key buffers and dropped values.
#[curry::verified]
pub(crate) fn free_table_buf(&mut self) {
let old_table = self.table;
let old_cap = self.cap;
if !old_table.is_null() && old_cap > 0 {
if let Some(old_bytes) = old_cap.checked_mul(self.slot_stride) {
// SAFETY: `old_table` was allocated with `(old_bytes, self.slot_align)`.
unsafe {
raw_dealloc(old_table, old_bytes, self.slot_align);
}
}
}
self.table = ptr::null_mut();
self.cap = 0;
self.len = 0;
}
}