Skip to content
2 changes: 2 additions & 0 deletions src/codegen/generate-js2native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const sourceFiles = readdirRecursiveWithExclusionsAndExtensionsSync(
const rustIdentifierPaths: Record<string, string> = {
"bun.rs": "bun.rs",
"ipc.rs": "runtime/ipc_host.rs",
"ConsoleObject.rs": "jsc/ConsoleObject.rs",
"Counters.rs": "jsc/Counters.rs",
"FrameworkRouter.rs": "runtime/bake/FrameworkRouter.rs",
"JSBundler.rs": "runtime/api/JSBundler.rs",
Expand Down Expand Up @@ -87,6 +88,7 @@ const rustIdentifierPaths: Record<string, string> = {
"patch.rs": "patch/patch.rs",
"postgres.rs": "sql_jsc/postgres.rs",
"runtime/dns_jsc/dns.rs": "runtime/dns_jsc/dns.rs",
"runtime/hash_map_testing.rs": "runtime/hash_map_testing.rs",
"runtime/node/types.rs": "runtime/node/types.rs",
"runtime/socket/socket.rs": "runtime/socket/socket.rs",
"runtime/timer/Timer.rs": "runtime/timer/Timer.rs",
Expand Down
4 changes: 2 additions & 2 deletions src/collections/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,8 @@ impl<T, const N: usize> SmallList<T, N> {
// ──────────────────────────────────────────────────────────────────────────
// HashMap
//
// Linear-probe layout (open-addressing, tombstones, power-of-two cap,
// 80% load) with deterministic iteration order — required by callers that
// Linear-probe layout (open-addressing, backward-shift delete, power-of-two
// cap, 80% load) with deterministic iteration order — required by callers that
Comment thread
robobun marked this conversation as resolved.
Resolved
// snapshot the iteration sequence (lockfile debug stringify, etc.). The `Ctx`
// type parameter is load-bearing: `AutoHashContext` wyhashes the key,
// `IdentityContext<K>` uses `k as u64` so pre-hashed keys aren't re-hashed.
Expand Down
274 changes: 233 additions & 41 deletions src/collections/zig_hash_map.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Open-addressing hash map — linear-probe, tombstone-on-delete, power-of-two
//! capacity, 80% max load. Layout (and therefore iteration order) is
//! load-bearing: callers snapshot the iteration sequence (e.g. lockfile debug
//! stringify).
//! Open-addressing hash map — linear-probe, backward-shift delete, power-of-two
//! capacity, 80% max load. The layout of a map that only inserts (and
//! therefore its iteration order) is load-bearing: callers snapshot the
//! iteration sequence (e.g. lockfile debug stringify). A removal walks and
//! reorders its run, which stays short only when the hash spreads the keys.
Comment thread
robobun marked this conversation as resolved.
Resolved
//!
//! Storage is split: `Vec<u8>` for metadata + `Vec<Option<(K, V)>>` for
//! slots. This costs an `Option` discriminant per slot but keeps the
Expand All @@ -17,24 +18,11 @@ use crate::identity_context::{IdentityContext, IdentityHash};
// ─── Metadata byte ─────────────────────────────────────────────────────────
// bit 7 = `used`, bits 0..7 = `fingerprint`.
const SLOT_FREE: u8 = 0x00; // used=0, fp=0
const SLOT_TOMBSTONE: u8 = 0x01; // used=0, fp=1

#[inline]
fn meta_is_used(m: u8) -> bool {
m & 0x80 != 0
}
#[inline]
fn meta_is_free(m: u8) -> bool {
m == SLOT_FREE
}
#[inline]
fn meta_is_tombstone(m: u8) -> bool {
m == SLOT_TOMBSTONE
}
#[inline]
fn meta_fingerprint(m: u8) -> u8 {
m & 0x7F
}
/// Top 7 bits of the 64-bit hash.
#[inline]
fn take_fingerprint(hash: u64) -> u8 {
Expand Down Expand Up @@ -101,7 +89,7 @@ pub struct HashMap<K, V, C = AutoHashContext> {
metadata: Vec<u8>,
slots: Vec<Option<(K, V)>>,
size: u32,
/// Slots writable before a grow (counts free *and* tombstone consumption).
/// Entries that fit before a grow.
available: u32,
_ctx: PhantomData<C>,
}
Expand Down Expand Up @@ -298,7 +286,7 @@ impl<K, V, C: HashContext<K>> HashMap<K, V, C> {
self.size += 1;
}

/// Probe for `key`, stop on free, skip tombstones.
/// Probe for `key`, stop on free. A run always ends at a free slot.
fn get_index<Q>(&self, key: &Q) -> Option<usize>
where
K: Borrow<Q>,
Expand All @@ -308,22 +296,19 @@ impl<K, V, C: HashContext<K>> HashMap<K, V, C> {
if self.size == 0 {
return None;
}
let cap = self.metadata.len();
let hash = C::ctx_hash(key);
let mask = cap - 1;
let fp = take_fingerprint(hash);
let mut limit = cap;
let mask = self.metadata.len() - 1;
let meta = meta_fill(take_fingerprint(hash));
let mut idx = (hash as usize) & mask;

while !meta_is_free(self.metadata[idx]) && limit != 0 {
if meta_is_used(self.metadata[idx]) && meta_fingerprint(self.metadata[idx]) == fp {
while meta_is_used(self.metadata[idx]) {
if self.metadata[idx] == meta {
if let Some((k, _)) = &self.slots[idx] {
if C::ctx_eql(key, k.borrow()) {
return Some(idx);
}
}
}
limit -= 1;
idx = (idx + 1) & mask;
}
None
Expand Down Expand Up @@ -381,33 +366,24 @@ impl<K, V, C: HashContext<K>> HashMap<K, V, C> {
fn get_or_put_slot(&mut self, key: &K) -> (usize, bool) {
self.grow_if_needed(1);

let cap = self.metadata.len();
let hash = C::ctx_hash(key);
let mask = cap - 1;
let fp = take_fingerprint(hash);
let mut limit = cap;
let mask = self.metadata.len() - 1;
let meta = meta_fill(take_fingerprint(hash));
let mut idx = (hash as usize) & mask;
let mut first_tombstone_idx = cap; // invalid sentinel

while !meta_is_free(self.metadata[idx]) && limit != 0 {
if meta_is_used(self.metadata[idx]) && meta_fingerprint(self.metadata[idx]) == fp {
while meta_is_used(self.metadata[idx]) {
if self.metadata[idx] == meta {
if let Some((k, _)) = &self.slots[idx] {
if C::ctx_eql(key, k) {
return (idx, true);
}
}
} else if first_tombstone_idx == cap && meta_is_tombstone(self.metadata[idx]) {
first_tombstone_idx = idx;
}
limit -= 1;
idx = (idx + 1) & mask;
}

if first_tombstone_idx < cap {
idx = first_tombstone_idx;
}
self.available -= 1;
self.metadata[idx] = meta_fill(fp);
self.metadata[idx] = meta;
self.size += 1;
(idx, false)
}
Expand Down Expand Up @@ -473,9 +449,23 @@ impl<K, V, C: HashContext<K>> HashMap<K, V, C> {
Ok(())
}

/// Backward-shift delete (Knuth, TAOCP 6.4, Algorithm R): leaves no tombstone.
fn remove_by_index(&mut self, idx: usize) -> Option<(K, V)> {
self.metadata[idx] = SLOT_TOMBSTONE;
let kv = self.slots[idx].take();
let mask = self.metadata.len() - 1;
let mut hole = idx;
let mut next = (idx + 1) & mask;
while let Some((key, _)) = &self.slots[next] {
let home = (C::ctx_hash(key) as usize) & mask;
// Move `next` into the hole only if the hole is on its probe path.
if (hole.wrapping_sub(home) & mask) < (next.wrapping_sub(home) & mask) {
self.metadata[hole] = self.metadata[next];
self.slots[hole] = self.slots[next].take();
hole = next;
}
next = (next + 1) & mask;
}
self.metadata[hole] = SLOT_FREE;
self.size -= 1;
self.available += 1;
kv
Expand Down Expand Up @@ -694,3 +684,205 @@ impl<'a, K, V, C: HashContext<K>> VacantEntry<'a, K, V, C> {
&mut self.map.slots[idx].as_mut().unwrap().1
}
}

#[cfg(test)]
mod tests {
use super::*;

/// Five home slots for every key: long runs in a small table.
struct FiveHomes;
impl HashContext<u64> for FiveHomes {
fn ctx_hash(key: &u64) -> u64 {
(key % 5) | (key << 57)
}
fn ctx_eql(a: &u64, b: &u64) -> bool {
a == b
}
}

/// Home slots at the end of the table: every run wraps around to slot 0.
struct LastSlots;
impl HashContext<u64> for LastSlots {
fn ctx_hash(key: &u64) -> u64 {
u64::MAX - (key % 3)
}
fn ctx_eql(a: &u64, b: &u64) -> bool {
a == b
}
}

fn xorshift(state: &mut u64) -> u64 {
*state ^= *state >> 12;
*state ^= *state << 25;
*state ^= *state >> 27;
state.wrapping_mul(0x2545_F491_4F6C_DD1D)
}

fn slot_keys<C>(map: &HashMap<u64, u64, C>, slots: usize) -> Vec<Option<u64>> {
map.slots[..slots]
.iter()
.map(|slot| slot.map(|kv| kv.0))
.collect()
}

/// Each entry is reachable from its home slot, and every other slot is free.
fn check<C: HashContext<u64>>(map: &HashMap<u64, u64, C>, model: &[Option<u64>]) {
let expected = model.iter().flatten().count();
assert_eq!(map.len(), expected);
let cap = map.metadata.len();
if cap == 0 {
return;
}
let mask = cap - 1;
let mut used = 0;
for i in 0..cap {
let Some((key, value)) = map.slots[i] else {
assert_eq!(map.metadata[i], SLOT_FREE, "slot {i} holds no entry");
continue;
};
used += 1;
assert_eq!(model[key as usize], Some(value));
let hash = C::ctx_hash(&key);
assert_eq!(map.metadata[i], meta_fill(take_fingerprint(hash)));
let mut j = (hash as usize) & mask;
while j != i {
assert!(
meta_is_used(map.metadata[j]),
"key {key} in slot {i}: slot {j} on its probe path is free"
);
j = (j + 1) & mask;
}
}
assert_eq!(used, expected);
assert_eq!(map.available as usize, cap * 80 / 100 - used);
}

fn run_against_model<C: HashContext<u64>>(seed: u64, key_space: usize, operations: usize) {
let mut state = seed | 1;
let mut map: HashMap<u64, u64, C> = HashMap::new();
let mut model: Vec<Option<u64>> = vec![None; key_space];
for op in 0..operations {
let key = xorshift(&mut state) % key_space as u64;
let value = xorshift(&mut state);
let slot = &mut model[key as usize];
match xorshift(&mut state) % 100 {
0..=29 => assert_eq!(map.insert(key, value), slot.replace(value)),
30..=39 => {
let entry = map.get_or_put(key).unwrap();
assert_eq!(entry.found_existing, slot.is_some());
*entry.value_ptr = value;
*slot = Some(value);
}
40..=44 => {
let got = *map.entry(key).or_insert_with(|| value);
assert_eq!(got, *slot.get_or_insert(value));
}
45..=79 => assert_eq!(map.remove(&key), slot.take()),
80..=84 => {
let got = map.fetch_remove(&key).map(|kv| (kv.key, kv.value));
assert_eq!(got, slot.take().map(|value| (key, value)));
}
85..=94 => assert_eq!(map.get(&key), slot.as_ref()),
95..=96 => map.reserve((value % 40) as usize),
97 => {
// Empty the map in key order: the first entry of each run goes first.
for (key, slot) in model.iter_mut().enumerate() {
assert_eq!(map.remove(&(key as u64)), slot.take());
}
}
_ => {
if value.is_multiple_of(8) {
map.clear();
model.fill(None);
}
}
}
if !cfg!(miri) || op % 8 == 7 {
check(&map, &model);
}
}
check(&map, &model);
}

// CI runs these under Miri, which interprets each statement: fewer operations and checks there.
const OPERATIONS: usize = if cfg!(miri) { 150 } else { 20_000 };

#[test]
fn agrees_with_a_model_wyhash() {
run_against_model::<AutoHashContext>(1, 48, OPERATIONS);
}

#[test]
fn agrees_with_a_model_long_runs() {
run_against_model::<FiveHomes>(3, 60, OPERATIONS);
}

#[test]
fn agrees_with_a_model_runs_that_wrap() {
run_against_model::<LastSlots>(4, 40, OPERATIONS);
}

#[test]
fn insert_only_order_is_fixed() {
// The slot is `key & mask`, so the order shows where collisions and the two grows put each key.
let mut map: HashMap<u64, (), IdentityContext<u64>> = HashMap::new();
for key in [17, 9, 1, 33, 2, 10, 49, 3, 25, 41, 57, 18, 26, 11] {
map.insert(key, ());
}
assert_eq!(map.capacity(), 32);
let order: Vec<u64> = map.keys().copied().collect();
assert_eq!(order, [1, 33, 2, 3, 9, 10, 41, 11, 17, 49, 18, 25, 57, 26]);
}

#[test]
fn removal_moves_back_the_entries_that_probed_past_it() {
// 0, 5, 10, 15 share home slot 0 and fill slots 0..=3. 1 has home slot 1 and lands in slot 4.
let mut map: HashMap<u64, u64, FiveHomes> = HashMap::new();
for key in [0, 5, 10, 15, 1] {
map.insert(key, key);
}
assert_eq!(map.remove(&5), Some(5));
assert_eq!(
slot_keys(&map, 5),
[Some(0), Some(10), Some(15), Some(1), None]
);
assert_eq!(map.metadata[4], SLOT_FREE);
for key in [0, 10, 15, 1] {
assert_eq!(map.get(&key), Some(&key));
}
assert_eq!(map.get(&5), None);
}

#[test]
fn removal_leaves_an_entry_in_its_home_slot() {
// 0 and 5 share home slot 0 and fill slots 0 and 1. 2 sits in its home slot 2.
let mut map: HashMap<u64, u64, FiveHomes> = HashMap::new();
for key in [0, 5, 2] {
map.insert(key, key);
}
assert_eq!(map.remove(&0), Some(0));
assert_eq!(slot_keys(&map, 3), [Some(5), None, Some(2)]);
}

#[test]
fn a_churn_of_distinct_keys_leaves_free_slots() {
const LIVE: u64 = 64;
const CYCLES: u64 = if cfg!(miri) { 300 } else { 50_000 };
let mut map: HashMap<u64, ()> = HashMap::new();
for key in 0..LIVE {
map.insert(key, ());
}
for cycle in 0..CYCLES {
assert_eq!(map.remove(&cycle), Some(()));
map.insert(LIVE + cycle, ());
}
assert_eq!(map.len(), LIVE as usize);
assert_eq!(map.capacity(), 128);
let free = map
.metadata
.iter()
.filter(|&&meta| meta == SLOT_FREE)
.count();
assert_eq!(free, 128 - LIVE as usize);
}
}
11 changes: 11 additions & 0 deletions src/js/internal-for-testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,17 @@ export const linearFifoOrderedRemoveProbe = $newRustFunction(
"TestingAPIs.orderedRemoveProbe",
1,
) as (scenario: number) => number[];
export const consoleTableSizes = $newRustFunction("ConsoleObject.rs", "tableSizesForTesting", 0) as () => {
timerEntries: number;
timerCapacity: number;
countEntries: number;
countCapacity: number;
};
/** `maxComparisons`: the most stored entries that a lookup of an absent key is compared against. */
export const hashMapChurnProbe = $newRustFunction("runtime/hash_map_testing.rs", "churnProbe", 2) as (
live: number,
cycles: number,
) => { capacity: number; length: number; maxComparisons: number };
export const hasNonReifiedStatic = $newCppFunction("InternalForTesting.cpp", "jsFunction_hasReifiedStatic", 1);

interface setSocketOptionsFn {
Expand Down
Loading
Loading