AI 代码审查实战:用 JavaScript 实现可逆 Move-to-Front 字节变换
审查 AI 生成的 Move-to-Front 实现,最重要的验收条件是:编码器和解码器在每一步都拥有同一个字母表排列。只看一次往返测试,很容易漏掉共同的下标错误;只看输出里出现很多零,又容易把可逆变换误认为压缩算法。本文针对固定的 256 个字节值,给出朴素列表参照、基于 Fenwick 树的顺序统计实现,以及九段可以单独运行的 Node.js 示例。
这里不构造后缀数组,不执行 Burrows–Wheeler 变换,也不展开通用树状数组教程。重点是把动态排列的语义落实到字节接口、内存所有权、块边界和独立验证上。实现只处理已经得到的字节序列;字符串应在外层明确选择 UTF-8 等编码,不能把 JavaScript 字符串索引当作字节索引。

先把协议写清楚
初始排列固定为 0、1、2,一直到 255,包含每种字节且只包含一次。编码读到字节 b 时,先输出 b 在当前排列中的零基位置 rank,再把 b 移到最前面;其余字节的相对顺序不变。解码读到 rank 时,先取出该位置的字节,再执行完全相同的移动。编码后的元素仍然都在 0 到 255 之间,长度也与输入相同。
两端一致性可以逐步证明:开始时排列相同;假设某一步之前相同,编码输出的位置必然指向解码器中同一个字节;双方随后做同一次删除和前插,下一步排列仍然相同。这个证明还明确了顺序:必须先读位置、再更新排列。把移动放到查询前面会让每个编码结果都成为零。
Bentley、Sleator、Tarjan 与 Wei 的论文讨论了发送方与接收方同步维护自组织列表,并把列表位置接入整数编码。本文采用固定字节全集和零基位置,不直接照搬论文中的动态单词字典,也不把论文对完整编码方案的结论套到这里的定长字节输出上。原始论文,第 2 节
示例一 用朴素列表确定答案
参照实现故意使用 indexOf、splice 和 unshift。它容易直接对应定义,也不与后面的 Fenwick 实现共享查询或移动逻辑,因此适合作为独立 oracle。此处 oracle 只用于已经确认合法的测试数据,不作为对外的输入验证接口。输入中的重复字节会反复移动同一个符号,绝不会向字母表插入第二份副本。
banana 的字节序列第一次读到 98 时输出 98。移动之后,97 的位置变成 98,第二个输出因此也是 98。这个已知向量比简单断言解码结果等于原文更有价值,因为它能够戳穿编解码器同时采用错误协议的情况。
完整示例 1,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function oracle(input, decode = false) {
const list = Array.from({ length: 256 }, (_, i) => i);
return Uint8Array.from(input, x => {
const rank = decode ? x : list.indexOf(x);
const symbol = list[rank];
list.splice(rank, 1);
list.unshift(symbol);
return decode ? symbol : rank;
});
}
const input = Uint8Array.from([98, 97, 110, 97, 110, 97]);
const ranks = oracle(input);
assert.deepEqual(oracle(ranks, true), input);
console.log(Array.from(ranks).join(","));
console.log("restored", Array.from(oracle(ranks, true)).join(","));精确输出:
98,98,110,1,1,1 restored 98,97,110,97,110,97
示例二 零代表当前队首
rank 为零不表示字节值为零,也不表示流结束。它只表示取当前排列的第一个符号。初始状态的队首恰好是字节 0,读过 65 之后队首就变成 65。因此连续零经常对应重复字节,但不能脱离之前的状态解释。对空输入,算法直接返回空字节数组;没有隐藏的结束标记。
编码器不能为了省事跳过重复字节,解码器也不能把连续零折叠为一次输出。这里每个输入元素都产生一个输出元素。下面同时测试真正的零字节、最大字节 255,以及不同历史下的零位置,让含义不再依赖文字说明。
完整示例 2,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function oracle(input, decode = false) {
const list = Array.from({ length: 256 }, (_, i) => i);
return Uint8Array.from(input, x => {
const rank = decode ? x : list.indexOf(x);
const symbol = list[rank];
list.splice(rank, 1);
list.unshift(symbol);
return decode ? symbol : rank;
});
}
const input = Uint8Array.from([0, 0, 255, 255, 0]);
assert.deepEqual(Array.from(oracle(input)), [0, 0, 255, 0, 1]);
assert.deepEqual(Array.from(oracle([0, 0, 0], true)), [0, 0, 0]);
assert.deepEqual(Array.from(oracle([65, 0, 0], true)), [65, 65, 65]);
console.log("ranks", Array.from(oracle(input)).join(","));
console.log("same zeros, different front: 0 and 65");精确输出:
ranks 0,0,255,0,1 same zeros, different front: 0 and 65
示例三 给队首预留有限位置
设块长为 n,分配从 1 到 n 加 256 的物理位置。位置 1 到 n 暂时空着,256 个字节按升序放在 n 加 1 到 n 加 256。每次移动都使用一个更小的空位置:先是 n,再是 n 减 1,直到 1。按物理位置升序读出仍然占用的位置,正好就是当前逻辑排列。这样,前插不需要把整段列表搬动。
tree 保存的是位置是否被占用的计数,不是某个字节出现的频率。pos 从字节映射到当前物理位置,symbolAt 则记录该位置的字节。编码时,对当前位置求前缀和再减一,得到零基 rank;解码时,寻找第 rank 加 1 个占用位置,再读取 symbolAt。旧位置残留的 symbolAt 值不会误入解码,因为其占用计数已经归零。
select 使用 Fenwick 二进制提升:从最大的不超过容量的二次幂开始,尝试跳过累计数量不足 k 的前缀。注意比较条件是严格小于 k;写成小于等于,会把正好命中的位置跳过去。select 是内部函数,调用者只传入 1 到 256,而树的占用总数始终为 256,不需要向外暴露一个未校验的顺序统计接口。
Fenwick 原始论文提供维护累计频数的树结构背景;这里将位置占用映射到该结构,并结合前端保留区,是本文的具体工程实现。它不意味着树状数组会自动理解字母表移动。Fenwick,1994,论文及摘要
完整示例 3,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
const input = [98, 97, 110, 97, 110, 97];
const encoded = mtf(input);
assert.deepEqual(Array.from(encoded), [98, 98, 110, 1, 1, 1]);
assert.deepEqual(Array.from(mtf(encoded, true)), input);
console.log("encoded", Array.from(encoded).join(","));
console.log("roundtrip", true);精确输出:
encoded 98,98,110,1,1,1 roundtrip true
每次更新先从旧位置减一,再向 front 加一。最后一个元素处理时 front 为 1,完成后才减成 0;循环已经结束,绝不会调用 add(0, 1)。这个细节值得在 AI 代码审查中单独指出:Fenwick 更新若从零开始,低位位元也是零,循环可能永远不前进。空块虽然没有移动,初始化仍会建立完整的 256 字节状态。
示例四 在转换之前拒绝非法输入
公开函数接受当前运行域中的 Uint8Array、Node.js Buffer 或普通的稠密数字数组。数字数组里的每一项必须是 0 到 255 的整数;负数、小数、字符串、NaN 和空洞都会被拒绝。普通数组应无带副作用的访问器或代理;代码不承诺在恶意 getter、原型篡改或跨运行域对象面前充当安全沙箱。对模式参数也检查布尔类型,避免把字符串误当作解码开关。
ECMAScript 的 Uint8Array 构造会把数值转换为对应的无符号八位值,所以不能先把任意数组转成 Uint8Array,再判断它是否越界。比如原始的 256 经转换已经成了 0,证据丢失。调用者若在进入本函数前已经做过这种转换,函数也不可能恢复被截断的原值。解码接收的任何合法字节都是合法 rank,非法的 256 只能在原始数字数组边界识别。ECMAScript 类型化数组规范
块上限固定为 1048576 字节,检查发生在复制数据和分配工作树之前。它是本文选择的资源政策,不是 MTF 的数学限制。共享缓冲区和可调整大小的缓冲区也明确拒绝,因为一次普通复制并不提供多线程一致快照协议。已分离的 Uint8Array 由原生复制构造抛错。下面既测超过上限,又真实执行恰好到达上限的全零块;这些是正确性与资源边界测试,不是速度对比。
完整示例 4,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
const bad = [null, "abc", new Uint16Array([1]), [256], [-1],
[1.5], [NaN], ["1"], new Array(1), new Uint8Array(2 ** 20 + 1),
new Uint8Array(new SharedArrayBuffer(1)),
new Uint8Array(new ArrayBuffer(1, { maxByteLength: 2 }))];
for (const input of bad) assert.throws(() => mtf(input));
assert.throws(() => mtf([1], 1), TypeError);
assert.throws(() => mtf([256], true), RangeError);
assert.equal(mtf([]).length, 0);
assert.deepEqual(Array.from(mtf([255, 255])), [255, 0]);
const full = new Uint8Array(2 ** 20);
const encoded = mtf(full);
assert.equal(encoded.length, full.length);
assert.ok(encoded.every(x => x === 0));
console.log("rejected", bad.length + 2);
console.log("empty", mtf([]).length, "max block", encoded.length);精确输出:
rejected 14 empty 0 max block 1048576
示例五 所有权比返回类型更重要
返回 Uint8Array 还不足以说明接口安全。真正的约定是:不改输入、不把输入视图直接当输出、不暴露内部排列,每次调用返回自己的结果。bytes 会复制所给视图的实际元素,Buffer 的切片即使只覆盖底层缓冲区的一小段,也不会误读前后区域。输出、快照和工作表分别分配,因此后续修改输入或编码结果不会改变此前已返回的解码结果。
Node.js 文档区分了从另一个 Buffer 或类型化数组复制,与从其底层 ArrayBuffer 创建共享视图两种行为。不能为了少一次复制,擅自把传入 view 换成 view.buffer;那会同时改变所有权和有效字节范围。下面使用前后有保护字节的 Buffer 子视图,并在调用后主动修改原数组,检查可观察行为。Node.js Buffer 与类型化数组
完整示例 5,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
const input = Buffer.from([99, 65, 65, 66, 99]);
const view = input.subarray(1, 4);
const encoded = mtf(view);
assert.deepEqual(Array.from(input), [99, 65, 65, 66, 99]);
const restored = mtf(encoded, true);
input.fill(0); encoded.fill(255);
assert.deepEqual(Array.from(restored), [65, 65, 66]);
assert.deepEqual(Array.from(mtf([65, 65, 66])), [65, 0, 66]);
console.log("owned", Array.from(restored).join(","));
console.log("fresh", Array.from(mtf([65, 65, 66])).join(","));精确输出:
owned 65,65,66 fresh 65,0,66
示例六 穷举短序列而不缩小字母表
为了控制测试量,测试输入只取 0、1、255 三个值,长度从零到七,总共 3280 条序列。但算法内部仍然初始化完整的 256 字节排列。把内部字母表也缩成三个值,会改变初始 rank,测试的就不是本文协议了。选入 255 能覆盖队尾访问,选入 0 能覆盖初始队首,两者与重复符号结合能制造多种移动次序。
每个用例分别比较快速编码与列表编码、快速解码与列表解码,还用列表产生的位置流交给快速解码。第三项检查把解码输入直接当成合法 rank 序列,避免解码路径永远只能见到同一个编码器生成的测试样本。穷举是一个有限域的强检查,不能替代全部长度和状态空间的证明;它与前面的不变量推导互相补充。
完整示例 6,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
function oracle(input, decode = false) {
const list = Array.from({ length: 256 }, (_, i) => i);
return Uint8Array.from(input, x => {
const rank = decode ? x : list.indexOf(x);
const symbol = list[rank];
list.splice(rank, 1);
list.unshift(symbol);
return decode ? symbol : rank;
});
}
const alphabet = [0, 1, 255];
let cases = 0;
function visit(a) {
const encoded = mtf(a), expected = oracle(a);
assert.deepEqual(encoded, expected);
assert.deepEqual(mtf(expected, true), Uint8Array.from(a));
assert.deepEqual(mtf(a, true), oracle(a, true));
cases++;
if (a.length < 7) for (const x of alphabet) visit([...a, x]);
}
visit([]);
console.log("exhaustive", cases, "PASS");精确输出:
exhaustive 3280 PASS
示例七 固定种子的随机差分
随机测试补充较长的混合路径,但测试应可重现。这里使用固定种子和显式的整数运算,生成两百个长度小于 512 的样本,再加入全字母表正序、倒序、双轮遍历、单值长重复和两值交替。随机值取生成器的高八位,避免只盯着低位模式。生成器不是密码学随机源,也没有被当作随机性质量证据。
全字母表正序有一个容易手算的性质:第一次依次访问 0 到 255,输出仍然是 0 到 255。移动已经访问过的前缀不会改变下一个尚未访问字节的当前位置。这是与一般 roundtrip 不同的又一个外部约束。遇到断言失败,应保留种子、具体样本和第一个分歧位置,再缩减反例,而不是换一个种子直到变绿。
完整示例 7,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
function oracle(input, decode = false) {
const list = Array.from({ length: 256 }, (_, i) => i);
return Uint8Array.from(input, x => {
const rank = decode ? x : list.indexOf(x);
const symbol = list[rank];
list.splice(rank, 1);
list.unshift(symbol);
return decode ? symbol : rank;
});
}
let seed = 0x5eed1234;
function next() {
seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
return seed >>> 0;
}
const all = Array.from({ length: 256 }, (_, i) => i);
const cases = [all, all.slice().reverse(), [...all, ...all],
Array(1024).fill(255), Array.from({ length: 1024 }, (_, i) => i & 1)];
for (let t = 0; t < 200; t++) {
const n = next() % 512;
cases.push(Array.from({ length: n }, () => next() >>> 24));
}
for (const a of cases) {
assert.deepEqual(mtf(a), oracle(a));
assert.deepEqual(mtf(a, true), oracle(a, true));
assert.deepEqual(mtf(oracle(a), true), Uint8Array.from(a));
}
assert.deepEqual(Array.from(mtf(all)), all);
console.log("random and directed", cases.length, "PASS");
console.log("all 256 byte values covered");精确输出:
random and directed 205 PASS all 256 byte values covered
示例八 分块重置必须同时发生
每次调用 mtf 都从固定初始排列开始,因此它是块接口,不是能够跨调用延续状态的流对象。编码端分成两块、解码端却把位置字节拼在一起解码,会在第二块开始使用错误的排列。即使拼接后每个值仍是合法字节,也不会自动触发错误。网络分片到达的位置同样不等于算法块边界;协议必须另行保存长度或分帧信息。
此例保留一个块数组,只演示正确的重置粒度,并没有定义文件格式。实际容器需要约定块长度、初始排列版本以及完整性检查。编码器的具体物理坐标可以不同,因为对外可见的是逻辑排列;然而重置时机必须一致。若要改成连续流,应另行设计状态保存、容量耗尽后的重新编号与异常恢复,不能在当前函数里偷偷复用一份全局工作表。
完整示例 8,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
const blocks = [[65, 66, 65], [65, 65, 66]];
const encoded = blocks.map(b => mtf(b));
const joined = Uint8Array.from(encoded.flatMap(b => Array.from(b)));
const original = blocks.flat();
const correct = encoded.flatMap(b => Array.from(mtf(b, true)));
const wrong = Array.from(mtf(joined, true));
assert.deepEqual(correct, original);
assert.notDeepEqual(wrong, original);
assert.notDeepEqual(Array.from(mtf(original)), Array.from(joined));
console.log("block ranks", encoded.map(b => Array.from(b).join(",")).join(" | "));
console.log("reset roundtrip", true);
console.log("missing reset", wrong.join(","));精确输出:
block ranks 65,66,1 | 65,0,66 reset roundtrip true missing reset 65,66,65,63,63,64
示例九 可逆变换不是压缩也不是校验
一段具有局部重复的数据,经过 MTF 后可能出现大量较小的 rank,为后续游程编码或熵编码提供有用分布。但是本文每个 rank 仍保存为一个字节,64 字节输入就产生 64 字节输出,外加容器元数据后还可能更长。不能用零的数量宣称节省了多少存储,也不能把往返成功当成压缩率报告。真正的压缩比较需要指定后续编码器、头部开销以及相同输入集。
MTF 也不提供校验或认证。任意 0 到 255 的位置序列都可以被解码为某个字节序列,单字节损坏往往改变后面的排列;错误可能传播,也可能在后续操作中重新汇合,并无固定的自动恢复保证。下面故意修改首个 rank,解码依然返回合法结果,只是已不再等于原数据。需要检测损坏时,应在外层使用合适的校验机制;对抗恶意篡改则需要认证机制。
完整示例 9,保存为独立的 .cjs 文件,使用 Node.js 24 或更新版本运行。无第三方依赖。
const assert = require("node:assert/strict");
function bytes(input) {
if (!(input instanceof Uint8Array) && !Array.isArray(input))
throw new TypeError("bytes required");
if (input instanceof Uint8Array &&
((typeof SharedArrayBuffer !== "undefined" &&
input.buffer instanceof SharedArrayBuffer) || input.buffer.resizable))
throw new TypeError("stable buffer required");
if (input.length > 2 ** 20) throw new RangeError("block too large");
if (input instanceof Uint8Array) return new Uint8Array(input);
const out = new Uint8Array(input.length);
for (let i = 0; i < out.length; i++) {
const x = input[i];
if (!Number.isInteger(x) || x < 0 || x > 255)
throw new RangeError("invalid byte");
out[i] = x;
}
return out;
}
function mtf(input, decode = false) {
if (typeof decode !== "boolean") throw new TypeError("boolean mode required");
const a = bytes(input), n = a.length, size = n + 256;
const tree = new Uint32Array(size + 1);
const symbolAt = new Uint8Array(size + 1);
const pos = new Uint32Array(256), out = new Uint8Array(n);
function add(i, delta) {
for (; i <= size; i += i & -i) tree[i] += delta;
}
function sum(i) {
let s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
let step = 1;
while (step * 2 <= size) step *= 2;
function select(k) {
let i = 0;
for (let bit = step; bit > 0; bit = Math.floor(bit / 2)) {
const j = i + bit;
if (j <= size && tree[j] < k) { i = j; k -= tree[j]; }
}
return i + 1;
}
for (let b = 0; b < 256; b++) {
const q = n + 1 + b;
pos[b] = q; symbolAt[q] = b; add(q, 1);
}
let front = n;
for (let i = 0; i < n; i++) {
const q = decode ? select(a[i] + 1) : pos[a[i]];
const b = symbolAt[q];
out[i] = decode ? b : sum(q) - 1;
add(q, -1);
pos[b] = front; symbolAt[front] = b; add(front, 1);
front--;
}
return out;
}
const input = [65, 66, 65, 0].flatMap(b => Array(16).fill(b));
const encoded = mtf(input);
assert.deepEqual(Array.from(mtf(encoded, true)), input);
const damaged = encoded.slice(); damaged[0] = 66;
const decoded = mtf(damaged, true);
assert.notDeepEqual(Array.from(decoded), input);
console.log("bytes", input.length, "to", encoded.length);
console.log("zero ranks", encoded.filter(x => x === 0).length);
console.log("valid byte corruption accepted", true);精确输出:
bytes 64 to 64 zero ranks 60 valid byte corruption accepted true
成本核算与审查结论
对长度 n 的块,工作树和位置到字节的数组容量都是 n 加 257,另有 256 项的字节到位置表、n 字节输入快照和 n 字节输出。仅这些类型化数组的有效载荷合计为 7n 加 2309 字节;上限块约为 7 MiB 再加 2309 字节。这个数不包括调用者原始输入、JavaScript 对象与闭包开销、运行时管理空间、测试辅助数组以及垃圾回收期间的旧对象,不能称为进程峰值内存。
零初始化与输入复制有线性成本,初始化 256 个占用位置使用 256 次树更新。每个符号的前缀查询或顺序选择,以及两次更新,都受 log(n 加 256) 约束。因此不能把整次调用只标成一个查询的对数成本,更不能漏掉分配。对于固定的 256 字节字母表,朴素列表每步至多扫描或移动 256 项,整体相对 n 仍是线性;本实现的坐标范围却随块长增长,并额外占用线性空间。
这意味着 Fenwick 版本首先是一份可审查的顺序统计实现,并不天然比紧凑列表更快。要选择生产方案,应在目标 Node.js 版本、真实块尺寸和输入分布下测量吞吐、尾延迟与内存,同时确保双方执行相同的验证和复制工作。本文没有给出速度冠军,也没有把测试运行时包装成基准结果。
审查 AI 生成代码时,可以沿着五个问题追踪:对外位置是否从零开始,树内查询是否从一开始;每个符号是否始终只占一个位置;前端保留区是否足够且从不更新零下标;两端是否在相同块边界重置;测试是否真正跨实现比较,而非只让两个同源函数互相证明。把这些契约落进断言,才能让一段看起来简洁的可逆变换成为可维护的字节组件。
资料与复现说明
Bentley 等,A Locally Adaptive Data Compression Scheme,1986:自组织列表与两端同步的原始讨论。
Fenwick,A new data structure for cumulative frequency tables,1994:累计频数结构的原始论文摘要。
ECMAScript 2024,类型化数组规范:构造、元素类型及转换语义。
Node.js 官方 Buffer 文档:复制、共享视图与类型化数组的关系。
本文代码与测试为围绕上述接口约定独立编写。九个示例均包含所需函数与断言,可逐段复制运行;在 Node.js v24.19.0 上逐一执行,标准输出与文中一致。每个示例均设置了 60 秒超时保护,实际测试均在该限额内完成。示例中的代码重复是为了保证独立可运行,生产项目应抽成单一模块,并保留独立 oracle 作为测试代码。

