blob: 75d441b305f18065322999c132df3cab3fb57432 [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.
//! Fallible `#![no_std]` hash map [`HashMap<K, V>`] backed statically by
//! [`RawU64Map`] (`KeyRepr::U64`) or [`RawBytesMap`] (`KeyRepr::Bytes`).
//!
//! Supports arbitrary non-`Copy` `Drop` values `V` cleanly via an
//! `#[inline(always)]` drain loop over `RawTable::next_occupied_val_ptr` +
//! `core::ptr::drop_in_place`.
use core::marker::PhantomData;
use core::mem::{ManuallyDrop, MaybeUninit, align_of, needs_drop, size_of};
use core::ptr;
use vx_alloc::alloc::AllocError;
use crate::collections::key::{Key, KeyQuery, KeyRepr};
use crate::collections::raw_bytes_map::BYTES_HEADER_SIZE;
use crate::collections::raw_table::{HEADER_ALIGN, RawTable, compute_slot_layout};
use crate::collections::raw_u64_map::U64_HEADER_SIZE;
/// Fallible, `#![no_std]` hash map (`std::collections::HashMap<K, V>` analog).
///
/// All generic methods are `#[inline(always)]` thin wrappers over the two
/// non-generic verified linear-probing cores (`RawU64Map` and `RawBytesMap`),
/// seeded via `__vx_hash_seed` with zero `BLR` comparators and zero
/// monomorphized probe loops.
#[repr(C)]
pub struct HashMap<K: Key, V> {
table: RawTable,
_marker: PhantomData<(K, V)>,
}
const _: () = assert!(size_of::<HashMap<u64, u64>>() == 64);
const _: () = assert!(align_of::<HashMap<u64, u64>>() == 8);
const _: () = assert!(size_of::<HashMap<&str, u64>>() == 64);
impl<K: Key, V> HashMap<K, V> {
/// Construct an empty [`HashMap<K, V>`] without allocating.
#[inline(always)]
pub const fn new() -> Self {
const {
let hs = match K::REPR {
KeyRepr::U64 => U64_HEADER_SIZE,
KeyRepr::Bytes => BYTES_HEADER_SIZE,
};
assert!(
compute_slot_layout(hs, size_of::<V>(), align_of::<V>()).is_some(),
"HashMap<K, V> value layout overflow"
);
}
let header_size = match K::REPR {
KeyRepr::U64 => U64_HEADER_SIZE,
KeyRepr::Bytes => BYTES_HEADER_SIZE,
};
let (val_offset, slot_stride, slot_align) =
match compute_slot_layout(header_size, size_of::<V>(), align_of::<V>()) {
Some(l) => l,
None => (header_size, header_size, HEADER_ALIGN),
};
Self {
table: RawTable::empty(size_of::<V>(), val_offset, slot_stride, slot_align),
_marker: PhantomData,
}
}
/// Construct an empty [`HashMap<K, V>`] with space reserved for at least
/// `capacity` entries without rehashing.
#[inline(always)]
pub fn try_with_capacity(capacity: usize) -> Result<Self, AllocError> {
let mut map = Self::new();
if capacity > 0 {
map.try_reserve(capacity)?;
}
Ok(map)
}
/// Reserve capacity for at least `additional` more entries.
#[inline(always)]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> {
self.table.reserve_for(additional)
}
/// Insert `key -> value`, returning `Ok(Some(old_value))` if `key` was
/// already present or `Ok(None)` if newly inserted.
///
/// On `Err(AllocError)`, both `key` and `value` are dropped cleanly and
/// existing map entries remain completely untouched.
#[inline(always)]
pub fn try_insert(&mut self, key: K, value: V) -> Result<Option<V>, AllocError> {
let md = ManuallyDrop::new(value);
let mut old = MaybeUninit::<V>::uninit();
// SAFETY: `&md` and `old` are stack-local (disjoint from `self.table.table`)
// with exact layout of `V`.
let res = unsafe {
K::raw_insert(
&mut self.table,
key,
(&*md as *const V) as *const u8,
old.as_mut_ptr() as *mut u8,
)
};
match res {
Ok(true) => {
// SAFETY: `raw_insert` initialized `old` with the displaced `V`
// and moved `md`'s bytes into the slot.
Ok(Some(unsafe { old.assume_init() }))
}
Ok(false) => Ok(None),
Err(err) => {
let _ = ManuallyDrop::into_inner(md);
Err(err)
}
}
}
/// Insert a borrowed key `key -> value` without allocating an intermediate
/// owned key (e.g. passing `&str` directly into `HashMap<String, V>` or
/// `&[u8]` into `HashMap<Vec<u8>, V>`).
///
/// On `Err(AllocError)`, `value` is dropped cleanly and existing entries
/// remain completely untouched.
#[inline(always)]
pub fn try_insert_ref<Q: ?Sized + KeyQuery<K>>(
&mut self,
key: &Q,
value: V,
) -> Result<Option<V>, AllocError> {
let md = ManuallyDrop::new(value);
let mut old = MaybeUninit::<V>::uninit();
// SAFETY: `&md` and `old` are stack-local (disjoint from `self.table.table`)
// with exact layout of `V`.
let res = unsafe {
key.raw_insert_ref(
&mut self.table,
(&*md as *const V) as *const u8,
old.as_mut_ptr() as *mut u8,
)
};
match res {
Ok(true) => {
// SAFETY: `raw_insert_ref` initialized `old` with the displaced `V`.
Ok(Some(unsafe { old.assume_init() }))
}
Ok(false) => Ok(None),
Err(err) => {
let _ = ManuallyDrop::into_inner(md);
Err(err)
}
}
}
/// Look up `key`, returning a shared reference to its stored value if present.
#[inline(always)]
pub fn get<Q: ?Sized + KeyQuery<K>>(&self, key: &Q) -> Option<&V> {
let p = key.raw_get_ptr(&self.table);
if p.is_null() {
None
} else {
// SAFETY: `p` is `align_of::<V>()`-aligned and points to a live `V`.
Some(unsafe { &*(p as *const V) })
}
}
/// Look up `key`, returning a mutable reference to its stored value if present.
#[inline(always)]
pub fn get_mut<Q: ?Sized + KeyQuery<K>>(&mut self, key: &Q) -> Option<&mut V> {
let p = key.raw_get_ptr(&self.table) as *mut u8;
if p.is_null() {
None
} else {
// SAFETY: `p` is `align_of::<V>()`-aligned and points to an
// exclusively owned live `V`.
Some(unsafe { &mut *(p as *mut V) })
}
}
/// Return `true` if `key` is present in the map.
#[inline(always)]
pub fn contains_key<Q: ?Sized + KeyQuery<K>>(&self, key: &Q) -> bool {
!key.raw_get_ptr(&self.table).is_null()
}
/// Remove `key` and return its stored value, or `None` if absent.
#[inline(always)]
pub fn remove<Q: ?Sized + KeyQuery<K>>(&mut self, key: &Q) -> Option<V> {
let mut out = MaybeUninit::<V>::uninit();
// SAFETY: `out` is stack-local and valid for `size_of::<V>()` bytes.
let removed = unsafe { key.raw_remove(&mut self.table, out.as_mut_ptr() as *mut u8) };
if removed {
// SAFETY: `raw_remove` moved the stored `V` into `out`.
Some(unsafe { out.assume_init() })
} else {
None
}
}
/// Drop every live value in place using the verified `next_occupied_val_ptr` cursor.
#[inline(always)]
fn drop_values_in_place(&mut self) {
if needs_drop::<V>() && self.table.len > 0 {
let mut cursor: usize = 0;
loop {
let vp = self.table.next_occupied_val_ptr(&mut cursor);
if vp.is_null() {
break;
}
// SAFETY: `vp` points to a live, initialized, `align_of::<V>()`-aligned
// `V` inside an occupied bucket, dropped once immediately prior to
// `raw_clear` or `raw_free_all`.
unsafe {
ptr::drop_in_place(vp as *mut V);
}
}
}
}
/// Remove and drop all entries while retaining the allocated bucket array.
#[inline(always)]
pub fn clear(&mut self) {
self.drop_values_in_place();
K::raw_clear(&mut self.table);
}
/// Return the number of live entries in the map.
#[inline(always)]
pub const fn len(&self) -> usize {
self.table.len
}
/// Return the current allocated bucket capacity (`0` or a power of 2 `>= 8`).
#[inline(always)]
pub const fn capacity(&self) -> usize {
self.table.cap
}
/// Return `true` if the map contains no entries.
#[inline(always)]
pub const fn is_empty(&self) -> bool {
self.table.len == 0
}
}
impl<K: Key, V> Default for HashMap<K, V> {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
impl<K: Key, V> Drop for HashMap<K, V> {
#[inline(always)]
fn drop(&mut self) {
self.drop_values_in_place();
K::raw_free_all(&mut self.table);
}
}