AI 代码审查实战:JavaScript PackBits 精确编解码与最短分包动态规划

10-20 4阅读

PackBits 的难点不只是重复多少次,而是把原样包与重复包放在哪里。本文通过九个独立示例,把格式互操作、严格校验、最短分包和 AI 代码审查连成一条可以复核的证据链。

AI 代码审查实战:JavaScript PackBits 精确编解码与最短分包动态规划
AI概念图:字节分组与路径选择的抽象表达,不代表真实文件布局。

一、先把头字节解释正确

让 AI 写一个 PackBits 压缩函数,最容易得到看似可用的游程编码:扫描相同字节,写入长度,再解码回来。问题在于,自写编码器和自写解码器可能共享同一个错误,往返测试仍然全部通过。本篇把审查目标分成三个层次:线格式是否准确,错误输入是否被明确拒绝,编码结果是否在给定分包规则下最短。每个层次都必须有独立证据。

PackBits 操作的是字节序列,不是 JavaScript 字符串,也不建立字典或概率模型。每个包先写一个头字节。无符号值 0 到 127 表示随后复制 h+1 个原始字节;129 到 255 表示将紧随的一个字节重复 257-h 次;128 表示空操作,只消耗头字节。这里的 129 对应有符号值 −127,而 255 对应 −1。把头值直接当重复次数,或者把 128 当作结束标志,都会破坏互操作。

以下九个示例都可单独保存为 .cjs 文件并用 Node.js 执行,无需安装依赖。测试环境为 Node.js v24.19.0。代码块内的辅助函数有意重复,复制任何一例都不依赖前文变量。第一例检查五个边界,并将无符号存储值与有符号解释并排打印。

function explain(h) {
  const signed = h < 128 ? h : h - 256;
  const action = h === 128 ? "noop" :
    h < 128 ? `literal:${h + 1}` : `repeat:${257 - h}`;
  return `${h} ${signed} ${action}`;
}
for (const h of [0, 127, 128, 129, 255]) console.log(explain(h));

运行输出:

0 0 literal:1
127 127 literal:128
128 -128 noop
129 -127 repeat:128
255 -1 repeat:2

注意,长度为一的字节只能使用原样包;重复包的长度范围是二到一百二十八。包的数据部分完全可以包含 128,只有解析游标位于包头时,它才具有空操作含义。审查时必须区分当前位置的角色,不能全局删除所有值为 128 的字节。

二、严格解码:完整包、输出上限与精确长度

先建立解码契约。输入必须是当前运行环境的 Uint8Array,Node.js 的 Buffer 也可使用;不接收普通数组、字符串或跨上下文的类型伪装。函数用内建长度访问器检查大小,避免自定义 length 属性绕过限制,再复制输入,让后续两遍扫描读取同一份本地数据。原始输入及展开结果上限为一 MiB;压缩输入上限则为 1,056,768 字节,即原样包最坏开销后的长度,保证最大合法原始输入编码后仍可解码。这是示例的工程策略,不是格式限制;共享内存的调用方仍应负责同步,复制过程本身不提供并发快照保证。

第一遍只验证包边界并统计长度,通过后才分配精确大小的输出;第二遍完成写入。expected 可选,但提供时必须精确匹配。整个压缩输入都会被解析,尾部空操作可以接受,尾部产生额外字节的包会触发长度错误。这个完整缓冲区接口与读取某一行后返回已消费字节数的流式接口不同,不能混用。

const assert = require("node:assert/strict");
const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function decode(input, expected) {
  const src = bytes(input, PACKED_LIMIT);
  if (expected !== undefined &&
      (!Number.isSafeInteger(expected) || expected < 0 || expected > LIMIT))
    throw new RangeError("expected length");
  function walk(out) {
    let i = 0, w = 0;
    while (i < src.length) {
      const h = src[i++];
      if (h === 128) continue;
      const literal = h < 128;
      const count = literal ? h + 1 : 257 - h;
      const need = literal ? count : 1;
      if (src.length - i < need) throw new Error("truncated packet");
      if (count > LIMIT - w) throw new RangeError("output limit");
      if (expected !== undefined && count > expected - w)
        throw new Error("length mismatch");
      if (out) {
        if (literal) out.set(src.subarray(i, i + count), w);
        else out.fill(src[i], w, w + count);
      }
      i += need;
      w += count;
    }
    if (expected !== undefined && w !== expected)
      throw new Error("length mismatch");
    return w;
  }
  const out = new Uint8Array(walk());
  walk(out);
  return out;
}
const hex = x => Buffer.from(x).toString("hex");
const packed = Buffer.from("feaa0280002afd aa0380002a22f7aa".replaceAll(" ", ""), "hex");
const raw = decode(packed, 24);
assert.equal(hex(raw), "aaaaaa80002aaaaaaaaa80002a22aaaaaaaaaaaaaaaaaaaa");
assert.deepEqual(decode(Uint8Array.of(128, 0, 128, 128), 1), Uint8Array.of(128));
console.log("Apple vector:", raw.length, "bytes");
console.log("payload 128:", hex(decode(Uint8Array.of(0, 128))));

运行输出:

Apple vector: 24 bytes
payload 128: 80

这里使用 Apple 技术说明中的既有压缩向量作为外部锚点,不是用自己的编码器制造期望值。空操作测试同时包含头部、有效数据和尾部的 128,能够抓住错误的全局过滤逻辑。两遍扫描的时间与输入及输出长度成正比;输入副本和最终结果之外只用常数工作状态。

三、先写一个保底编码器,证明空间上界

在追求最优之前,可以先构造永远合法的答案:每一百二十八个字节组成一个原样包。这种方案不尝试压缩,但给出了任何最优编码器都不能超过的上界。长度为 n 的非空输入,其结果长度为 n+向上取整的 n/128;空输入直接返回空序列。

这一上界来自我们自己选择的分包规则,不需要借用某个历史系统例程的缓冲区估计。Apple 的旧系统例程文档还讨论过以一百二十七为分组尺度的实现上界,不能不加区别地拿来替代这里的证明。代码只展示原样包基线,真正的重复数据应交给后面的最优编码器。

const assert = require("node:assert/strict");
const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function literalOnly(input) {
  const src = bytes(input);
  const out = new Uint8Array(src.length + Math.ceil(src.length / 128));
  for (let i = 0, w = 0; i < src.length; i += 128) {
    const k = Math.min(128, src.length - i);
    out[w++] = k - 1;
    out.set(src.subarray(i, i + k), w);
    w += k;
  }
  return out;
}
for (const n of [0, 1, 127, 128, 129, 256]) {
  const packed = literalOnly(new Uint8Array(n));
  assert.equal(packed.length, n + Math.ceil(n / 128));
  console.log(`${n} -> ${packed.length}`);
}

运行输出:

0 -> 0
1 -> 2
127 -> 128
128 -> 129
129 -> 131
256 -> 258

输入恰好一百二十八字节时,包头应为 127,结果为一百二十九字节。多出一个输入字节就要再付一个包头。这种包边界是审查 AI 生成循环时很有价值的检查点:小于号与小于等于号的一处偏差,可能直到长输入才暴露。

四、一个四字节反例,推翻见重复就切包

压缩局部的两个相同字节确实只需两字节,但切出重复包也可能把左右的原样数据拆成两包,各多付一个头。因此,局部节省不能直接推导出全局最短。下面故意实现一个错误的优化目标:只要遇到两字节重复就立即切包。它仍然生成合法 PackBits,错的是声称最优。

输入 1、2、2、3 总共四字节。全部放入一个原样包要五字节;先写一个原样字节,再写重复二,最后写一个原样字节,则要六字节。测试不仅打印长度,也打印完整编码,让审查者看到代价来自哪里。

function eagerRepeat(a) {
  const out = [];
  let i = 0;
  while (i < a.length) {
    let run = 1;
    while (run < 128 && i + run < a.length && a[i + run] === a[i]) run++;
    if (run >= 2) { out.push(257 - run, a[i]); i += run; continue; }
    const start = i++;
    while (i < a.length && i - start < 128 &&
           !(i + 1 < a.length && a[i] === a[i + 1])) i++;
    out.push(i - start - 1, ...a.slice(start, i));
  }
  return out;
}
const a = [1, 2, 2, 3];
const greedy = eagerRepeat(a), literal = [a.length - 1, ...a];
console.log("greedy:", greedy.join(","), "bytes=" + greedy.length);
console.log("literal:", literal.join(","), "bytes=" + literal.length);

运行输出:

greedy: 0,1,255,2,0,3 bytes=6
literal: 3,1,2,2,3 bytes=5

把阈值改成三并不等于完成了一般性最优证明。达到一百二十八字节上限、相邻游程以及末尾残余都会影响分包。教学中更稳妥的做法是把所有合法的下一包写成候选边,再让动态规划选择总长度最小的路径。

五、动态规划:最短字节数与确定性的平局规则

令 cost[i] 表示从位置 i 到末尾的最小编码字节数,终点 cost[n] 为零。从 i 选择长度 k 的原样包,总代价是 1+k+cost[i+k];选择长度 k 的重复包,必须确认对应字节全部相同,代价是 2+cost[i+k]。原样长度枚举一到一百二十八,重复长度枚举二到当前同值游程长度,并同时受剩余长度约束。

这等价于在位置零到 n 构成的有向无环图上找最短路径,每个包是一条向右的边。任何非空合法编码都有第一包;去掉第一包后,余下部分不优于对应后缀的最优代价。反过来,把候选第一包与最优后缀拼起来一定合法。由后往前归纳,就得到全局最优性,而不是凭测试数量宣布正确。空操作没有输出却增加一字节,删除它总能更短,因此最短编码不需要考虑它。

多个最短答案并存时,本文自定一个稳定规则:先比较总字节数;相等则优先重复包;包类型也相同则优先较长的第一包;后缀继续用相同规则。它不是 PackBits 标准规定的唯一编码,也不承诺包数最少或字典序最小。这种策略按合法包语法优化,不逐项复现历史编码器的分组建议;总长度相同时,内部三字节游程也可能保留在原样包中。pick 用正数保存原样长度,负数保存重复长度,最后只沿已选路径写出结果。

const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function encode(input) {
  const src = bytes(input), n = src.length;
  const cost = new Float64Array(n + 1);
  const pick = new Int16Array(n);
  for (let i = n - 1; i >= 0; i--) {
    let best = Infinity, kind = 2, length = 0;
    function offer(c, t, k) {
      if (c < best || (c === best &&
          (t < kind || (t === kind && k > length)))) {
        best = c; kind = t; length = k;
      }
    }
    const end = Math.min(128, n - i);
    for (let k = 1; k <= end; k++) offer(1 + k + cost[i + k], 1, k);
    let run = 1;
    while (run < end && src[i + run] === src[i]) run++;
    for (let k = 2; k <= run; k++) offer(2 + cost[i + k], 0, k);
    cost[i] = best;
    pick[i] = kind === 0 ? -length : length;
  }
  const out = new Uint8Array(cost[0]);
  for (let i = 0, w = 0; i < n;) {
    const k = Math.abs(pick[i]);
    if (pick[i] < 0) { out[w++] = 257 - k; out[w++] = src[i]; }
    else { out[w++] = k - 1; out.set(src.subarray(i, i + k), w); w += k; }
    i += k;
  }
  return out;
}
const hex = x => Buffer.from(x).toString("hex");
for (const a of [[1, 2, 2, 3], [5, 5, 6], [1, 2, 2, 2, 3], Array(129).fill(9), []]) {
  const p = encode(Uint8Array.from(a));
  console.log(`${a.length} bytes -> ${hex(p) || "empty"}`);
}

运行输出:

4 bytes -> 0301020203
3 bytes -> ff050006
5 bytes -> 040102020203
129 bytes -> 81090009
0 bytes -> empty

每个位置最多检查一百二十八种原样长度和一百二十七种重复长度,时间为 O(128n),把包上限视为常数时就是线性时间;代价表和选择表使用 O(n) 空间。这里存储的是整数代价,输入上限保证它远小于 Number 的精确整数边界。递归暴力搜索不能替代生产实现,后面只把它用于短输入的独立判定。

六、围绕包上限做边界回归

边界验证要同时检查编码长度和展开内容。只有长度正确,可能掩盖复制偏移错误;只有往返正确,可能掩盖分包不最优。下面把完整编解码器放在同一个独立示例里,测试重复游程的一、二、一百二十七、一百二十八、一百二十九、二百五十五、二百五十六和二百五十七字节。

一百二十九个相同字节可以拆成重复一百二十八加原样一,也可以拆成重复一百二十七加重复二,编码都为四字节。本文的平局规则会选择较长的第一重复包。这正说明精确编码断言必须与明确的本地策略绑定,不能把另一种同样合法的分包误报为格式错误。

const assert = require("node:assert/strict");
const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function encode(input) {
  const src = bytes(input), n = src.length;
  const cost = new Float64Array(n + 1);
  const pick = new Int16Array(n);
  for (let i = n - 1; i >= 0; i--) {
    let best = Infinity, kind = 2, length = 0;
    function offer(c, t, k) {
      if (c < best || (c === best &&
          (t < kind || (t === kind && k > length)))) {
        best = c; kind = t; length = k;
      }
    }
    const end = Math.min(128, n - i);
    for (let k = 1; k <= end; k++) offer(1 + k + cost[i + k], 1, k);
    let run = 1;
    while (run < end && src[i + run] === src[i]) run++;
    for (let k = 2; k <= run; k++) offer(2 + cost[i + k], 0, k);
    cost[i] = best;
    pick[i] = kind === 0 ? -length : length;
  }
  const out = new Uint8Array(cost[0]);
  for (let i = 0, w = 0; i < n;) {
    const k = Math.abs(pick[i]);
    if (pick[i] < 0) { out[w++] = 257 - k; out[w++] = src[i]; }
    else { out[w++] = k - 1; out.set(src.subarray(i, i + k), w); w += k; }
    i += k;
  }
  return out;
}
function decode(input, expected) {
  const src = bytes(input, PACKED_LIMIT);
  if (expected !== undefined &&
      (!Number.isSafeInteger(expected) || expected < 0 || expected > LIMIT))
    throw new RangeError("expected length");
  function walk(out) {
    let i = 0, w = 0;
    while (i < src.length) {
      const h = src[i++];
      if (h === 128) continue;
      const literal = h < 128;
      const count = literal ? h + 1 : 257 - h;
      const need = literal ? count : 1;
      if (src.length - i < need) throw new Error("truncated packet");
      if (count > LIMIT - w) throw new RangeError("output limit");
      if (expected !== undefined && count > expected - w)
        throw new Error("length mismatch");
      if (out) {
        if (literal) out.set(src.subarray(i, i + count), w);
        else out.fill(src[i], w, w + count);
      }
      i += need;
      w += count;
    }
    if (expected !== undefined && w !== expected)
      throw new Error("length mismatch");
    return w;
  }
  const out = new Uint8Array(walk());
  walk(out);
  return out;
}
for (const n of [1, 2, 127, 128, 129, 255, 256, 257]) {
  const raw = new Uint8Array(n).fill(9), packed = encode(raw);
  assert.deepEqual(decode(packed, n), raw);
  assert.equal(packed.length, 2 * Math.ceil(n / 128));
  console.log(`${n}: packed=${packed.length}, roundtrip=true`);
}
const everyByte = Uint8Array.from({length: 256}, (_, i) => i);
assert.deepEqual(decode(encode(everyByte), 256), everyByte);
console.log("all byte values:", encode(everyByte).length);

运行输出:

1: packed=2, roundtrip=true
2: packed=2, roundtrip=true
127: packed=2, roundtrip=true
128: packed=2, roundtrip=true
129: packed=4, roundtrip=true
255: packed=4, roundtrip=true
256: packed=4, roundtrip=true
257: packed=6, roundtrip=true
all byte values: 258

最后一项涵盖所有二百五十六种字节值,证明数据中的高位字节没有被错误地当作负数处理。若要压缩中文,应先明确采用 UTF-8 得到字节,再压缩该字节序列;解压后的字节与原始字节相等,才是这里承诺的无损。字符个数不能充当解压长度。

七、让独立枚举器审判最优长度

最危险的测试是把动态规划递推式原样复制一遍,给它换个函数名,再称为独立验证。下面的短输入判定器直接枚举所有分包路径,不保存后缀最优值,也不调用编码器。它只返回所有完整路径的最小花费。另一个解包判定器使用有符号头值和普通数组,避免与正式解码器共享两遍扫描结构。

穷举三种字节组成的所有零到七字节输入,共三千二百八十个。每个输入同时检查最短长度、独立解包后的字节一致性,以及原样包上界。这个范围无法证明任意长度的正确性,证明仍来自前面的归纳论证;穷举的价值是高密度地寻找实现是否偏离证明。

const assert = require("node:assert/strict");
const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function encode(input) {
  const src = bytes(input), n = src.length;
  const cost = new Float64Array(n + 1);
  const pick = new Int16Array(n);
  for (let i = n - 1; i >= 0; i--) {
    let best = Infinity, kind = 2, length = 0;
    function offer(c, t, k) {
      if (c < best || (c === best &&
          (t < kind || (t === kind && k > length)))) {
        best = c; kind = t; length = k;
      }
    }
    const end = Math.min(128, n - i);
    for (let k = 1; k <= end; k++) offer(1 + k + cost[i + k], 1, k);
    let run = 1;
    while (run < end && src[i + run] === src[i]) run++;
    for (let k = 2; k <= run; k++) offer(2 + cost[i + k], 0, k);
    cost[i] = best;
    pick[i] = kind === 0 ? -length : length;
  }
  const out = new Uint8Array(cost[0]);
  for (let i = 0, w = 0; i < n;) {
    const k = Math.abs(pick[i]);
    if (pick[i] < 0) { out[w++] = 257 - k; out[w++] = src[i]; }
    else { out[w++] = k - 1; out.set(src.subarray(i, i + k), w); w += k; }
    i += k;
  }
  return out;
}
function brute(a, i = 0) {
  if (i === a.length) return 0;
  let best = Infinity;
  for (let end = i + 1; end <= Math.min(i + 128, a.length); end++) {
    const k = end - i;
    best = Math.min(best, k + 1 + brute(a, end));
    if (k >= 2 && a.slice(i, end).every(v => v === a[i]))
      best = Math.min(best, 2 + brute(a, end));
  }
  return best;
}
function referenceDecode(p) {
  const out = [];
  for (let i = 0; i < p.length;) {
    const h = p[i] < 128 ? p[i] : p[i] - 256;
    i++;
    if (h === -128) continue;
    if (h >= 0) {
      assert.ok(i + h + 1 <= p.length);
      for (let j = 0; j <= h; j++) out.push(p[i++]);
    } else {
      assert.ok(i < p.length);
      const v = p[i++];
      for (let j = 0; j < 1 - h; j++) out.push(v);
    }
  }
  return out;
}
let checked = 0;
for (let n = 0; n <= 7; n++) {
  for (let id = 0; id < 3 ** n; id++) {
    let q = id;
    const a = Array.from({length: n}, () => { const v = q % 3; q = Math.floor(q / 3); return v; });
    const packed = encode(Uint8Array.from(a));
    assert.equal(packed.length, brute(a));
    assert.deepEqual(referenceDecode(packed), a);
    assert.ok(packed.length <= n + Math.ceil(n / 128));
    checked++;
  }
}
console.log("exhaustive cases:", checked);

运行输出:

exhaustive cases: 3280

固定三种值足以制造大量重复与交替结构,但它没有覆盖所有数值转换风险,所以不能替代上一节的全字节域测试。实际审查还应加入较长输入的前向最短路差分测试、所有包头和截断位置测试,并记录随机种子,让失败可复现。发布前的复核还执行了这些额外验证,测试记录用于复现与审查。

八、坏输入必须失败,空操作必须有明确策略

错误处理不是压缩算法之外的附属功能。原样包宣称的字节数多于剩余输入、重复包缺少数据字节,都必须拒绝;调用方提供的展开长度不匹配,也不能默默裁剪或补零。资源限制应在分配大输出前生效,否则一个很短的输入就可能诱使程序投入远超预期的内存。

本实现兼容读取空操作,但编码器从不主动生成它。接受空操作不等于接受任意垃圾:非空操作的尾随包仍然要完整解析,仍然要满足长度约束。若应用还要求唯一表示,应另设规范化检查,例如解码后重编码并比较,但那会拒绝许多合法的其他分包,因此不能把它混入基础解码器。

const assert = require("node:assert/strict");
const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function decode(input, expected) {
  const src = bytes(input, PACKED_LIMIT);
  if (expected !== undefined &&
      (!Number.isSafeInteger(expected) || expected < 0 || expected > LIMIT))
    throw new RangeError("expected length");
  function walk(out) {
    let i = 0, w = 0;
    while (i < src.length) {
      const h = src[i++];
      if (h === 128) continue;
      const literal = h < 128;
      const count = literal ? h + 1 : 257 - h;
      const need = literal ? count : 1;
      if (src.length - i < need) throw new Error("truncated packet");
      if (count > LIMIT - w) throw new RangeError("output limit");
      if (expected !== undefined && count > expected - w)
        throw new Error("length mismatch");
      if (out) {
        if (literal) out.set(src.subarray(i, i + count), w);
        else out.fill(src[i], w, w + count);
      }
      i += need;
      w += count;
    }
    if (expected !== undefined && w !== expected)
      throw new Error("length mismatch");
    return w;
  }
  const out = new Uint8Array(walk());
  walk(out);
  return out;
}
const cases = [
  ["literal missing", () => decode(Uint8Array.of(0))],
  ["literal short", () => decode(Uint8Array.of(2, 7, 8))],
  ["repeat missing", () => decode(Uint8Array.of(129))],
  ["too many", () => decode(Uint8Array.of(255, 7), 1)],
  ["too few", () => decode(Uint8Array.of(0, 7), 2)],
  ["bad type", () => decode([0, 7])],
  ["bad expected", () => decode(new Uint8Array(), -1)],
  ["input limit", () => decode(new Uint8Array(PACKED_LIMIT + 1))],
  ["output limit", () => decode(Uint8Array.from({length: 16386}, (_, i) => i % 2 ? 7 : 129))]
];
for (const [label, fn] of cases) {
  assert.throws(fn);
  console.log("rejected:", label);
}
assert.equal(decode(Uint8Array.of(128, 128), 0).length, 0);
console.log("noop-only: accepted");

运行输出:

rejected: literal missing
rejected: literal short
rejected: repeat missing
rejected: too many
rejected: too few
rejected: bad type
rejected: bad expected
rejected: input limit
rejected: output limit
noop-only: accepted

这里的限制分别控制压缩输入与解压输出,压缩输入预算特意包含包头开销,并不声称总进程内存只有一 MiB。输入副本、编码器动态规划表以及运行时自身都需要额外空间。生产服务还应设置请求总量、超时和并发预算;算法上的线性复杂度不是无限接收数据的理由。

九、逐行分包与文件格式的边界

TIFF 6.0 第九节要求每行单独打包,不能跨行合并游程。即使两行交界处的字节完全相同,也不能为节省两个头字节把它们压成一个跨行包。下面用两个只有两字节的示意行展示这一点:分别编码得到两个重复包,拼接原始字节后再编码则得到一个更短的包,但它失去了调用方指定的行边界。

这个示例返回每一行各自的压缩缓冲区,调用方已经知道对应的原始行长。它没有解析 TIFF 文件头、IFD、条带偏移、压缩字节计数、像素采样或行布局,也没有实现 PICT。不能把这组函数包装成支持任意 TIFF 的图片读取器。若接入真实容器,应先由容器层验证长度和布局,再把单行的确切字节交给该编解码层。

const assert = require("node:assert/strict");
const LIMIT = 1 << 20;
const PACKED_LIMIT = LIMIT + Math.ceil(LIMIT / 128);
const arrayLength = Object.getOwnPropertyDescriptor(
  Object.getPrototypeOf(Uint8Array.prototype), "length").get;
function bytes(x, limit = LIMIT) {
  if (!(x instanceof Uint8Array)) throw new TypeError("bytes required");
  if (arrayLength.call(x) > limit) throw new RangeError("input limit");
  return new Uint8Array(x);
}
function encode(input) {
  const src = bytes(input), n = src.length;
  const cost = new Float64Array(n + 1);
  const pick = new Int16Array(n);
  for (let i = n - 1; i >= 0; i--) {
    let best = Infinity, kind = 2, length = 0;
    function offer(c, t, k) {
      if (c < best || (c === best &&
          (t < kind || (t === kind && k > length)))) {
        best = c; kind = t; length = k;
      }
    }
    const end = Math.min(128, n - i);
    for (let k = 1; k <= end; k++) offer(1 + k + cost[i + k], 1, k);
    let run = 1;
    while (run < end && src[i + run] === src[i]) run++;
    for (let k = 2; k <= run; k++) offer(2 + cost[i + k], 0, k);
    cost[i] = best;
    pick[i] = kind === 0 ? -length : length;
  }
  const out = new Uint8Array(cost[0]);
  for (let i = 0, w = 0; i < n;) {
    const k = Math.abs(pick[i]);
    if (pick[i] < 0) { out[w++] = 257 - k; out[w++] = src[i]; }
    else { out[w++] = k - 1; out.set(src.subarray(i, i + k), w); w += k; }
    i += k;
  }
  return out;
}
const hex = x => Buffer.from(x).toString("hex");
const rows = [Uint8Array.of(7, 7), Uint8Array.of(7, 7)];
const perRow = rows.map(encode);
const joined = encode(Uint8Array.of(...rows[0], ...rows[1]));
assert.equal(perRow.reduce((sum, p) => sum + p.length, 0), 4);
assert.equal(joined.length, 2);
console.log("rows:", perRow.map(hex).join(" | "));
console.log("cross-row bytes:", hex(joined));
console.log("use per-row packets when row boundaries apply");

运行输出:

rows: ff07 | ff07
cross-row bytes: fd07
use per-row packets when row boundaries apply

审查的最终结论应说清楚三个不同承诺:合法包能够被精确解码;本文编码器在单次调用的字节范围内达到最小长度;确定性的平局策略让同一输入得到可重复的输出。最短只相对于给定包语法和给定边界成立,不代表比通用压缩器更小,也不代表文件容器完整有效。让 AI 同时给出契约、反例、证明与独立测试,比只要求它写一个能跑的函数可靠得多。

参考资料与复核范围

最短路建模、平局选择、资源上限和测试程序为本文的实现设计,并非上述规范强制指定的编码策略。规范事实与工程策略分开标注,才能避免把特定实现的行为误称为标准要求。

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