AI 代码审查实战:有界布谷鸟哈希表如何在重建失败后保住旧数据
让 AI 写一个哈希表,几分钟就能得到一段看起来完整的代码。真正值得审查的,却常常是那个没有出现在演示里的分支:新键碰撞了,旧键被挤出来,重试次数耗尽,此时旧数据还在不在?本文用一个有明确资源上限的 JavaScript 布谷鸟哈希映射,把这个问题拆成可以运行、可以反驳、也可以复查的九组实验。

这是一篇代码审查与验证教程。实现保存完整键和值,支持精确查询;它不是只保存短指纹、允许误报的布谷鸟过滤器。它也不维护探测距离,不使用 Robin Hood 哈希的距离比较或后移删除。这里的核心不变量只有一个:每个键恰好放在自己的两个候选槽之一。
九个 JavaScript 代码块均可分别保存为 .cjs 文件,独立用 Node.js 运行,不需要拼接前文、安装第三方包或共享进程状态。示例一至八分别验证局部合同或构造反例,示例九给出完整实现与集成测试。输出均来自实际执行;示例五故意展示错误做法,不能当作可用插入函数。
一、先固定键的含义,再讨论哈希值
审查 AI 代码时,我会先删掉“支持任意键”这类未经实现支撑的宣传。本例只接受字符串与 Number,包括 NaN、正负零和正负无穷;字符串最长为 1024 个 UTF-16 代码单元。对象、函数、Symbol、BigInt、布尔值、null 与 undefined 都不属于键域,查询和删除也沿用这项限制。值则可以是任意 JavaScript 值,包括 undefined;值的对象引用不会被深拷贝。
在支持的键域内,相等关系与原生 Map 的 SameValueZero 一致:所有 NaN 视为同一个键,负零与正零视为同一个键,数字 1 与字符串“1”是两个键。ECMAScript 的 Map 规范和 SameValueZero 定义是语义依据,不应凭熟悉的严格相等运算符猜测。
tokenOf 先加类型前缀,再把数值转换为规范字符串;正负零在转换前归一。字符串保留原始代码单元,不做大小写折叠或 Unicode 规范化。因此预组合的“é”和由字母与组合重音构成的字符串仍然不同。这不是显示层面的细节:如果写入时规范化、读取时没有规范化,同一个视觉文本就可能走向不同候选位置。
示例 1:相等合同与拒绝的键域
function tokenOf(key) {
if (typeof key === 'string') {
if (key.length > 1024) throw new RangeError('key too long');
return 's:' + key;
}
if (typeof key === 'number') return 'n:' + String(key === 0 ? 0 : key);
throw new TypeError('keys must be strings or numbers');
}
console.log(tokenOf(NaN) === tokenOf(Number('bad')));
console.log(tokenOf(-0) === tokenOf(+0));
console.log(tokenOf(1) === tokenOf('1'));
console.log(tokenOf('é') === tokenOf('e\u0301'));
for (const key of [{}, 1n, 'x'.repeat(1025)]) {
try { tokenOf(key); } catch (e) { console.log(e.name); }
}精确输出:
true true false false TypeError TypeError RangeError
前两个 true 是必须通过的合并规则;接下来的 false 是必须保留的区分规则。长度限制以 JavaScript 的 length 计数,不能称作“1024 个字符”,因为补充平面字符通常占两个代码单元。错误类型也要测试,不能让不支持的键在隐式字符串化后悄悄混进容器。
二、两个候选位置是两个物理槽位
Pagh 与 Rodler 的 《Cuckoo Hashing》原论文,第 4 节描述了双表结构:每个键在两张表中各有一个位置,实际只占其中一个。本例把两张长度为 m 的表摊平成长度为 2m 的数组,槽号为 side × m + index。两次哈希即使返回相同数字,也不意味着两个候选位置合并,因为它们属于不同的表。
查询必须验证候选槽里的完整 token。哈希结果相同只是碰撞,不是相等。下面把所有键都强制映射到局部下标零:左表已有一个不相关键,右表存着目标键。只看第一个槽,或者拿下标当作身份,都过不了这组最小测试。
示例 2:相同下标仍是不同槽位
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
const capacity = 4, hash = () => 0;
const cells = Array(8).fill(null);
cells[0] = { token: 's:left', value: 11 };
cells[4] = { token: 's:right', value: 22 };
let probes = 0;
function lookup(token) {
for (let side = 0; side < 2; side++) {
const slot = slotOf(token, side, capacity, 1, hash);
probes++;
if (cells[slot]?.token === token) return cells[slot].value;
}
return undefined;
}
console.log([0, 1].map(s => slotOf('s:right', s, capacity, 1, hash)).join(','));
console.log(lookup('s:right'), probes);
probes = 0;
console.log(lookup('s:missing'), probes);精确输出:
0,4 22 2 undefined 2
最多检查两个槽位,是对容器探测次数的描述。默认哈希仍然要读完整 token,字符串比较也可能随长度增长,不能因此把任意长字符串查询的总耗时写成严格常数。本例保留键长上限,就是让输入规模的边界可见,而不是隐藏在“哈希是常数时间”这个假设里。
三、位移前先找完整路径
最常见的写法是立即覆盖候选槽,把旧键拿在手里,再继续踢走下一个键。它很短,却把“搜索”与“修改”耦合在一起。本例选择另一种容易审查的策略:表在搜索期间保持不变,从新键的两个候选槽同时出发,寻找一个空槽;找到后,才沿父指针逆向搬动条目,最后把新键放进路径起点。
每个占用槽的出边只有一个:当前条目的另一张表里的候选位置。搜索使用队列与 head 游标,不调用会整体移动数组元素的 shift。parent 既记录父槽,又充当发现集合;根槽的父值为负一。下面原有 A 位于左表零号,B 位于右表零号,新键 N 的两个位置都被占据。A 能搬到右表一号,所以找到的路径只需要移动一个旧条目。
示例 3:先找空槽,再逆向搬运
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
// The table is unchanged unless a complete path to an empty slot is found.
function place(cells, entry, capacity, seed, hash, budget) {
const parent = new Map();
const queue = [];
for (let side = 0; side < 2; side++) {
const slot = slotOf(entry.token, side, capacity, seed, hash);
parent.set(slot, -1);
queue.push(slot);
}
let head = 0, revisits = 0;
while (head < queue.length && head < budget) {
let slot = queue[head++];
const occupant = cells[slot];
if (occupant === null) {
let moves = 0;
while (parent.get(slot) !== -1) {
const from = parent.get(slot);
cells[slot] = cells[from];
slot = from;
moves++;
}
cells[slot] = entry;
return { ok: true, reason: 'placed', visited: head, revisits, moves };
}
const otherSide = 1 - Math.floor(slot / capacity);
const next = slotOf(occupant.token, otherSide, capacity, seed, hash);
if (parent.has(next)) revisits++;
else { parent.set(next, slot); queue.push(next); }
}
return {
ok: false,
reason: head < queue.length ? 'budget' : 'closed',
visited: head, revisits, moves: 0
};
}
const capacity = 4, cells = Array(8).fill(null);
const pairs = { A: [0, 1], B: [1, 0], N: [0, 0] };
const hash = (token, side) => pairs[token][side];
cells[0] = { token: 'A', value: 10 };
cells[4] = { token: 'B', value: 20 };
const result = place(cells, { token: 'N', value: 30 }, capacity, 1, hash, 8);
console.log(result.ok, result.moves);
console.log(cells.map(x => x?.token ?? '-').join(' '));
console.log(cells.filter(Boolean).map(x => x.value).sort((a,b) => a-b).join(','));精确输出:
true 1 N - - - B A - - 10,20,30
输出中 N 接替 A 原来的位置,A 出现在右表一号,B 留在原处。三个值的集合没有改变,新增值也没有丢失。逆向搬运十分关键:如果从起点向终点直接覆盖,就会在读到后继之前破坏后继原本保存的条目。成功路径中的槽位不重复,因此逆向赋值能够保持整条路径上的内容。
四、循环、汇合与预算不足要分别解释
“发现访问过的槽位”不能直接翻译成“全表插不进去”。两条搜索路径可能汇合,某条分支可能成环,另一条分支却仍然通向空槽。parent 的用途是防止重复入队,截断循环;它不是遇到一次重复就立即宣布失败的开关。搜索图在本次尝试期间不变,这是这种去重方式成立的前提。
place 返回两种失败原因。closed 表示队列已经耗尽,在本次容量、种子与静态候选图下,可达槽位里没有找到空位。budget 表示还有未处理的队列元素,但出队次数达到上限;它只能证明此次搜索未完成,不能证明不存在可用路径。两种失败都不修改传入表。它们都可以触发上层更换种子或扩容,但诊断意义不同。
示例 4:闭合分量和搜索预算不是同一件事
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
// The table is unchanged unless a complete path to an empty slot is found.
function place(cells, entry, capacity, seed, hash, budget) {
const parent = new Map();
const queue = [];
for (let side = 0; side < 2; side++) {
const slot = slotOf(entry.token, side, capacity, seed, hash);
parent.set(slot, -1);
queue.push(slot);
}
let head = 0, revisits = 0;
while (head < queue.length && head < budget) {
let slot = queue[head++];
const occupant = cells[slot];
if (occupant === null) {
let moves = 0;
while (parent.get(slot) !== -1) {
const from = parent.get(slot);
cells[slot] = cells[from];
slot = from;
moves++;
}
cells[slot] = entry;
return { ok: true, reason: 'placed', visited: head, revisits, moves };
}
const otherSide = 1 - Math.floor(slot / capacity);
const next = slotOf(occupant.token, otherSide, capacity, seed, hash);
if (parent.has(next)) revisits++;
else { parent.set(next, slot); queue.push(next); }
}
return {
ok: false,
reason: head < queue.length ? 'budget' : 'closed',
visited: head, revisits, moves: 0
};
}
const cells = Array(8).fill(null), hash = () => 0;
cells[0] = { token: 'A' }; cells[4] = { token: 'B' };
const before = JSON.stringify(cells);
const closed = place(cells, { token: 'N' }, 4, 1, hash, 8);
console.log(closed.reason, closed.visited, closed.revisits);
console.log(JSON.stringify(cells) === before);
const oneFree = Array(8).fill(null);
oneFree[0] = { token: 'A' };
const short = place(oneFree, { token: 'N' }, 4, 1, hash, 1);
console.log(short.reason, oneFree[4] === null);
console.log(place(oneFree, { token: 'N' }, 4, 1, hash, 2).ok);精确输出:
closed 2 2 true budget true true
前一半测试把两个键限制在同一对槽里,第三个键没有可用位置,搜索在两个槽之间遇到重复并结束。后一半故意只给一次出队预算:右表明明是空的,也会返回 budget。把预算提高到二就成功。这能抓出一种很隐蔽的 AI 生成代码错误:把所有失败都记录成“哈希循环”,使后续排障完全找错方向。
五、限制踢出次数,并不会自动保证数据安全
下面是应当拒绝合并的反例。原表只有 A、B,新键是 N。代码最多交换两次,所以不会无限循环;然而停止后 B 留在局部变量 pending 里,表里已经出现未完成插入的 N。如果此时抛异常,或者仅从数组内容收集条目去重建,就会把一个旧键丢掉。运行时间有界与失败原子性,是两项不同的合同。
示例 5:有次数上限的错误代码仍会丢旧键
// Deliberately broken: a budget limits time but does not roll back writes.
const cells = ['A', 'B'];
let pending = 'N';
for (let step = 0; step < 2; step++) {
const slot = step % 2;
[pending, cells[slot]] = [cells[slot], pending];
}
console.log(cells.join(','));
console.log('pending=' + pending);
console.log(['A', 'B'].every(key => cells.includes(key)));
// Rebuilding from cells alone would silently omit the pending old key.精确输出:
N,A pending=B false
这类错误在普通随机测试中不一定容易撞到,因为多数插入能很快找到空槽。审查时应该主动构造“多个键共享两个位置”的小案例,把预算设得很低,让失败分支成为主要路径。计数器在何时增加、异常从哪里抛出、暂时被踢出的条目由谁保存,都要在测试里有观察点。
六、重建是准备完成以后的一次提交
本例的失败原子性定义很具体:一次新键插入或显式 rehash 失败后,原有槽位布局、容量、种子、size,以及保存的键值关联保持不变。重建只操作新数组;所有旧条目和待插入条目都成功放入后,才把候选状态交给提交函数。失败的候选表可以直接丢弃,不需要逐步反向撤销。
下面故意设置一个稳定但很差的哈希函数:种子为一时,三个键有不同位置;任何后续种子都把它们压到同一对槽里。它不是依赖调用次数变化的随机故障,而是完全由入参决定的可复现反例。两次候选重建都失败之后,状态引用以及可序列化内容都保持原样。
示例 6:重建失败后仍保留原状态
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
// The table is unchanged unless a complete path to an empty slot is found.
function place(cells, entry, capacity, seed, hash, budget) {
const parent = new Map();
const queue = [];
for (let side = 0; side < 2; side++) {
const slot = slotOf(entry.token, side, capacity, seed, hash);
parent.set(slot, -1);
queue.push(slot);
}
let head = 0, revisits = 0;
while (head < queue.length && head < budget) {
let slot = queue[head++];
const occupant = cells[slot];
if (occupant === null) {
let moves = 0;
while (parent.get(slot) !== -1) {
const from = parent.get(slot);
cells[slot] = cells[from];
slot = from;
moves++;
}
cells[slot] = entry;
return { ok: true, reason: 'placed', visited: head, revisits, moves };
}
const otherSide = 1 - Math.floor(slot / capacity);
const next = slotOf(occupant.token, otherSide, capacity, seed, hash);
if (parent.has(next)) revisits++;
else { parent.set(next, slot); queue.push(next); }
}
return {
ok: false,
reason: head < queue.length ? 'budget' : 'closed',
visited: head, revisits, moves: 0
};
}
function rebuildAtomically(old, entries, hash) {
for (let seed = old.seed + 1; seed <= old.seed + 2; seed++) {
const candidate = { capacity: old.capacity, seed,
cells: Array(2 * old.capacity).fill(null) };
if (entries.every(e => place(candidate.cells, e,
candidate.capacity, seed, hash, 16).ok)) return candidate;
}
throw new RangeError('bounded rebuild failed');
}
const hash = (token, side, capacity, seed) => seed === 1
? token.charCodeAt(0) % capacity : 0;
const entries = ['A', 'B', 'C'].map(token => ({ token, value: token }));
let state = { capacity: 8, seed: 1, cells: Array(16).fill(null) };
entries.forEach(e => place(state.cells, e, 8, 1, hash, 16));
const before = JSON.stringify(state), original = state;
try { state = rebuildAtomically(state, entries, hash); }
catch (e) { console.log(e.message); }
console.log(state === original, JSON.stringify(state) === before);
console.log(state.cells.filter(Boolean).map(e => e.token).sort().join(','));精确输出:
bounded rebuild failed true true A,B,C
正式实现还会尝试更大容量,但容量也有上限。若所有允许的候选都失败,它抛出 RangeError,绝不无限递归重试。这里的“原子”仅指同一个 JavaScript 调用中的容器状态提交,不是多线程原子指令、持久化事务或崩溃恢复协议。代码没有 await,提交阶段也不调用用户代码,因此正常同步调用不会观察到分步提交的中间状态。
哈希回调的合同同样重要:它必须纯粹、确定、会终止,返回指定范围内的整数,不得重入并修改容器。代码会检查返回下标,但无法替调用方证明纯度或终止性。对外部对象值的修改、恶意回调的副作用、进程被终止以及内存耗尽,也不属于回滚承诺。
七、删除不需要墓碑,undefined 需要 has
线性探测的查询可能沿着一段连续区间前进,因此直接清空中间槽会切断搜索链。布谷鸟查询只访问两个固定候选槽,本例删除时把命中的槽设为 null 即可,不需要墓碑或后移压缩;其他键的两个候选位置没有因此改变。重复删除应返回 false,删除缺失键不应改变 size。
null 是内部空槽标记,真实条目是包装对象,值本身可以为 null 或 undefined。get 返回 undefined 时,既可能是没有这个键,也可能是值恰好等于 undefined,所以要用 has 判断存在性。下面刻意删除左表条目,再读取同一对候选中的右表条目,防止实现偷懒地把“第一格为空”当成整个查询结束。
示例 7:删除一侧后仍能读取另一侧
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
const cells = Array(8).fill(null), hash = () => 0;
cells[0] = { token: 's:A', value: undefined };
cells[4] = { token: 's:B', value: 2 };
function find(token) {
for (let side = 0; side < 2; side++) {
const slot = slotOf(token, side, 4, 1, hash);
if (cells[slot]?.token === token) return slot;
}
return -1;
}
function remove(token) {
const slot = find(token);
if (slot < 0) return false;
cells[slot] = null; return true;
}
console.log(find('s:A') >= 0, cells[find('s:A')].value === undefined);
console.log(remove('s:A'), remove('s:A'));
console.log(cells[find('s:B')].value);
console.log(find('s:missing') === -1);精确输出:
true true true false 2 true
正式类的更新路径先查找已有键,再替换值,不增加 size,也不触发新键的负载检查。因此即使已经达到容量政策上限,也应当允许覆盖已有键。这也是差分测试中必须覆盖的一点:容器满了以后,新增失败与更新成功可以同时成立。
八、负载阈值只是政策,不能修好坏哈希
本例固定负载上限为 n / (2m) ≤ 0.45,其中 m 是每张表的长度,两张表总共有 2m 个槽。容量为八时最多接纳七个键,容量为十六时最多接纳十四个键。检查发生在新键插入之前,不能先增加 size 再在失败时忘记减回去。
原论文的期望性能结论依赖适当的哈希函数族和随机性条件;默认 demoHash 只是一个带种子、按 UTF-16 代码单元混合的教学散列,没有证明两张表的映射独立,也没有证明满足论文所需的通用性条件。因此 0.45 是本例保守的工程政策,不是“低于它就一定成功”的证明,更不是成功概率或延迟承诺。
示例 8:扩容不会自动分开同一对候选
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
// The table is unchanged unless a complete path to an empty slot is found.
function place(cells, entry, capacity, seed, hash, budget) {
const parent = new Map();
const queue = [];
for (let side = 0; side < 2; side++) {
const slot = slotOf(entry.token, side, capacity, seed, hash);
parent.set(slot, -1);
queue.push(slot);
}
let head = 0, revisits = 0;
while (head < queue.length && head < budget) {
let slot = queue[head++];
const occupant = cells[slot];
if (occupant === null) {
let moves = 0;
while (parent.get(slot) !== -1) {
const from = parent.get(slot);
cells[slot] = cells[from];
slot = from;
moves++;
}
cells[slot] = entry;
return { ok: true, reason: 'placed', visited: head, revisits, moves };
}
const otherSide = 1 - Math.floor(slot / capacity);
const next = slotOf(occupant.token, otherSide, capacity, seed, hash);
if (parent.has(next)) revisits++;
else { parent.set(next, slot); queue.push(next); }
}
return {
ok: false,
reason: head < queue.length ? 'budget' : 'closed',
visited: head, revisits, moves: 0
};
}
function attemptThree(capacity) {
const cells = Array(2 * capacity).fill(null);
let inserted = 0;
for (const token of ['A', 'B', 'C']) {
if (!place(cells, { token }, capacity, 1, () => 0, 32).ok) break;
inserted++;
}
return inserted;
}
for (const capacity of [4, 8, 16]) {
console.log(capacity, attemptThree(capacity));
}
console.log('limit@8=' + Math.floor(2 * 8 * 0.45));
console.log('limit@16=' + Math.floor(2 * 16 * 0.45));精确输出:
4 2 8 2 16 2 limit@8=7 limit@16=14
三个容量都只能放入两个键,因为这个测试哈希忽略容量和种子,永远返回零。即使总表几乎全空,也解决不了局部拥挤。这也是为什么实现必须既限制搜索,又限制每档种子的尝试次数和最大容量。不要把循环重试伪装成“最终一定成功”的接口。
默认参数为每表十六槽、最大每表四千零九十六槽、每次路径搜索最多一百二十八次出队、每档容量最多三次重建。容量必须是四到六万五千五百三十六之间的二次幂;预算与重试次数也有明确整数范围。确定性的种子递增仅为了复现测试,不提供攻击防护;这段实现没有密码学用途、抗哈希洪泛或其他安全性声明。
九、完整实现与对原生 Map 的差分验证
下面把局部合同装进 CuckooMap。类的字段是私有的,外部无法通过直接改数组破坏槽位不变量。新键插入会先扫描并复制当前数组,再尝试位移;普通成功路径也有线性复制成本。显式 rehash 使用同样的候选构建与提交过程。哈希函数接收 token、表号、单表容量和种子,方便注入极端映射进行验证。
接口有意小于原生 Map:没有构造器 iterable、迭代器、forEach 或插入顺序保证。entries 返回物理槽位顺序的快照数组,重建后顺序可以改变;snapshot 仅供测试观察布局和种子,也返回新的外层数组。原生 Map 在这里是支持键域内 set、get、has、delete 和 size 的语义参照,不能据此宣称整个类是 Map 的即插即用替代品。
测试使用固定种子的操作发生器,混合写入、覆盖、读取与删除,并在每步之后检查全部候选键,而不是只检查刚才访问的那个键。值中加入 undefined,键中加入 NaN、正负零、数字与字符串、组合 Unicode。后面再单独验证固定碰撞、显式重建失败和容量政策拒绝,确保异常分支也在测试覆盖内。
示例 9:完整类与五千步差分测试
'use strict';
function tokenOf(key) {
if (typeof key === 'string') {
if (key.length > 1024) throw new RangeError('key too long');
return 's:' + key;
}
if (typeof key === 'number') return 'n:' + String(key === 0 ? 0 : key);
throw new TypeError('keys must be strings or numbers');
}
function demoHash(token, side, capacity, seed) {
let h = (2166136261 ^ seed ^ Math.imul(side + 1, 0x9e3779b9)) >>> 0;
for (let i = 0; i < token.length; i++) {
h = Math.imul(h ^ token.charCodeAt(i), 16777619) >>> 0;
}
h ^= h >>> 16;
h = Math.imul(h, 0x85ebca6b) >>> 0;
h ^= h >>> 13;
return (h >>> 0) % capacity;
}
function slotOf(token, side, capacity, seed, hash) {
const index = hash(token, side, capacity, seed);
if (!Number.isInteger(index) || index < 0 || index >= capacity) {
throw new RangeError('invalid hash index');
}
return side * capacity + index;
}
// The table is unchanged unless a complete path to an empty slot is found.
function place(cells, entry, capacity, seed, hash, budget) {
const parent = new Map();
const queue = [];
for (let side = 0; side < 2; side++) {
const slot = slotOf(entry.token, side, capacity, seed, hash);
parent.set(slot, -1);
queue.push(slot);
}
let head = 0, revisits = 0;
while (head < queue.length && head < budget) {
let slot = queue[head++];
const occupant = cells[slot];
if (occupant === null) {
let moves = 0;
while (parent.get(slot) !== -1) {
const from = parent.get(slot);
cells[slot] = cells[from];
slot = from;
moves++;
}
cells[slot] = entry;
return { ok: true, reason: 'placed', visited: head, revisits, moves };
}
const otherSide = 1 - Math.floor(slot / capacity);
const next = slotOf(occupant.token, otherSide, capacity, seed, hash);
if (parent.has(next)) revisits++;
else { parent.set(next, slot); queue.push(next); }
}
return {
ok: false,
reason: head < queue.length ? 'budget' : 'closed',
visited: head, revisits, moves: 0
};
}
class CuckooMap {
#cells; #capacity; #seed = 1; #size = 0;
#maxCapacity; #budget; #retries; #hash;
constructor({ capacity = 16, maxCapacity = 4096,
budget = 128, retries = 3, hash = demoHash } = {}) {
const power = x => Number.isInteger(x) && x >= 4 && x <= 65536 &&
(x & (x - 1)) === 0;
if (!power(capacity) || !power(maxCapacity) || capacity > maxCapacity ||
!Number.isInteger(budget) || budget < 1 || budget > 131072 ||
!Number.isInteger(retries) || retries < 1 || retries > 16 ||
typeof hash !== 'function') throw new RangeError('invalid options');
this.#capacity = capacity;
this.#maxCapacity = maxCapacity;
this.#budget = budget;
this.#retries = retries;
this.#hash = hash;
this.#cells = Array(2 * capacity).fill(null);
}
get size() { return this.#size; }
get capacity() { return this.#capacity; } // Per table, not total slots.
#find(token) {
for (let side = 0; side < 2; side++) {
const slot = slotOf(token, side, this.#capacity, this.#seed, this.#hash);
if (this.#cells[slot]?.token === token) return slot;
}
return -1;
}
has(key) { return this.#find(tokenOf(key)) !== -1; }
get(key) {
const slot = this.#find(tokenOf(key));
return slot === -1 ? undefined : this.#cells[slot].value;
}
#build(entries, firstCapacity) {
let seed = this.#seed;
for (let capacity = firstCapacity; capacity <= this.#maxCapacity; capacity *= 2) {
if (entries.length > Math.floor(2 * capacity * 0.45)) continue;
for (let attempt = 0; attempt < this.#retries; attempt++) {
seed = (seed + 1) >>> 0;
const cells = Array(2 * capacity).fill(null);
let ok = true;
for (const entry of entries) {
if (!place(cells, entry, capacity, seed, this.#hash, this.#budget).ok) {
ok = false; break;
}
}
if (ok) return { cells, capacity, seed };
}
}
throw new RangeError('bounded rebuild failed');
}
#commit(next, size) {
this.#cells = next.cells;
this.#capacity = next.capacity;
this.#seed = next.seed;
this.#size = size;
}
set(key, value) {
const token = tokenOf(key);
const slot = this.#find(token);
const entry = { key: key === 0 ? 0 : key, token, value };
if (slot !== -1) { this.#cells[slot] = entry; return this; }
const entries = this.#cells.filter(x => x !== null);
entries.push(entry);
if (entries.length <= Math.floor(2 * this.#capacity * 0.45)) {
const cells = this.#cells.slice();
if (place(cells, entry, this.#capacity, this.#seed,
this.#hash, this.#budget).ok) {
this.#commit({ cells, capacity: this.#capacity, seed: this.#seed }, entries.length);
return this;
}
}
const next = this.#build(entries, this.#capacity);
this.#commit(next, entries.length);
return this;
}
delete(key) {
const slot = this.#find(tokenOf(key));
if (slot === -1) return false;
this.#cells[slot] = null;
this.#size--;
return true;
}
rehash() {
const entries = this.#cells.filter(x => x !== null);
this.#commit(this.#build(entries, this.#capacity), this.#size);
return this;
}
entries() {
return this.#cells.filter(x => x !== null).map(x => [x.key, x.value]);
}
snapshot() {
return { capacity: this.#capacity, seed: this.#seed, size: this.#size,
slots: this.#cells.map(x => x === null ? null : [x.token, x.value]) };
}
}
const assert = require('node:assert/strict');
const map = new CuckooMap({ maxCapacity: 4096 });
const reference = new Map();
const keys = [NaN, -0, 0, Infinity, -Infinity, 1, '1', '', 'é', 'e\u0301',
...Array.from({length: 50}, (_, i) => 'key:' + i)];
let random = 20261020;
function next() {
random = (Math.imul(random, 1664525) + 1013904223) >>> 0;
return random;
}
for (let step = 0; step < 5000; step++) {
const key = keys[next() % keys.length];
const op = next() % 5;
if (op < 3) {
const value = step % 7 ? step : undefined;
map.set(key, value); reference.set(key, value);
} else if (op === 3) assert.equal(map.delete(key), reference.delete(key));
else { assert.equal(map.has(key), reference.has(key));
assert.equal(map.get(key), reference.get(key)); }
assert.equal(map.size, reference.size);
for (const k of keys) {
assert.equal(map.has(k), reference.has(k));
assert.equal(map.get(k), reference.get(k));
}
}
console.log('differential=5000 PASS');
const blocked = new CuckooMap({ capacity: 8, maxCapacity: 16, hash: () => 0 });
blocked.set('A', 1).set('B', 2);
const saved = blocked.snapshot();
assert.throws(() => blocked.set('C', 3), /bounded rebuild failed/);
assert.deepEqual(blocked.snapshot(), saved);
blocked.set('A', 9);
assert.equal(blocked.size, 2);
assert.equal(blocked.delete('B'), true);
blocked.set('C', undefined);
assert.equal(blocked.has('C'), true);
console.log('collision/update/delete=PASS');
const badSeed = (token, side, capacity, seed) => seed === 1
? token.charCodeAt(2) % capacity : 0;
const stable = new CuckooMap({ capacity: 8, maxCapacity: 8, hash: badSeed });
stable.set('A', 1).set('B', 2).set('C', 3);
const old = stable.snapshot();
assert.throws(() => stable.rehash(), /bounded rebuild failed/);
assert.deepEqual(stable.snapshot(), old);
console.log('failed-rehash=unchanged');
const small = new CuckooMap({ capacity: 4, maxCapacity: 4 });
small.set('a', 1).set('b', 2).set('c', 3);
const full = small.snapshot();
assert.throws(() => small.set('d', 4), /bounded rebuild failed/);
assert.deepEqual(small.snapshot(), full);
small.set('a', 7);
assert.equal(small.get('a'), 7);
console.log('capacity/update=PASS');精确输出:
differential=5000 PASS collision/update/delete=PASS failed-rehash=unchanged capacity/update=PASS
十、怎样解读复杂度与这份测试结果
设 m 为当前单表容量,n 为条目数,L 为参与操作的最大 token 长度,B 为搜索预算,R 为每档重建次数。默认哈希计算成本为 O(L)。get、has、delete 与已有键更新最多探测两个槽,核心成本为 O(L)。place 最多处理 min(B, 2m) 个不同槽,每次最多计算一个旧条目的另一候选位置,加上两个根位置;队列不会因循环无限增长。
parent 使用原生 Map 保存搜索元数据,而非存储用户键值。若采用元数据操作期望常数时间的通常实现模型,一次路径搜索为 O(BL),成功逆向搬运不超过 B 次;不能把这个模型写成 ECMAScript 对 Map 单次操作的严格最坏时间保证。这里更直接可验证的是出队、散列调用与搬运次数的上界。
每次新增键都包含 O(m) 扫描与复制,所以通常路径的成本应写为 O(m + BL),不继承经典布谷鸟哈希的期望摊还常数插入结论。一次候选重建会分配 2m 个槽,并对最多 n 个条目执行有界搜索;在同样的元数据成本模型下,单候选上界为 O(m + nBL)。若共有 G 档容量,最大单表容量为 M,一个保守的总界为 O(GR(M + nBL)),另加最初的直接尝试。空间包括旧表、候选表、条目列表、搜索元数据以及保存的键与 token 文本,量级为 O(M + nL + B),不计用户值本身占用的空间。
预算控制的是本实现发出的有限工作量,不是毫秒级超时。字符串处理、分配、垃圾回收和注入哈希的运行时间仍会影响实际延迟。这份教材优先让失败语义清晰,因此接受了复制成本;如果要做高吞吐服务,应另行设计路径日志、内存复用、统计指标和基准,而不能先删掉事务边界再沿用这里的可靠性结论。
五千步差分测试是可重复的回归检查,强制碰撞与坏种子是定向反例,它们都不是正确性的形式化证明。更有价值的审查顺序是:先检查“每条目属于两个候选之一、没有重复键、size 等于实际条目数”,再证明路径搬运保留所有旧条目,最后检查每一种失败是否在提交之前结束。独立测试还应换种子、换操作分布、覆盖无穷与空字符串,并把失败前后的完整快照逐项比较。
向 AI 要一段算法代码时,最好同时要它列出键域、失效条件与可观察的不变量,再亲自用反例去检验这些描述。对这个容器而言,最重要的交付不是一行漂亮的 O(1),而是当搜索失败、重建失败或者容量政策拒绝新增时,调用方能知道发生了什么,并且仍然找得到原先存进去的每一条数据。
参考资料
Rasmus Pagh、Flemming Friche Rodler:Cuckoo Hashing,原始论文,第 4 节的双表不变量、插入重建机制与哈希假设。本文的有界双起点搜索与失败原子接口是教学实现选择,不是原文算法的逐字复刻。
ECMAScript 2023:Map Objects,用于对照支持键域内的容器语义与原生 Map 的接口差异。
ECMAScript 2023:SameValueZero,用于核对 NaN、正负零与不同类型的相等规则。资料核对日期:2026 年 10 月 20 日。

