AI 代码审查实战:JavaScript 规范哈夫曼编码的确定性、严格解码与独立验证

10-19 4阅读

让 AI 写一个哈夫曼编码器并不困难,困难的是确认它真的保留了整数权重、在同频时可复现、拒绝不完整码字,并且没有用自己的错误算法证明自己正确。一次编码再解码成功,只说明两个函数在这一个样本上相互配合;它既不能证明码表最优,也不能证明换一种输入顺序后输出仍然一致。本文把审查目标拆成可运行的契约,逐步构造规范哈夫曼编码,再用另一种搜索空间独立验证加权代价。

AI 代码审查实战:JavaScript 规范哈夫曼编码的确定性、严格解码与独立验证
AI 生成的原创概念配图:符号、分支与码字。画面用于表达主题,不作为编码树或位序的技术示意图。

本文的输入是符号与正 BigInt 频率组成的二元数组,符号必须是互不重复的非空字符串,最多一百二十八个。符号可以是一个汉字,也可以是一个完整词元;编码消息始终使用符号数组,不自动切分字符串。零频率条目必须由调用方明确移除,函数不会静默忽略它们。输出位串是仅含 ASCII 数字零和一的普通字符串,既没有字节封装,也没有填充位、文件头、校验和或终止符。本文不实现任何二进制压缩文件格式。

以下恰好九个示例均可单独保存为对应编号的 .cjs 文件,不依赖前一个示例的变量或本地模块。实测环境是 Node.js v24.19.0,统一运行命令为 node --unhandled-rejections=strict 01.cjs,并相应替换编号。代码有意重复公共函数,以便复制后直接运行。严格断言来自 Node.js 官方断言文档;启动参数的含义见 官方命令行文档。本组算法同步执行,严格拒绝模式是统一测试约定,不会把同步函数变成异步函数。

一、先把频率精度写进输入契约

频率不是适合随意转成浮点数的统计标签。超过安全整数范围后,相邻整数可能变成同一个 Number;排序时丢失的一票会改变合并顺序,之后再转回 BigInt 也无法恢复。ECMAScript 对 BigInt 的定义允许不固定比特宽度的整数,本文因此让频率、权重之和与加权代价都留在 BigInt 域内。长度和数组下标仍使用受限的 Number,两种数值只在有明确边界时转换。

可以给 AI 的第一个审查要求是:找出所有可能丢精度的转换,并为每一个拒绝分支提供输入。下面直接复现相邻整数碰撞,同时验证复制后的二元数组不会反向修改调用方数据。输入校验使用逐项遍历,因此稀疏数组里的空洞也会成为非法条目,不能被数组映射悄悄跳过。我们不接受数字字符串、普通数字频率或自动合并重复符号,避免调用者误以为函数会替他纠正数据。

示例 1,独立文件 01.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;

const a = 9007199254740992n, b = a + 1n;
assert.equal(Number(a), Number(b));
assert.notEqual(a, b);
const input = [["甲", b], ["乙", 2n]];
const copy = pairs(input, "frequency");
copy[0][1] = 1n;
assert.equal(input[0][1], b);
assert.throws(() => pairs([["甲", 2]], "frequency"), TypeError);
assert.throws(() => pairs(new Array(1), "frequency"), TypeError);
console.log("Number collision:", Number(a) === Number(b));
console.log("exact frequency:", input[0][1].toString());

运行输出:

Number collision: true
exact frequency: 9007199254740993

二、把同频选择变成公开规则

构树时每次选权重最小的两棵树。权重相等,就比较各子树中最小的符号,较小者先选;这里的字符串顺序明确采用 JavaScript 关系比较的 UTF-16 码元字典序,依据 ECMAScript 的字符串比较规则,不使用可能随语言环境变化的本地化排序。活动子树的叶集合互不相交,因此两个不同子树不可能拥有相同的最小符号,这个次级键足以给出确定次序。

示例故意使用一、一、二、二这组权重,让刚合并出的内部节点与原有叶子同频。内部节点的最小符号是 a,于是它先于 c 参与下一次合并,最终 a、b 长三位,c 长两位,d 长一位。这个结果并不声称是所有最优码表中字典序最小的一个;它只是本文准确、可重现的选择策略。冻结输入再运行还能检查实现是否偷偷原地排序了用户数组,输出长度表则统一按符号排序。

示例 2,独立文件 02.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}

const input = Object.freeze([
  Object.freeze(["d", 2n]), Object.freeze(["b", 1n]),
  Object.freeze(["a", 1n]), Object.freeze(["c", 2n])
]);
assert.deepEqual(lengths(input), [["a", 3], ["b", 3], ["c", 2], ["d", 1]]);
assert.deepEqual(lengths([...input].reverse()), lengths(input));
console.log(JSON.stringify(lengths(input)));

运行输出:

[["a",3],["b",3],["c",2],["d",1]]

三、只凭长度重建规范码字

树的左右边如何标零或一,并不影响每个叶子的深度。我们先保留深度,再按长度从短到长、同长时按符号排序,重新分配连续整数码字。处理一个更长的长度时,将下一个可用整数左移长度差,再补齐前导零。RFC 1951 第 3.2.2 节给出了这种规范分配思路;下面使用其中的长度样例作对照。这里只借用码字规则,不实现该文档的块结构或字节位序。

这里必须审查移位操作的数值类型:编码整数使用 BigInt,不能让 Number 的三十二位位运算截断长码字。长度表限制在一到一百二十七位,并沿用唯一符号与条目数量检查。当下一个整数已经无法装入目标位宽,长度表就是过度订阅,应立即拒绝。函数也明确接受未用满编码空间的长度表,例如两位和三位各一个;这样的表可以合法解码,但并不因此具有哈夫曼最优性。长度零从来不代表一个可编码符号。

示例 3,独立文件 03.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}

const rows = [["A", 3], ["B", 3], ["C", 3], ["D", 3],
  ["E", 3], ["F", 2], ["G", 4], ["H", 4]];
const codes = canonical(rows);
assert.deepEqual([...codes.values()], ["00", "010", "011", "100", "101", "110", "1110", "1111"]);
assert.throws(() => canonical([["a", 1], ["b", 1], ["c", 1]]), /oversubscribed/);
assert.deepEqual([...canonical([["x", 2], ["y", 3]])], [["x", "00"], ["y", "010"]]);
console.log([...codes].map(([s, bits]) => s + "=" + bits).join(" "));

运行输出:

F=00 A=010 B=011 C=100 D=101 E=110 G=1110 H=1111

四、实现一个完整且可检查的往返

现在把频率、长度、规范码表与前缀树连起来。编码只从内部 Map 查找完整符号,遇到未知符号就失败;解码按每一位向下走,到叶子立即输出该符号,再回到根。外露的 codes 只是独立快照,修改它不会破坏闭包中的真正码表。这是审查 API 所有权时很容易遗漏的地方:只冻结一个包含 Map 的对象,并不能自动禁止 Map 内部变化。

例中的短消息不必与训练频率完全一致。频率描述用于设计码表的权重,消息则是一次实际输入;加权位数七十一针对频率表计算,并不是这条演示消息的位数。测试分别固定码串、还原后的符号顺序和加权代价,避免把三个不同概念揉成一个压缩率数字。接入真实业务前,还需要明确频率表来自哪个时间窗口、何时更新、解码端如何取得相同长度表。

示例 4,独立文件 04.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}
function codec(lengthRows) {
  const codes = canonical(lengthRows);
  const makeNode = () => ({ next: [null, null], symbol: null });
  const root = makeNode();
  for (const [symbol, bits] of codes) {
    let node = root;
    for (const bit of bits) {
      if (node.symbol !== null) throw new Error("prefix conflict");
      const i = bit === "1" ? 1 : 0;
      node = node.next[i] ??= makeNode();
    }
    if (node.symbol !== null || node.next.some(Boolean)) throw new Error("prefix conflict");
    node.symbol = symbol;
  }
  return {
    codes: new Map(codes),
    encode(message) {
      if (!Array.isArray(message)) throw new TypeError("message must be an array");
      const parts = [];
      for (const symbol of message) {
        if (!codes.has(symbol)) throw new RangeError("unknown symbol");
        parts.push(codes.get(symbol));
      }
      return parts.join("");
    },
    decode(bits) {
      if (typeof bits !== "string" || /[^01]/u.test(bits))
        throw new TypeError("bits must contain only 0 and 1");
      const result = [];
      let node = root;
      for (const bit of bits) {
        node = node.next[bit === "1" ? 1 : 0];
        if (node === null) throw new RangeError("missing branch");
        if (node.symbol !== null) {
          result.push(node.symbol);
          node = root;
        }
      }
      if (node !== root) throw new RangeError("truncated codeword");
      return result;
    }
  };
}

const frequencies = [["A", 5n], ["B", 7n], ["C", 10n], ["D", 15n]];
const machine = codec(lengths(frequencies));
const message = ["D", "A", "C", "B", "D"];
const bits = machine.encode(message);
assert.equal(bits, "0110101110");
assert.deepEqual(machine.decode(bits), message);
machine.codes.set("A", "broken"); // 展示用快照不会改变内部码表
assert.equal(machine.encode(["A"]), "110");
const cost = frequencies.reduce((sum, [s, w]) =>
  sum + w * BigInt(canonical(lengths(frequencies)).get(s).length), 0n);
assert.equal(cost, 71n);
console.log(bits);
console.log(JSON.stringify(machine.decode(bits)));
console.log("weighted bits:", cost.toString());

运行输出:

0110101110
["D","A","C","B","D"]
weighted bits: 71

五、空字母表与单符号不能靠偶然行为

空字母表只允许编码空消息,也只能把空位串解成空数组。出现任何符号或任何位,就应失败。单符号时,纯数学模型可以讨论零长度码字,但如果没有额外记录消息长度,空位串无法区分零次、一次与很多次出现。本文主动选择一位零作为单符号码,因此三个零恰好还原三个符号,空位串仍代表零个符号。

这一决定也改变最优代价的边界定义:单符号的代价是它的频率,而不是零。后面的独立预言机必须遵守同一个已声明契约,不能一边用空码字建模,一边指责一位实现不最优。规范化函数接受一般长度表,但由频率构树产生的单符号长度始终是一;调用者手工传入更长单符号码时,合法性与最优性仍要分开判断。

示例 5,独立文件 05.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}
function codec(lengthRows) {
  const codes = canonical(lengthRows);
  const makeNode = () => ({ next: [null, null], symbol: null });
  const root = makeNode();
  for (const [symbol, bits] of codes) {
    let node = root;
    for (const bit of bits) {
      if (node.symbol !== null) throw new Error("prefix conflict");
      const i = bit === "1" ? 1 : 0;
      node = node.next[i] ??= makeNode();
    }
    if (node.symbol !== null || node.next.some(Boolean)) throw new Error("prefix conflict");
    node.symbol = symbol;
  }
  return {
    codes: new Map(codes),
    encode(message) {
      if (!Array.isArray(message)) throw new TypeError("message must be an array");
      const parts = [];
      for (const symbol of message) {
        if (!codes.has(symbol)) throw new RangeError("unknown symbol");
        parts.push(codes.get(symbol));
      }
      return parts.join("");
    },
    decode(bits) {
      if (typeof bits !== "string" || /[^01]/u.test(bits))
        throw new TypeError("bits must contain only 0 and 1");
      const result = [];
      let node = root;
      for (const bit of bits) {
        node = node.next[bit === "1" ? 1 : 0];
        if (node === null) throw new RangeError("missing branch");
        if (node.symbol !== null) {
          result.push(node.symbol);
          node = root;
        }
      }
      if (node !== root) throw new RangeError("truncated codeword");
      return result;
    }
  };
}

const empty = codec(lengths([]));
assert.equal(empty.codes.size, 0);
assert.equal(empty.encode([]), "");
assert.deepEqual(empty.decode(""), []);
assert.throws(() => empty.encode(["x"]), /unknown/);
assert.throws(() => empty.decode("0"), /missing/);
const one = codec(lengths([["唯一", 999999999999999999999n]]));
assert.deepEqual([...one.codes], [["唯一", "0"]]);
assert.equal(one.encode(["唯一", "唯一", "唯一"]), "000");
assert.deepEqual(one.decode("000"), ["唯一", "唯一", "唯一"]);
assert.deepEqual(one.decode(""), []);
assert.throws(() => one.decode("1"), /missing/);
console.log("empty: [] -> empty bits -> []");
console.log("singleton:", one.encode(["唯一", "唯一", "唯一"]));

运行输出:

empty: [] -> empty bits -> []
singleton: 000

六、严格解码拒绝哪些坏输入

严格不是遇到错误后尽量猜出原文。位串参数必须是字符串,而且每个字符都必须是真正的零或一,空白、换行、全角数字与其他字符一律拒绝。走到不存在的分支属于非法路径;输入耗尽时如果还停在内部节点,就属于截断码字。下面把这两类错误分别触发,并覆盖重复符号、错误类型、非正频率、非法长度和符号数量越界。抛出的异常不携带部分解码结果,调用方不会误用半条消息。

但严格语法检查不等于损坏检测。例中的十和十一分别都是合法码字,翻转一位以后会得到另一个合法符号,解码器没有任何证据证明它被篡改。完整码字被删去、重复或追加也可能无法发现。需要消息完整性时,应在外层设计长度、帧边界与适当校验或认证机制;不要让 AI 把前缀码的可唯一解析性包装成防篡改保证,也不要自行把尾部零当作可以忽略的填充。

示例 6,独立文件 06.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}
function codec(lengthRows) {
  const codes = canonical(lengthRows);
  const makeNode = () => ({ next: [null, null], symbol: null });
  const root = makeNode();
  for (const [symbol, bits] of codes) {
    let node = root;
    for (const bit of bits) {
      if (node.symbol !== null) throw new Error("prefix conflict");
      const i = bit === "1" ? 1 : 0;
      node = node.next[i] ??= makeNode();
    }
    if (node.symbol !== null || node.next.some(Boolean)) throw new Error("prefix conflict");
    node.symbol = symbol;
  }
  return {
    codes: new Map(codes),
    encode(message) {
      if (!Array.isArray(message)) throw new TypeError("message must be an array");
      const parts = [];
      for (const symbol of message) {
        if (!codes.has(symbol)) throw new RangeError("unknown symbol");
        parts.push(codes.get(symbol));
      }
      return parts.join("");
    },
    decode(bits) {
      if (typeof bits !== "string" || /[^01]/u.test(bits))
        throw new TypeError("bits must contain only 0 and 1");
      const result = [];
      let node = root;
      for (const bit of bits) {
        node = node.next[bit === "1" ? 1 : 0];
        if (node === null) throw new RangeError("missing branch");
        if (node.symbol !== null) {
          result.push(node.symbol);
          node = root;
        }
      }
      if (node !== root) throw new RangeError("truncated codeword");
      return result;
    }
  };
}

let rejected = 0;
const rejects = (fn, error) => { assert.throws(fn, error); rejected++; };
for (const input of [null, {}, new Array(1), [7], [["a"]], [["", 1n]],
  [["a", 1n], ["a", 2n]], [[3, 1n]], [["a", 1]], [["a", "1"]]]) {
  rejects(() => lengths(input), TypeError);
}
for (const input of [[["a", 0n]], [["a", -1n]],
  Array.from({ length: 129 }, (_, i) => [String(i), 1n])]) {
  rejects(() => lengths(input), RangeError);
}
for (const n of [0, -1, 1.5, NaN, Infinity, 128, 1n, "1"])
  rejects(() => canonical([["a", n]]), RangeError);
rejects(() => canonical([["a", 1], ["b", 1], ["c", 1]]), /oversubscribed/);
const machine = codec([["a", 1], ["b", 2], ["c", 2]]);
for (const bits of [null, 10, "10\n", " 10", "10x", "0"])
  rejects(() => machine.decode(bits), TypeError);
rejects(() => machine.decode("1"), /truncated/);
rejects(() => machine.encode("abc"), TypeError);
rejects(() => machine.encode(new Array(1)), /unknown/);
rejects(() => machine.encode(["z"]), /unknown/);
rejects(() => codec([["x", 2]]).decode("1"), /missing/);
assert.deepEqual(machine.decode("10"), ["b"]);
assert.deepEqual(machine.decode("11"), ["c"]); // 翻位仍可能是合法消息
console.log("rejected:", rejected);
console.log("valid bit flip: b -> c");

运行输出:

rejected: 33
valid bit flip: b -> c

七、用排列测试检查确定性与符号身份

只反转一次数组还不足以覆盖所有同频交错。四个条目的二十四种排列很小,值得全部枚举,并要求每一种产生完全相同的规范码表,包括迭代顺序。这种测试比只比总代价更严格,因为两个不同码表完全可能有相同最优代价。以后若把排序队列替换成堆,仍应保留这些测试,使性能优化不偷偷改变公开的同频策略。

符号是精确字符串,不是用户眼中的字形。带组合重音的字符串与预组字符在本文中保持不同身份,表情、多字符词元以及看似对象属性的名字也应正常往返。使用 Map 避免把词元当普通对象属性处理。若产品需要 Unicode 规范化或按字素切分,应在构建频率之前统一处理,并向解码端传递同样的约定;那属于输入协议,不能由编码器在途中无声修改。

示例 7,独立文件 07.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}
function codec(lengthRows) {
  const codes = canonical(lengthRows);
  const makeNode = () => ({ next: [null, null], symbol: null });
  const root = makeNode();
  for (const [symbol, bits] of codes) {
    let node = root;
    for (const bit of bits) {
      if (node.symbol !== null) throw new Error("prefix conflict");
      const i = bit === "1" ? 1 : 0;
      node = node.next[i] ??= makeNode();
    }
    if (node.symbol !== null || node.next.some(Boolean)) throw new Error("prefix conflict");
    node.symbol = symbol;
  }
  return {
    codes: new Map(codes),
    encode(message) {
      if (!Array.isArray(message)) throw new TypeError("message must be an array");
      const parts = [];
      for (const symbol of message) {
        if (!codes.has(symbol)) throw new RangeError("unknown symbol");
        parts.push(codes.get(symbol));
      }
      return parts.join("");
    },
    decode(bits) {
      if (typeof bits !== "string" || /[^01]/u.test(bits))
        throw new TypeError("bits must contain only 0 and 1");
      const result = [];
      let node = root;
      for (const bit of bits) {
        node = node.next[bit === "1" ? 1 : 0];
        if (node === null) throw new RangeError("missing branch");
        if (node.symbol !== null) {
          result.push(node.symbol);
          node = root;
        }
      }
      if (node !== root) throw new RangeError("truncated codeword");
      return result;
    }
  };
}

function permutations(xs) {
  if (xs.length === 0) return [[]];
  return xs.flatMap((x, i) => permutations(xs.filter((_, j) => i !== j))
    .map(rest => [x, ...rest]));
}
const input = [["a", 1n], ["b", 1n], ["c", 2n], ["d", 2n]];
const expected = [["d", "0"], ["c", "10"], ["a", "110"], ["b", "111"]];
let checked = 0;
for (const order of permutations(input)) {
  assert.deepEqual([...canonical(lengths(order))], expected);
  checked++;
}
const tokens = ["__proto__", "constructor", "😀", "é", "e\u0301", "ab"];
const machine = codec(lengths(tokens.map(s => [s, 1n])));
assert.equal(machine.codes.size, 6);
assert.deepEqual(machine.decode(machine.encode(tokens)), tokens);
assert.notEqual(machine.codes.get("é"), machine.codes.get("e\u0301"));
console.log("permutations:", checked);
console.log("exact token round trip:", machine.decode(machine.encode(tokens)).length);

运行输出:

permutations: 24
exact token round trip: 6

八、先用独立结构检查排除前缀冲突

这一层测试不调用解码器。它直接两两比较码字,确认任何码字都不是另一个的前缀;再把所有长度换算到共同深度,以 BigInt 累加它们占用的叶槽数。这就是 Kraft 不等式的整数形式,避免浮点小数累加误差。对由频率构树得到的多符号码表,占用数应恰好等于总容量;单符号一位约定只占一半;空表占零。前缀检查和容量检查分别观察结构与长度,不应相互替代。

测试穷举零到六个符号、每个权重取一到三的全部一千零九十三组表,并另外使用七十项斐波那契权重制造六十九位深码字。长码字用例针对常见的三十二位移位错误,不能被几个短英文单词替代。最后人为构造零与零一两个冲突码字,确认检查器自身真的能报警。不过即使前缀和容量全部通过,也只能说明这些码字具备相应结构,仍不能说明高频符号拿到了合适的长度。

示例 8,独立文件 08.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}

function inspect(codes) {
  const words = [...codes.values()];
  for (const word of words) assert.match(word, /^[01]+$/u);
  for (let i = 0; i < words.length; i++)
    for (let j = 0; j < words.length; j++)
      if (i !== j) assert.equal(words[j].startsWith(words[i]), false);
  const max = Math.max(0, ...words.map(s => s.length));
  const capacity = 1n << BigInt(max);
  const used = words.reduce((sum, word) =>
    sum + (1n << BigInt(max - word.length)), 0n);
  assert(used <= capacity);
  return { used, capacity, max };
}

let cases = 0;
function visit(weights, remaining) {
  const codes = canonical(lengths(weights.map((w, i) => [String(i), w])));
  const { used, capacity } = inspect(codes);
  if (weights.length >= 2) assert.equal(used, capacity);
  if (weights.length === 1) assert.equal(used * 2n, capacity);
  if (weights.length === 0) assert.equal(used, 0n);
  cases++;
  if (remaining) for (const w of [1n, 2n, 3n]) visit([...weights, w], remaining - 1);
}
visit([], 6);
const fibonacci = [];
let a = 1n, b = 1n;
for (let i = 0; i < 70; i++) {
  fibonacci.push([String(i).padStart(3, "0"), a]);
  [a, b] = [b, a + b];
}
const deep = inspect(canonical(lengths(fibonacci)));
assert.equal(deep.max, 69);
assert.equal(deep.used, deep.capacity);
assert.throws(() => inspect(new Map([["a", "0"], ["b", "01"]])));
console.log("prefix and Kraft cases:", cases);
console.log("deep code width:", deep.max);

运行输出:

prefix and Kraft cases: 1093
deep code width: 69

九、换一种算法验证真正的最优代价

最终预言机不再重复取两个最小权重。它枚举符号集合在根节点左右两边的所有非空划分,对每个子集记住最小代价,再加上整个集合的权重和,表示全部叶子因为根的两条边增加一层。固定最小编号符号位于左边,只消除左右镜像的重复,并不遗漏树形。正权重下最优树无需单孩子内部节点,否则收缩那条边就能降低代价,因此枚举满二叉树的分割足以覆盖最优解。

这是指数级的小规模检查器,最多八个符号,时间随子集分割数量增长,不能替代生产构树算法。测试对零到五个符号的三百六十四组小整数表全部检查,再加入四百组固定种子的随机权重,并放大到远超安全整数范围。最后构造一个前缀合法、容量用满、也能规范分配的码表,代价却是二百零三而非一百零四。这个反例明确说明:往返、前缀、Kraft 与最优性是四层不同证据,审查报告应该分别给结论。

示例 9,独立文件 09.cjs:

"use strict";
const assert = require("node:assert/strict");
function pairs(input, mode) {
  if (!Array.isArray(input)) throw new TypeError("table must be an array");
  if (input.length > 128) throw new RangeError("at most 128 symbols");
  const seen = new Set();
  const rows = [];
  for (const row of input) {
    if (!Array.isArray(row) || row.length !== 2)
      throw new TypeError("each row must be a pair");
    const [symbol, value] = row;
    if (typeof symbol !== "string" || symbol.length === 0 || seen.has(symbol))
      throw new TypeError("symbols must be unique nonempty strings");
    seen.add(symbol);
    if (mode === "frequency") {
      if (typeof value !== "bigint") throw new TypeError("frequency must be BigInt");
      if (value <= 0n) throw new RangeError("frequency must be positive");
    } else if (!Number.isInteger(value) || value < 1 || value > 127) {
      throw new RangeError("length must be an integer from 1 to 127");
    }
    rows.push([symbol, value]);
  }
  return rows;
}
const lex = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function lengths(frequencies) {
  const queue = pairs(frequencies, "frequency").map(([symbol, weight]) =>
    ({ symbol, weight, min: symbol }));
  if (queue.length === 0) return [];
  const compare = (a, b) => a.weight < b.weight ? -1 :
    a.weight > b.weight ? 1 : lex(a.min, b.min);
  while (queue.length > 1) {
    queue.sort(compare);
    const left = queue.shift(), right = queue.shift();
    queue.push({ weight: left.weight + right.weight,
      min: lex(left.min, right.min) < 0 ? left.min : right.min, left, right });
  }
  const result = [], stack = [[queue[0], 0]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    if (node.symbol !== undefined) result.push([node.symbol, Math.max(1, depth)]);
    else stack.push([node.left, depth + 1], [node.right, depth + 1]);
  }
  return result.sort((a, b) => lex(a[0], b[0]));
}
function canonical(lengthRows) {
  const rows = pairs(lengthRows, "length").sort((a, b) =>
    a[1] - b[1] || lex(a[0], b[0]));
  const codes = new Map();
  let next = 0n, previous = 0;
  for (const [symbol, width] of rows) {
    next <<= BigInt(width - previous);
    if (next >= (1n << BigInt(width))) throw new RangeError("oversubscribed lengths");
    codes.set(symbol, next.toString(2).padStart(width, "0"));
    next += 1n;
    previous = width;
  }
  return codes;
}

function optimalCost(weights) {
  const n = weights.length;
  if (n === 0) return 0n;
  if (n === 1) return weights[0]; // 本文单符号必须使用一位
  if (n > 8) throw new RangeError("oracle is limited to eight symbols");
  const size = 1 << n, sums = Array(size).fill(0n), costs = Array(size).fill(null);
  costs[0] = 0n;
  for (let mask = 1; mask < size; mask++) {
    for (let i = 0; i < n; i++) if (mask & (1 << i)) sums[mask] += weights[i];
    if ((mask & (mask - 1)) === 0) { costs[mask] = 0n; continue; }
    const anchor = mask & -mask;
    for (let left = (mask - 1) & mask; left; left = (left - 1) & mask) {
      if (!(left & anchor)) continue;
      const right = mask ^ left;
      const candidate = costs[left] + costs[right] + sums[mask];
      if (costs[mask] === null || candidate < costs[mask]) costs[mask] = candidate;
    }
  }
  return costs[size - 1];
}
function weightedCost(weights, codes) {
  return weights.reduce((sum, w, i) => sum + w * BigInt(codes.get(String(i)).length), 0n);
}
let cases = 0;
function check(weights) {
  const table = weights.map((w, i) => [String(i), w]);
  assert.equal(weightedCost(weights, canonical(lengths(table))), optimalCost(weights));
  cases++;
}
function visit(weights, remaining) {
  check(weights);
  if (remaining) for (const w of [1n, 2n, 3n]) visit([...weights, w], remaining - 1);
}
visit([], 5);
let state = 20261019;
const random = () => (state = (Math.imul(state, 1664525) + 1013904223) >>> 0);
for (let i = 0; i < 400; i++) {
  const n = 2 + random() % 6;
  check(Array.from({ length: n }, () => BigInt(1 + random() % 100) * (1n << 70n)));
}
const weights = [100n, 1n, 1n];
const nonoptimal = canonical([["0", 2], ["1", 2], ["2", 1]]);
assert.equal(weightedCost(weights, nonoptimal), 203n);
assert.equal(optimalCost(weights), 104n);
console.log("independent optimum cases:", cases);
console.log("valid but nonoptimal: 203 > 104");

运行输出:

independent optimum cases: 764
valid but nonoptimal: 203 > 104

把审查结论限制在证据覆盖的范围内

这个版本选择每轮重新排序,最多一百二十八个符号,目的是让审查路径清晰。在把一次权重比较视作单位操作的粗略模型下,构树需要平方乘对数级别的比较;真实 BigInt 运算成本还取决于权重位数。树节点本身占线性空间,但显式保存所有码字与前缀树还需要与码长总和相关的空间。编码要处理符号和输出位,解码逐位处理,并保留返回的符号数组。它不是不受输入规模影响的常量内存实现。

条目数量与码长上限也不等于完整资源防护:非常长的符号、巨大 BigInt、超长消息和位串仍会消耗时间与内存。网络服务还要在边界设置字节数、频率位数、消息长度和输出上限。本文也没有实现流式状态恢复、长度受限哈夫曼优化、跨语言序列化或者码表传输。若这些需求出现,应先扩充契约和测试,再让 AI 修改实现,避免把一个可审查的小算法误称为生产级压缩协议。

一个有效的 AI 审查请求可以这样组织:先列出输入与异常契约,再说明确定性次序和单符号约定,要求给出能杀死错误实现的反例,最后用不同算法验证最优代价。审查者尤其要追问:测试是不是复用了待测代码的决策,是否把合法误当最优,是否把可解码误当可校验。这些问题比让模型重复解释哈夫曼树的定义,更能帮助我们发现实际实现中的边界缺口。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。