AI 代码审查实战:JavaScript Adler-32 流式计算、分块合并与滚动窗口

10-20 4阅读

审查 AI 生成的 Adler-32 实现时,最危险的代码未必复杂。有的版本把初值写成零,有的每收到一个分块就重新计算,还有的把固定窗口向前移动理解成只从校验值中减掉旧字节。它们都可能通过一条英文字符串测试,却在实际文件流、并行合并或相似片段扫描中给出错误结果。本文把这些问题放到同一套可检查的代数关系里:先确定字节和状态,再处理串接,最后推导窗口的移除与补入。

Adler-32 的核心是整数加法及模 65521 运算。这里不需要 CRC 的多项式除法、反射位序或 GF(2) 矩阵。两者虽然都能输出一个三十二位数,却不能互换递推式。本文只讨论 Adler-32;即使项目刚实现过 CRC,也应该重新确认初值、模数和合并条件。以下九个示例均为完整 Node.js 脚本,可分别保存为 .cjs 文件执行,互不依赖;每个代码块后附本次实际运行输出。

AI 代码审查实战:JavaScript Adler-32 流式计算、分块合并与滚动窗口
AI概念图:字节流、双累加器和固定窗口的视觉隐喻,不是严格电路或数据流程图。

一、先确定输入是字节,空消息也有状态

按照 RFC 1950 的 Adler-32 定义,把两个分量记作 A 和 B,初值分别为 1 和 0。读入一个字节 x 后,先令 A 等于 A 加 x 后对 65521 取模,再用更新后的 A 累加 B。结果以 B 乘 65536 加 A 打包。因此空消息是 00000001,不能因为没有输入就返回零。文件中保存的四个结果字节使用大端序;整数的显示形式与字节的存储顺序要分开讨论。

JavaScript 字符串不是字节数组。中文、表情、组合字符以及代理项会放大这个区别;直接遍历字符串并调用 charCodeAt,不能替代约定好的编码步骤。示例明确采用 UTF-8,输出中同时列出字节长度。实际协议若要求原始二进制,直接传 Uint8Array 或 Buffer 即可,不应先转成字符串再编码。对有偏移的视图也只遍历当前视图,不能把它背后的整个 ArrayBuffer 当输入。

split 检查的是规范化状态:两个分量均在零到 65520 之间,而不是任意三十二位数都能作为有效状态。最终乘法也不需要按位或;JavaScript 的按位运算容易把结果展示成有符号负数。这里始终返回可精确表示的非负 Number,十六进制只负责显示。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
for (const s of ["", "Wikipedia", "中🙂"]) {
  const bytes = Buffer.from(s, "utf8");
  console.log(JSON.stringify(s), bytes.length, hex(adler(bytes)));
}

运行输出:

"" 0 00000001
"Wikipedia" 9 11e60398
"中🙂" 7 154504f4

二、流式处理保持状态,不重新编码半个字符

一个流式对象的职责非常小:把上一次结果作为下一次更新的种子。空分块应当保持状态,读取摘要应当是观察操作,不能重置累加器或偷偷追加终止字节。若 digest 会改变状态,调用者为了显示进度而多读一次摘要,就可能改变最后结果,这种接口特别难排查。

下面枚举一份含中文与表情的 UTF-8 数据的每一个二分边界,包括首尾空块。切点可以落在一个多字节字符中间,因为校验处理的是已经编码完成的字节。不要把这种能力误解成可以随意切割 JavaScript 字符串后分别编码;如果切断代理对,各片段编码后的字节可能与完整字符串不同。网络数据已经是字节时,保持其原貌即可。

这项性质应成为 AI 代码验收的不变量:相同字节序列,无论分块尺寸、空块位置或摘要读取次数如何变化,最终值都必须相同。示例还用两边夹着干扰字节的 Buffer 验证子视图,只会计算中间三个字节。它比单测一句 hello 更接近真实的缓冲池使用方式。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
class AdlerStream {
  #value = 1;
  update(bytes) { this.#value = adler(bytes, this.#value); return this; }
  digest() { return this.#value; }
}
const data = Buffer.from("AI审查🙂", "utf8");
const expected = adler(data);
let checked = 0;
for (let cut = 0; cut <= data.length; cut++) {
  const stream = new AdlerStream();
  stream.update(data.subarray(0, cut)).update(new Uint8Array());
  const snapshot = stream.digest();
  stream.update(data.subarray(cut));
  if (stream.digest() !== expected || snapshot !== adler(data.subarray(0, cut)))
    throw new Error("split or digest mutated state");
  checked++;
}
const backing = Buffer.from([99, 1, 2, 3, 88]);
console.log("boundaries", checked);
console.log("view", hex(new AdlerStream().update(backing.subarray(1, 4)).digest()));

运行输出:

boundaries 13
view 000d0007

三、减少取模次数之前,给累加器写出上界

逐字节取模最容易审查,性能优化可以稍后进行。如果延迟取模,B 会累加不断增长的 A,增长速度是二次的,不能只看输入字节最大为 255 就认为一定安全。设批次开始时 A 与 B 都不超过 65520,连续处理 n 个最大字节后,B 的保守上界为 255×n×(n+1)÷2+(n+1)×65520。这个式子同时包含旧状态的影响和本批字节的三角形权重。

zlib 官方实现使用 5552 作为延迟取模的批次长度。下面保留这个易于核对的保守界限;它保证本批中间整数不超过无符号三十二位上界,也自然落在 JavaScript Number 的安全整数范围之内。这并不意味着 Number 每隔 5553 字节就会失真,只说明这里选择了已有清晰证明的界限,不尝试推到浮点整数精度的极限。

测试使用全 255 字节并覆盖批次前后和两批交界。作为参照的 oracle 从加权和直接计算 B,采用 BigInt 且最后才归约,结构与被测的逐步累加不同。让两个几乎相同的循环互相验证,很容易把同一个错误复制两次;换一种表达式能提高发现问题的机会。优化是否更快仍要在目标运行时测量,历史文档中的速度比较不能替代当前基准。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
function batched(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (let start = 0; start < bytes.length; start += 5552) {
    const end = Math.min(start + 5552, bytes.length);
    for (let i = start; i < end; i++) { a += bytes[i]; b += a; }
    a %= M; b %= M;
  }
  return b * 65536 + a;
}
function oracle(bytes) {
  let a = 1n, b = BigInt(bytes.length);
  for (let i = 0; i < bytes.length; i++) {
    a += BigInt(bytes[i]);
    b += BigInt(bytes.length - i) * BigInt(bytes[i]);
  }
  return Number((b % 65521n) * 65536n + a % 65521n);
}
for (const n of [0, 1, 5551, 5552, 5553, 11104, 11105]) {
  const bytes = Buffer.alloc(n, 255);
  if (batched(bytes) !== oracle(bytes)) throw new Error("batch bound");
}
const bound = n => 255 * n * (n + 1) / 2 + (n + 1) * 65520;
console.log("batch cases", 7);
console.log("5552 bound", bound(5552));
console.log("5553 bound", bound(5553));

运行输出:

batch cases 7
5552 bound 4294690200
5553 bound 4296171735

四、并行分块的合并只需要右块长度

令左块为 X,右块为 Y,右块字节长度为 m。两块都必须从标准初值独立计算。串接后 A 为 Aₓ+Aᵧ−1,减去的一来自两次初始化。右块中每一步的 A 相比独立计算增加了 Aₓ−1,因此 B 为 Bₓ+Bᵧ+m×(Aₓ−1),两个结果都对 65521 取模。这个推导只涉及普通整数运算,顺序由右块的长度承载。

zlib 手册的 adler32_combine也明确要求右侧数据长度,而不需要重新读取原始数据。下面把长度接口限定为非负 BigInt,先对模数归约,再转换成 Number。此时乘法的两个因子都有严格的小上界,后续 Number 运算依然精确。JavaScript 的百分号是余数,表达式出现负数时要用 mod 函数归一化,不能默认得到数学意义上的非负模。

示例验证全部十个切点。空右块的标准校验值是 1,长度是 0,这时合并保持左值。校验值和长度必须来自同一份数据;函数无法证明一个调用者给出的长度是真的。并行任务结果应携带校验值、字节长度和顺序编号,并按原始顺序合并。交换左右块通常改变结果,不能把合并当作无序求和。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
function combine(left, right, rightLength) {
  if (typeof rightLength !== "bigint" || rightLength < 0n)
    throw new TypeError("nonnegative BigInt length required");
  const [a1, b1] = split(left), [a2, b2] = split(right);
  const n = Number(rightLength % 65521n);
  const a = mod(a1 + a2 - 1);
  const b = mod(b1 + b2 + n * (a1 - 1));
  return b * 65536 + a;
}
const data = Buffer.from("Wikipedia");
let count = 0;
for (let cut = 0; cut <= data.length; cut++) {
  const left = data.subarray(0, cut), right = data.subarray(cut);
  const joined = combine(adler(left), adler(right), BigInt(right.length));
  if (joined !== adler(data)) throw new Error("combine");
  count++;
}
console.log("combine boundaries", count);
console.log("joined", hex(adler(data)));

运行输出:

combine boundaries 10
joined 11e60398

五、超长逻辑数据不能先经过不安全的 Number

把一个大长度先转成 Number,再调用 BigInt,并不能找回已经丢失的低位。生产接口可以接受非负 BigInt,或者先验证安全整数的 Number 后再转;本文为简化边界选择前者。长度来自数据库或对象存储元数据时,也应该检查返回类型,避免 JSON 数字在进入合并函数之前就被舍入。

本例不分配超大缓冲区,而是描述一个长度超过安全整数上限的全零后缀。零字节不会改变 A,却会在每一步把当前 A 加入 B,所以其效果可以用闭式表达式准确计算。我们先得到零块自身的标准校验值,再与前缀合并,最后用针对前缀字节直接推导的另一条表达式检查。输出中的 true 只证明两条计算一致,不表示实际读取过如此大的文件。

把长度对 65521 归约足以计算当前合并的校验值,但业务层仍应保存完整的 BigInt 长度。否则后续边界校验、文件大小检查和读写进度会失去信息。校验状态中出现周期,也不意味着不同长度的数据等价;这种压缩信息的能力正是校验值不能当唯一标识的原因之一。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
function combine(left, right, rightLength) {
  if (typeof rightLength !== "bigint" || rightLength < 0n)
    throw new TypeError("nonnegative BigInt length required");
  const [a1, b1] = split(left), [a2, b2] = split(right);
  const n = Number(rightLength % 65521n);
  const a = mod(a1 + a2 - 1);
  const b = mod(b1 + b2 + n * (a1 - 1));
  return b * 65536 + a;
}
const n = 9007199254740993n;
const prefix = Buffer.from("AI");
const left = adler(prefix);
const zeroBlock = Number(n % 65521n) * 65536 + 1;
const actual = combine(left, zeroBlock, n);
// Closed form for prefix [65, 73] followed by n zero bytes.
const expected = Number(((205n + n * 139n) % 65521n) * 65536n + 139n);
console.log("huge length", actual === expected);
console.log("digest", hex(actual));
try { combine(left, zeroBlock, Number(n)); }
catch (e) { console.log("unsafe number", e.name); }

运行输出:

huge length true
digest 1f63008b
unsafe number TypeError

六、固定窗口先移除首字节,再补入尾字节

窗口含 w 个字节,首字节是 x,新进入尾部的字节是 y。把 B 展开,可写成 w 加上 w×x₀、(w−1)×x₁,依次直到最后一个字节的权重 1。移除最前面的 x 后,剩余字节的权重不变,只有常数项少了 1。因此尾部子串的状态为 A移=A−x,B移=B−1−w×x,随后按普通追加规则加入 y。

把两步合起来得到 A新=A−x+y,B新=B−w×x+A新−1,全部模 65521。这里必须使用新的 A;漏掉减一则会使每次移动都产生偏差。宽度为一时,移除后应回到空消息状态,再补入新字节,这个小边界能迅速检验公式。窗口宽度必须大于零,移出的 x 也必须真的是当前窗口的首字节。

示例同时检查删除阶段和完整移动阶段。roll 只接收当前校验、窗口宽度以及两个字节,并不保存窗口内容。实际持续流需要环形缓冲区或其他数据结构记录将要移出的字节;若没有旧字节,仅凭校验状态不能恢复它。宽度先用 BigInt 取模,因此乘以字节时也有明确数值上界,不会因一个巨大逻辑宽度而使 Number 乘法失真。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
function roll(h, width, outgoing, incoming) {
  if (typeof width !== "bigint" || width <= 0n)
    throw new TypeError("positive BigInt width required");
  for (const x of [outgoing, incoming]) {
    if (!Number.isInteger(x) || x < 0 || x > 255)
      throw new RangeError("byte");
  }
  const [a, b] = split(h);
  const n = Number(width % 65521n);
  const nextA = mod(a - outgoing + incoming);
  const nextB = mod(b - n * outgoing + nextA - 1);
  return nextB * 65536 + nextA;
}
const first = Buffer.from("ABCD"), next = Buffer.from("BCDE");
const h = roll(adler(first), 4n, first[0], next[3]);
const [a, b] = split(adler(first));
const removed = mod(b - 1 - 4 * first[0]) * 65536 + mod(a - first[0]);
console.log("removed", hex(removed), removed === adler(Buffer.from("BCD")));
console.log("rolled", hex(h), h === adler(next));
console.log("width one", roll(adler(Buffer.from([255])), 1n, 255, 0) === 0x00010001);

运行输出:

removed 019300ca true
rolled 02a2010f true
width one true

七、窗口测试要遍历位置,也要遍历宽度

固定测试一个窗口尺寸,很可能只验证了公式的幸运路径。下面生成确定性的二百五十七字节序列,并枚举从一到完整长度的每种宽度。每个宽度都从头计算首个窗口,此后逐字节移动,再与直接重算当前窗口对照。这样既覆盖刚好一个字节,也覆盖只能产生一个窗口的全长情况,还让不同移入与移出字节反复出现。

摘要计算自身只维护两个分量,初始化一个宽度为 w 的窗口需要读取 w 个字节,之后每次移动的摘要更新为常数工作量;为了知道离开的字节,真实流仍需保存相应窗口或借助可回读数据。示例为了可审计而直接用 subarray 重算参照,整体测试成本较高,不能把测试实现的成本误当成滚动算法的成本。

这个阶段还应区分算法正确性和输入协议正确性。即使公式完全正确,如果事件乱序、重复消费,或者缓冲环指针提前推进,得到的仍是错误窗口。生产日志至少要能关联当前偏移、窗口长度和数据版本。对数据竞争造成的错读,调整取模公式不会有帮助。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
function roll(h, width, outgoing, incoming) {
  if (typeof width !== "bigint" || width <= 0n)
    throw new TypeError("positive BigInt width required");
  for (const x of [outgoing, incoming]) {
    if (!Number.isInteger(x) || x < 0 || x > 255)
      throw new RangeError("byte");
  }
  const [a, b] = split(h);
  const n = Number(width % 65521n);
  const nextA = mod(a - outgoing + incoming);
  const nextB = mod(b - n * outgoing + nextA - 1);
  return nextB * 65536 + nextA;
}
const data = Uint8Array.from({length: 257}, (_, i) => (i * 73 + 19) % 256);
let windows = 0, shifts = 0;
for (let width = 1; width <= data.length; width++) {
  let h = adler(data.subarray(0, width));
  for (let start = 0; start + width <= data.length; start++) {
    if (start > 0) {
      h = roll(h, BigInt(width), data[start - 1], data[start + width - 1]);
      shifts++;
    }
    if (h !== adler(data.subarray(start, start + width)))
      throw new Error("rolling window");
    windows++;
  }
}
console.log("windows", windows);
console.log("shifts", shifts);

运行输出:

windows 33153
shifts 32896

八、短消息分布与显式碰撞划清用途

当消息不超过二百五十六字节时,A 的最大值为 1+255×256=65281,还没有触及模数。因此低半部只是一个受限的字节和,不能假设三十二位输出均匀分布。RFC 3309 对短报文的分析指出过这种分布问题,并据此讨论 SCTP 校验方案的变化。这里引用它说明适用边界,不把某种输入分布下的结论泛化成固定的碰撞概率。

下面给出两个不同的三字节序列,二者的总和相同,加权和也相同,因此输出完全相等。差分为加一、减二、加一时,普通和的变化为零,权重三、二、一的加权变化也为零。无需遍历所有三十二位输出就能构造碰撞。这比一句抽象的校验值可能重复更能提醒代码审查者:不要将它用作去重的最终判定、签名、口令摘要或内容真实性凭据。

只有一字节时,恰好存在二百五十六个不同结果;这不表示一字节消息之间发生碰撞,而是可达结果集合很小。讨论检错能力必须给出输入和错误模型。面对主动篡改者,Adler-32 没有密钥认证能力,也不能证明发送者身份。若业务要求认证,应另外采用适当的带密钥认证机制或数字签名,并审查相应协议。

const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
const x = Buffer.from([1, 2, 3]), y = Buffer.from([2, 0, 4]);
const singleByteValues = new Set();
for (let b = 0; b <= 255; b++) singleByteValues.add(adler(Buffer.from([b])));
console.log("different bytes", !x.equals(y));
console.log("collision", hex(adler(x)), hex(adler(y)));
console.log("one-byte values", singleByteValues.size);
console.log("max A at 256 bytes", 1 + 255 * 256);

运行输出:

different bytes true
collision 000d0007 000d0007
one-byte values 256
max A at 256 bytes 65281

九、最后用原生 zlib 做独立的互操作校验

自洽还不够,最终需要确认能与现有实现交换数据。下面调用 Node 的原生 zlib,使用默认 deflateSync 产生带 zlib 包装的完整数据,再读取末尾四字节的大端 Adler-32。这只针对本例自己生成、完整且无预置字典的 zlib 输出,不是任意压缩文件的通用解析器。不要把同样的尾部读取逻辑套到 gzip 或裸 DEFLATE 上。

这里仍枚举每一个切点,分别验证流式继续和两个独立校验值的合并;然后遍历所有窗口宽度及位置,把滚动结果逐一与原生结果比较。单个正确的已知向量只能排除少量问题,跨实现加边界枚举更能暴露初值、更新顺序、视图范围以及大端读取错误。测试保留固定输入,便于持续集成复现;真正接入项目后还应补充真实数据样本和畸形接口参数。

审查 AI 代码的落点是可验证的约束:输入是明确编码的字节,空消息为标准初值,分块只延续状态;批量累加有数值上界;合并携带正确的右长度并保留精度;滚动使用旧首字节与新的 A;比较通过仍不授予认证含义。把这些要求写入测试和接口说明,才能让看似短小的校验函数在后续重构中继续可靠。

const {deflateSync} = require("node:zlib");
const M = 65521;
const mod = x => ((x % M) + M) % M;
function split(h) {
  const a = h % 65536, b = Math.floor(h / 65536);
  if (!Number.isInteger(h) || h < 0 || h > 0xffffffff ||
      a >= M || b >= M) throw new RangeError("checksum");
  return [a, b];
}
function adler(bytes, seed = 1) {
  if (!(bytes instanceof Uint8Array)) throw new TypeError("bytes");
  let [a, b] = split(seed);
  for (const x of bytes) {
    a = (a + x) % M;
    b = (b + a) % M;
  }
  return b * 65536 + a;
}
const hex = h => h.toString(16).padStart(8, "0");
function combine(left, right, rightLength) {
  if (typeof rightLength !== "bigint" || rightLength < 0n)
    throw new TypeError("nonnegative BigInt length required");
  const [a1, b1] = split(left), [a2, b2] = split(right);
  const n = Number(rightLength % 65521n);
  const a = mod(a1 + a2 - 1);
  const b = mod(b1 + b2 + n * (a1 - 1));
  return b * 65536 + a;
}
function roll(h, width, outgoing, incoming) {
  if (typeof width !== "bigint" || width <= 0n)
    throw new TypeError("positive BigInt width required");
  for (const x of [outgoing, incoming]) {
    if (!Number.isInteger(x) || x < 0 || x > 255)
      throw new RangeError("byte");
  }
  const [a, b] = split(h);
  const n = Number(width % 65521n);
  const nextA = mod(a - outgoing + incoming);
  const nextB = mod(b - n * outgoing + nextA - 1);
  return nextB * 65536 + nextA;
}
function zlibAdler(bytes) {
  const wrapped = deflateSync(bytes);
  return wrapped.readUInt32BE(wrapped.length - 4);
}
const data = Uint8Array.from({length: 33}, (_, i) => (i * 173 + 255) % 256);
const expected = zlibAdler(data);
let cuts = 0, windows = 0;
for (let cut = 0; cut <= data.length; cut++) {
  const left = data.subarray(0, cut), right = data.subarray(cut);
  if (adler(right, adler(left)) !== expected ||
      combine(zlibAdler(left), zlibAdler(right), BigInt(right.length)) !== expected)
    throw new Error("zlib split");
  cuts++;
}
for (let width = 1; width <= data.length; width++) {
  let h = adler(data.subarray(0, width));
  for (let start = 0; start + width <= data.length; start++) {
    if (start) h = roll(h, BigInt(width), data[start - 1], data[start + width - 1]);
    if (h !== zlibAdler(data.subarray(start, start + width)))
      throw new Error("zlib window");
    windows++;
  }
}
console.log("zlib boundaries", cuts);
console.log("zlib windows", windows);
console.log("empty", hex(zlibAdler(new Uint8Array())));

运行输出:

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