| // 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. | |
| //! Non-generic verified open-addressed linear-probing map for heap-owned byte | |
| //! keys ([`RawBytesMap`], seeded SipHash-1-3, native `&[u8] == &[u8]` / `memcmp`). | |
| use core::mem::{align_of, size_of}; | |
| use core::{ptr, slice}; | |
| use vx_alloc::alloc::{AllocError, raw_alloc, raw_dealloc}; | |
| use crate::collections::raw_table::{ | |
| HEADER_ALIGN, RawTable, SlotPrefix, SlotState, compute_slot_layout, hash_bytes_seeded, | |
| }; | |
| /// 32-byte slot header for heap-owned byte-slice keys. | |
| #[repr(C)] | |
| struct BytesSlotHeader { | |
| prefix: SlotPrefix, | |
| key_ptr: *mut u8, | |
| key_len: usize, | |
| } | |
| pub(crate) const BYTES_HEADER_SIZE: usize = size_of::<BytesSlotHeader>(); | |
| const _: () = assert!(BYTES_HEADER_SIZE == 32); | |
| const _: () = assert!(align_of::<BytesSlotHeader>() == HEADER_ALIGN); | |
| /// Allocate a heap copy of `key` (returns null without allocating when empty). | |
| #[curry::verified] | |
| unsafe fn alloc_key_copy(key: &[u8]) -> Result<*mut u8, AllocError> { | |
| let len = key.len(); | |
| if len == 0 { | |
| return Ok(ptr::null_mut()); | |
| } | |
| // SAFETY: `len > 0` and alignment is 1. | |
| let nn = unsafe { raw_alloc(len, 1)? }; | |
| // SAFETY: `nn` is freshly allocated and valid for `len` bytes. | |
| unsafe { | |
| ptr::copy_nonoverlapping(key.as_ptr(), nn.as_ptr(), len); | |
| } | |
| Ok(nn.as_ptr()) | |
| } | |
| /// Free a heap-allocated key buffer if `key_len > 0`. | |
| #[inline(always)] | |
| unsafe fn free_key_buf(key_ptr: *mut u8, key_len: usize) { | |
| if key_len > 0 && !key_ptr.is_null() { | |
| // SAFETY: Key buffers are always allocated with alignment 1 and exact `key_len`. | |
| unsafe { | |
| raw_dealloc(key_ptr, key_len, 1); | |
| } | |
| } | |
| } | |
| /// Non-generic open-addressed linear-probing map with heap-owned byte keys and | |
| /// fixed-layout value bytes. | |
| #[repr(transparent)] | |
| pub struct RawBytesMap(pub(crate) RawTable); | |
| const _: () = assert!(size_of::<RawBytesMap>() == 64); | |
| const _: () = assert!(align_of::<RawBytesMap>() == 8); | |
| impl RawBytesMap { | |
| /// Construct an empty [`RawBytesMap`] for values of layout `(val_size, val_align)`. | |
| #[inline(always)] | |
| pub const fn new(val_size: usize, val_align: usize) -> Option<Self> { | |
| let Some((val_offset, slot_stride, slot_align)) = | |
| compute_slot_layout(BYTES_HEADER_SIZE, val_size, val_align) | |
| else { | |
| return None; | |
| }; | |
| Some(Self(RawTable::empty(val_size, val_offset, slot_stride, slot_align))) | |
| } | |
| #[inline(always)] | |
| pub(crate) const fn from_table_ref(t: &RawTable) -> &Self { | |
| // SAFETY: `RawBytesMap` is `#[repr(transparent)]` over `RawTable`. | |
| unsafe { &*(t as *const RawTable as *const Self) } | |
| } | |
| #[inline(always)] | |
| pub(crate) fn from_table_mut(t: &mut RawTable) -> &mut Self { | |
| // SAFETY: `RawBytesMap` is `#[repr(transparent)]` over `RawTable`. | |
| unsafe { &mut *(t as *mut RawTable as *mut Self) } | |
| } | |
| /// Return the number of live entries. | |
| #[inline(always)] | |
| pub const fn len(&self) -> usize { | |
| self.0.len | |
| } | |
| /// Return the allocated bucket count (`0` or a power of 2 `>= 8`). | |
| #[inline(always)] | |
| pub const fn capacity(&self) -> usize { | |
| self.0.cap | |
| } | |
| /// Return `true` if the map contains no entries. | |
| #[inline(always)] | |
| pub const fn is_empty(&self) -> bool { | |
| self.0.len == 0 | |
| } | |
| /// Reserve capacity for at least `additional` more entries. | |
| #[inline(always)] | |
| pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> { | |
| self.0.reserve_for(additional) | |
| } | |
| /// Advance `*cursor` to the next occupied slot and return a mutable pointer | |
| /// to its value bytes, or null when finished. | |
| #[inline(always)] | |
| pub fn next_occupied_val_ptr(&self, cursor: &mut usize) -> *mut u8 { | |
| self.0.next_occupied_val_ptr(cursor) | |
| } | |
| /// Probe for an occupied bucket matching `(key, hash)` using native | |
| /// `&[u8] == &[u8]` (lowered to `memcmp`/`bcmp`, zero hand-rolled loops). | |
| #[curry::verified] | |
| fn find_slot(&self, key: &[u8], hash: u64) -> Option<usize> { | |
| if self.0.table.is_null() || self.0.cap == 0 { | |
| return None; | |
| } | |
| let mask = self.0.cap - 1; | |
| let key_len = key.len(); | |
| let mut idx = (hash as usize) & mask; | |
| let mut steps: usize = 0; | |
| while steps < self.0.cap { | |
| // SAFETY: `idx < self.0.cap` and `self.0.table` holds `self.0.cap` slots. | |
| let hdr = unsafe { &*(self.0.slot_ptr(idx) as *const BytesSlotHeader) }; | |
| if hdr.prefix.state == SlotState::Empty { | |
| return None; | |
| } | |
| if hdr.prefix.hash == hash && hdr.key_len == key_len { | |
| if key_len == 0 { | |
| return Some(idx); | |
| } | |
| if !hdr.key_ptr.is_null() { | |
| // SAFETY: `hdr.key_ptr` is non-null and initialized for `key_len` bytes. | |
| let stored = unsafe { slice::from_raw_parts(hdr.key_ptr, key_len) }; | |
| if stored == key { | |
| return Some(idx); | |
| } | |
| } | |
| } | |
| idx = (idx + 1) & mask; | |
| steps += 1; | |
| } | |
| None | |
| } | |
| /// Look up `key`, returning a raw pointer to its stored value bytes or null | |
| /// if absent. | |
| #[curry::verified] | |
| pub fn get_ptr(&self, key: &[u8]) -> *const u8 { | |
| if self.0.len == 0 || self.0.cap == 0 || self.0.table.is_null() { | |
| return ptr::null(); | |
| } | |
| let hash = hash_bytes_seeded(self.0.seed, key); | |
| let Some(idx) = self.find_slot(key, hash) else { | |
| return ptr::null(); | |
| }; | |
| // SAFETY: `idx < self.0.cap`, so `slot_ptr(idx) + val_offset` lies in slot `idx`. | |
| unsafe { self.0.slot_ptr(idx).add(self.0.val_offset) as *const u8 } | |
| } | |
| /// Populate empty bucket `idx` with a new occupied entry and increment `len`. | |
| #[curry::verified] | |
| unsafe fn write_new_slot( | |
| &mut self, | |
| idx: usize, | |
| hash: u64, | |
| key_ptr: *mut u8, | |
| key_len: usize, | |
| val_src: *const u8, | |
| ) { | |
| // SAFETY: Caller guarantees `idx < self.0.cap` is an empty bucket. | |
| let dst_slot = unsafe { self.0.slot_ptr(idx) }; | |
| unsafe { | |
| ptr::write( | |
| dst_slot as *mut BytesSlotHeader, | |
| BytesSlotHeader { | |
| prefix: SlotPrefix { state: SlotState::Occupied, hash }, | |
| key_ptr, | |
| key_len, | |
| }, | |
| ); | |
| if self.0.val_size > 0 { | |
| ptr::copy_nonoverlapping(val_src, dst_slot.add(self.0.val_offset), self.0.val_size); | |
| } | |
| } | |
| self.0.len += 1; | |
| } | |
| /// Insert or overwrite `key` with `val_size` bytes from `val_src`. | |
| /// | |
| /// Returns `Ok(true)` if `key` already existed (copying its previous value | |
| /// bytes into `old_val_out` when non-null), or `Ok(false)` if newly inserted. | |
| /// On `Err(AllocError)`, existing entries remain untouched and zero bytes leak. | |
| /// | |
| /// # Safety | |
| /// | |
| /// When `val_size > 0`, `val_src` (and non-null `old_val_out`) must be valid | |
| /// for `val_size` bytes and disjoint from `self.0.table`. | |
| #[curry::verified] | |
| pub unsafe fn try_insert_raw( | |
| &mut self, | |
| key: &[u8], | |
| val_src: *const u8, | |
| old_val_out: *mut u8, | |
| ) -> Result<bool, AllocError> { | |
| let existing_hash = if self.0.cap > 0 { | |
| let h = hash_bytes_seeded(self.0.seed, key); | |
| if let Some(existing) = self.find_slot(key, h) { | |
| // SAFETY: `existing < self.0.cap`, forwarded from caller. | |
| unsafe { | |
| self.0.overwrite_slot(existing, val_src, old_val_out); | |
| } | |
| return Ok(true); | |
| } | |
| Some(h) | |
| } else { | |
| None | |
| }; | |
| // Allocate key copy first so OOM during rehash leaves `self.0.cap` | |
| // untouched and rolls back the key copy cleanly. | |
| // SAFETY: Allocates an exact-length byte copy via `raw_alloc`. | |
| let key_ptr = unsafe { alloc_key_copy(key)? }; | |
| if let Err(err) = self.0.ensure_insert_capacity() { | |
| // SAFETY: Roll back the freshly allocated key copy on rehash OOM. | |
| unsafe { | |
| free_key_buf(key_ptr, key.len()); | |
| } | |
| return Err(err); | |
| } | |
| // Reuse the hash computed above whenever `cap > 0` (the seed only | |
| // initializes on the `cap == 0` -> `INITIAL_MAP_CAP` transition). | |
| let hash = match existing_hash { | |
| Some(h) => h, | |
| None => hash_bytes_seeded(self.0.seed, key), | |
| }; | |
| let Some(dst_idx) = self.0.find_empty_slot(hash) else { | |
| // SAFETY: Defensive rollback if table invariant was violated. | |
| unsafe { | |
| free_key_buf(key_ptr, key.len()); | |
| } | |
| return Err(AllocError); | |
| }; | |
| // SAFETY: `dst_idx < self.0.cap` is an empty bucket. | |
| unsafe { | |
| self.write_new_slot(dst_idx, hash, key_ptr, key.len(), val_src); | |
| } | |
| Ok(false) | |
| } | |
| /// Remove `key`, copying its value bytes into `out_val` when non-null. | |
| /// | |
| /// # Safety | |
| /// | |
| /// When `val_size > 0` and `out_val` is non-null, `out_val` must be valid | |
| /// for writes of `val_size` bytes disjoint from `self.0.table`. | |
| #[curry::verified] | |
| pub unsafe fn remove_raw(&mut self, key: &[u8], out_val: *mut u8) -> bool { | |
| if self.0.len == 0 || self.0.cap == 0 || self.0.table.is_null() { | |
| return false; | |
| } | |
| let hash = hash_bytes_seeded(self.0.seed, key); | |
| let Some(idx) = self.find_slot(key, hash) else { | |
| return false; | |
| }; | |
| // SAFETY: `idx < self.0.cap` is an occupied slot. | |
| let slot = unsafe { self.0.slot_ptr(idx) }; | |
| let hdr = unsafe { &*(slot as *const BytesSlotHeader) }; | |
| let key_ptr = hdr.key_ptr; | |
| let key_len = hdr.key_len; | |
| if !out_val.is_null() && self.0.val_size > 0 { | |
| // SAFETY: `out_val` is disjoint and valid for `self.0.val_size` bytes. | |
| unsafe { | |
| ptr::copy_nonoverlapping(slot.add(self.0.val_offset), out_val, self.0.val_size); | |
| } | |
| } | |
| // SAFETY: Free the removed entry's heap key copy. | |
| unsafe { | |
| free_key_buf(key_ptr, key_len); | |
| } | |
| self.0.len -= 1; | |
| self.0.backward_shift(idx); | |
| true | |
| } | |
| /// Free all stored key buffers and mark every bucket empty while retaining | |
| /// the allocated bucket array. | |
| #[curry::verified] | |
| pub fn clear(&mut self) { | |
| if self.0.table.is_null() || self.0.cap == 0 { | |
| self.0.len = 0; | |
| return; | |
| } | |
| let mut i: usize = 0; | |
| while i < self.0.cap { | |
| // SAFETY: `i < self.0.cap` and `self.0.table` holds `self.0.cap` slots. | |
| let hdr = unsafe { &mut *(self.0.slot_ptr(i) as *mut BytesSlotHeader) }; | |
| if hdr.prefix.state == SlotState::Occupied { | |
| let kp = hdr.key_ptr; | |
| let kl = hdr.key_len; | |
| hdr.prefix.state = SlotState::Empty; | |
| hdr.prefix.hash = 0; | |
| hdr.key_ptr = ptr::null_mut(); | |
| hdr.key_len = 0; | |
| // SAFETY: `kp` was allocated for this occupied slot. | |
| unsafe { | |
| free_key_buf(kp, kl); | |
| } | |
| } | |
| i += 1; | |
| } | |
| self.0.len = 0; | |
| } | |
| /// Free every key buffer and the bucket array itself, resetting to empty. | |
| #[curry::verified] | |
| pub fn free_all(&mut self) { | |
| self.clear(); | |
| self.0.free_table_buf(); | |
| } | |
| } | |
| impl Drop for RawBytesMap { | |
| #[curry::verified] | |
| fn drop(&mut self) { | |
| self.free_all(); | |
| } | |
| } |