AI 代码审查实战:让字节环形缓冲区守住容量、回绕与所有权边界

10-19 5阅读

环形缓冲区的代码常常短得让人放松警惕:一个 Uint8Array、两个索引,再加几次取余,看起来就能接住不断到来的字节。但 AI 生成的实现最容易漏掉的,恰恰是这几行算术背后的约定:标称容量到底能不能写满,失败是否留下半次写入,读出的字节归谁所有,以及一圈之后如何辨认空满。

本文审查一个同步、固定容量、先进先出的字节容器。它不负责消息边界、字符解码或等待调度,也不会在满时覆盖旧数据。我们先用反例建立契约,再给出可复用基线,最后用不同结构的参考模型验证操作轨迹。全部九个代码块在 Node.js v24.19.0 下独立运行,命令形式为 node --unhandled-rejections=strict 01.mjs;把文件名替换为对应编号即可。该选项用于让未处理的 Promise 拒绝以错误暴露,本文核心操作本身全部同步。

AI 代码审查实战:让字节环形缓冲区守住容量、回绕与所有权边界
概念插画:槽位首尾相接,读写标记沿环移动;环外字节代表独立副本。图中格数与标记位置不对应代码实例。

一、先证明两个指针不足以区分空和满

让 AI 生成环形缓冲区时,一个很像正确答案的实现,是用读位置与写位置是否相等判断空,再把每次移动对容量取余。问题在于,写满一整圈后,写位置也回到了读位置。只有位置而没有其他信息,无法知道这一圈到底没有数据,还是每个槽位都已占用。这个问题不会出现在只写两个字节再读两个字节的演示里,却会直接吞掉恰好填满的输入。

这里明确选择计数方案:容量为 C,已用数量为 size,满足零到 C 的闭区间;读写位置始终位于零到 C 减一之间。空由 size 等于零表示,满由 size 等于 C 表示。另一种保留空槽方案也能正确工作,但分配 C 个槽位时只能使用 C 减一字节。如果接口承诺可写满 C 字节,就不能偷偷混用这两套定义。下面的反例只演示歧义,不作为可复用组件。

示例 1,保存为 01.mjs:

import assert from "node:assert/strict";
const capacity = 3;
let read = 0, write = 0, size = 0;
console.log("empty", read === write, size);
for (const byte of [7, 8, 9]) {
  void byte;
  write = (write + 1) % capacity;
  size++;
}
assert.equal(read, write);
assert.equal(size, capacity);
console.log("full", read === write, size);
console.log("same pointers, different states");

精确输出:

empty true 0
full true 3
same pointers, different states

二、把精确容量写进完整实现

下面是本文使用的完整基线。每个后续代码块都重复所需定义,复制成独立的 .mjs 文件即可运行,不依赖前文文件。输入只接受同一 JavaScript 运行上下文中的普通 Uint8Array 或 Node.js Buffer;不支持代理、篡改访问器的子类、被修改的内建方法,以及跨线程共享内存。可调整大小的底层缓冲区也被明确拒绝。构造器要求正的安全整数;通过数字校验不等于一定能分配成功,实际内存与运行时上限仍可能让构造失败。

写入采用全有或全无的契约:空闲空间足够才返回 true,否则返回 false 并保持原状态。读取与预览要求非负安全整数,数据不足返回 null,零长度成功返回空数组。它们都不自动截短请求。这个决定让调用方能够区分“没有拿够”与“成功拿到零个字节”。state 只返回数字组成的新对象,供测试观察,不泄露内部存储。测试从容量一开始,因为只测常见的二次幂容量,会漏掉最容易暴露空满冲突的边界。

示例 2,保存为 02.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
for (const capacity of [1, 3, 5]) {
  const ring = new ByteRing(capacity);
  const input = Uint8Array.from({ length: capacity }, (_, i) => i + 1);
  assert.equal(ring.write(input), true);
  assert.equal(ring.free, 0);
  assert.equal(ring.write(Uint8Array.of(99)), false);
  assert.deepEqual([...ring.read(capacity)], [...input]);
  assert.equal(ring.size, 0);
  console.log(`capacity=${capacity} exact=true empty=true`);
}

精确输出:

capacity=1 exact=true empty=true
capacity=3 exact=true empty=true
capacity=5 exact=true empty=true

这里的容量限制针对尚未消费的字节和固定内部存储,不是整个进程的内存上限。写入快照与返回副本会产生临时分配,调用方长期持有结果也会占用额外内存。审查时若只看内部数组固定大小,就宣称整个链路内存恒定,会把接口保证扩大到它无法控制的范围。

三、跨尾部写入与读取都必须拆成两段

环形存储的逻辑顺序连续,物理位置不一定连续。写入 n 个字节时,第一段长度是 n 与“容量减写位置”的较小值;剩余部分从物理位置零开始。读取做相同分割,但以读位置为起点,第二段复制到结果中的第一段之后。最常见的错误,是写入做了回绕,读取仍然用一次切片;另一个错误则是第二段的目标偏移仍写成零,覆盖了已经复制的前缀。

此处故意使用容量五。先写四字节、读三字节,再写四字节,让未读的旧字节与跨边界的新字节组成一个满环。只有 FIFO 内容、两个指针和已用计数同时正确,测试才通过。指针用取余计算,不能随意替换成按位与容量减一;那种优化需要容量为二次幂等前提,而本文接口允许任意可分配的正容量。这里先保留清晰的公式,再考虑基准测试能否证明优化值得引入。

示例 3,保存为 03.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
const ring = new ByteRing(5);
ring.write(Uint8Array.of(10, 11, 12, 13));
assert.deepEqual([...ring.read(3)], [10, 11, 12]);
ring.write(Uint8Array.of(20, 21, 22, 23));
assert.deepEqual(ring.state(), { read: 3, write: 3, size: 5, free: 0 });
console.log("full", JSON.stringify([...ring.peek()]));
assert.deepEqual([...ring.read(4)], [13, 20, 21, 22]);
console.log("remaining", JSON.stringify([...ring.read()]));
assert.deepEqual(ring.state(), { read: 3, write: 3, size: 0, free: 5 });

精确输出:

full [13,20,21,22,23]
remaining [23]

两次 set 负责字节复制,最后才提交写位置和数量。ECMAScript 的 TypedArray.set 定义了按目标偏移复制元素的行为;本文额外规定的容量判断、两段布局与提交顺序,是组件自己的契约,并非标准库自动替我们完成的事务。

四、拒绝写入时,连已经存好的字节也不能改变

“容量不够时返回 false”还不够完整。若实现一边逐字节写入,一边检查空间,它可能先吃掉输入前半段,最后才报告失败。调用方拿原始输入重试,就会造成重复。还有一种更隐蔽的错误:先覆盖内部槽位,之后恢复计数和指针,表面 state 没变,未读内容却已经损坏。因此回归测试必须同时比对状态快照与完整可读内容。

这里把失败分成两类。容量不足属于正常结果,返回 false;输入类型错误或计数不合法属于调用错误,抛出异常。所有这些被测试的路径都不消费旧数据。实现先做类型和存储形态检查,再判断空闲量,成功路径才复制输入并提交。所谓原子拒写只是在本同步对象的契约内没有部分成功,既不是 SharedArrayBuffer 上的原子操作,也不是跨线程或跨进程事务。不要让一个听起来安全的形容词掩盖实际适用范围。

示例 4,保存为 04.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
const ring = new ByteRing(5);
ring.write(Uint8Array.of(1, 2, 3, 4));
ring.read(2);
ring.write(Uint8Array.of(5, 6));
const state = ring.state();
const bytes = ring.peek();
assert.equal(ring.write(Uint8Array.of(7, 8)), false);
assert.throws(() => ring.write([7]), TypeError);
assert.throws(() => ring.read(-1), RangeError);
assert.equal(ring.read(5), null);
assert.deepEqual(ring.state(), state);
assert.deepEqual(ring.peek(), bytes);
console.log("unchanged", JSON.stringify([...ring.peek()]));
assert.equal(ring.write(Uint8Array.of(7)), true);
console.log("retry", JSON.stringify([...ring.read()]));

精确输出:

unchanged [3,4,5,6]
retry [3,4,5,6,7]

五、复制边界决定谁拥有这些字节

AI 常把 slice 和 subarray 当作可互换的“取一段”。这在所有权设计里很危险。普通 Uint8Array 的 subarray 与原数组共享底层存储;Node.js Buffer 的 slice 也保留共享视图,而普通 Uint8Array 的 slice 会复制。Node.js 官方文档专门列出了这项差异。方法名相同,并不意味着所有权一致。本文写入前使用 new Uint8Array(source) 得到自己的快照;输出则新建 Uint8Array,再把逻辑内容复制进去。内部临时 subarray 只在同步复制中使用,绝不作为公开结果逃逸。

下面同时测试两条方向。修改原始输入,不能倒过来更改环内数据;修改 peek 或 read 返回的结果,也不能影响还未读取的内容。输入还刻意选成具有非零偏移的视图,确保实现复制的是视图覆盖的字节,而非 source.buffer 里的整个底层内存。对池化 Buffer 尤其不能忽略这个区别。复制有成本,但它换来了容易解释的生命周期;若以后改成零复制接口,就必须另行定义借用期限和失效规则,不能只删掉一次分配。

示例 5,保存为 05.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
const buffer = Buffer.from([1, 2]);
const bufferView = buffer.slice(0, 1);
const owned = new Uint8Array(buffer);
bufferView[0] = 9;
assert.deepEqual([...owned], [1, 2]);
console.log("buffer", JSON.stringify([...buffer]), "copy", JSON.stringify([...owned]));
const backing = Uint8Array.of(90, 4, 5, 91);
const input = backing.subarray(1, 3);
const ring = new ByteRing(4);
ring.write(input);
input.fill(99);
assert.deepEqual([...ring.peek()], [4, 5]);
const preview = ring.peek();
preview[0] = 88;
assert.deepEqual([...ring.peek()], [4, 5]);
const output = ring.read(1);
assert.deepEqual([...output], [4]);
output[0] = 77;
ring.write(Uint8Array.of(6, 7, 8));
assert.deepEqual([...output], [77]);
assert.deepEqual([...ring.peek()], [5, 6, 7, 8]);
console.log("remaining", JSON.stringify([...ring.read()]));

精确输出:

buffer [9,2] copy [1,2]
remaining [5,6,7,8]

六、peek 是非消费式快照,read 才推进位置

预览接口最重要的不是名字,而是它对状态的承诺。peek 成功时返回当前前缀的独立副本,不更新读位置;数据不足则返回 null,仍然不移动任何位置。read 复用同样的检查与复制,只有得到完整结果后才推进读位置并减少已用量。如此一来,读取长度错误或无法拿到完整请求,都不会让后续读取从错误位置开始。

调用方必须用严格的 null 判断表达数据不足。空 Uint8Array 也是一次成功结果,不能把“长度等于零”误认成失败。连续两次 peek 得到相同内容,并不代表返回同一个对象;它们应该各自拥有存储。下面在预览后继续写入,再消费原来的前缀,验证预览没有暗中占位。这里没有异步等待和锁;如果业务在 peek 与 read 之间安排了其他调用,看到的内容自然可能改变,业务需要自己保证组合操作的执行顺序。

示例 6,保存为 06.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
const ring = new ByteRing(4);
ring.write(Uint8Array.of(30, 31));
const before = ring.state();
assert.equal(ring.peek(3), null);
assert.deepEqual(ring.state(), before);
const first = ring.peek(2), second = ring.peek(2);
assert.notEqual(first, second);
assert.deepEqual(first, second);
assert.equal(ring.read(0).length, 0);
assert.deepEqual(ring.state(), before);
ring.write(Uint8Array.of(32));
console.log("peek", JSON.stringify([...first]));
console.log("read", JSON.stringify([...ring.read(2)]));
console.log("tail", JSON.stringify([...ring.read()]));
assert.equal(ring.read(1), null);

精确输出:

peek [30,31]
read [30,31]
tail [32]

七、reset 是可复用边界,不是隐含的关闭动作

重置需要回答三个问题:旧的未读字节还能不能读到,读写位置是否回到统一起点,以及对象之后能否重新使用。本文 reset 清零整个内部字节数组,再把两个位置和计数设为零。它没有关闭状态,没有等待者,也不会通知外部生产者。重置后可以立刻写入新的数据,容量保持不变。这个生命周期选择应当写进接口说明,而不是让调用方从函数名猜测。

清零内部数组不等于安全销毁数据。已经交给调用方的副本仍然存在,写入时的临时快照也由运行时管理;不能把这一行 fill 宣传为可靠的机密擦除。它的时间复杂度与容量成正比,频繁重置大容量对象时要计入成本。若业务只需要逻辑清空,可以设计另一种明确命名的接口,但那是不同的清理保证。本例保留一份重置前的预览,检查它不随内部清零而变化,并验证新一轮写读完全独立。

示例 7,保存为 07.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
const ring = new ByteRing(3);
ring.write(Uint8Array.of(7, 8, 9));
ring.read(2);
ring.write(Uint8Array.of(10, 11));
const oldSnapshot = ring.peek();
ring.reset();
assert.deepEqual(ring.state(), { read: 0, write: 0, size: 0, free: 3 });
assert.equal(ring.read(1), null);
assert.equal(ring.read().length, 0);
ring.write(Uint8Array.of(1, 2, 3));
console.log("old", JSON.stringify([...oldSnapshot]));
console.log("new", JSON.stringify([...ring.read()]));
ring.reset(); ring.reset();
console.log("reset twice", JSON.stringify(ring.state()));

精确输出:

old [9,10,11]
new [1,2,3]
reset twice {"read":0,"write":0,"size":0,"free":3}

八、零长度、非法计数与底层存储形态要有固定答案

边界审查不能止于“正数和负数”。字符串三、三点五、无穷大与非数值都不能悄悄参与索引算术;同样,构造容量零没有可用的取余空间,应当直接拒绝。负零在这里视作零,零长度写入即使面对满环也成功,并且不移动位置。超过当前数据量的非负安全整数请求则返回 null,这与参数类型错误是不同的分支。

底层缓冲区同样影响契约。共享内存允许其他线程同时改变输入,复制不自动构成整段一致的快照,所以这里拒绝 SharedArrayBuffer。检测使用Node.js 的 types.isSharedArrayBuffer,避免用 instanceof 漏掉其他运行上下文产生的共享底层存储。即使外层 Uint8Array 在本地创建,这种共享来源也必须被拒绝。可调整大小的 ArrayBuffer 也排除在接口范围外。对于已经转移而分离的普通缓冲区,复制构造器会抛错,且发生在内部写入之前。不要为兼容所有输入形态随手增加隐式转换;让调用方先完成格式选择,能让字节容器保持足够小的审计面。下面把这些分支变成可重复的固定断言。

示例 8,保存为 08.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
import { runInNewContext } from "node:vm";
for (const value of [0, -1, 1.5, NaN, Infinity, "3"])
  assert.throws(() => new ByteRing(value), RangeError);
const ring = new ByteRing(1);
ring.write(Uint8Array.of(42));
const before = ring.state();
assert.equal(ring.write(new Uint8Array(0)), true);
assert.equal(ring.peek(-0).length, 0);
for (const count of [-1, 0.5, NaN, Infinity, "1"])
  assert.throws(() => ring.peek(count), RangeError);
assert.equal(ring.peek(Number.MAX_SAFE_INTEGER), null);
assert.throws(() => ring.write(new Uint8Array(new SharedArrayBuffer(1))), TypeError);
const foreignShared = runInNewContext("new SharedArrayBuffer(1)");
assert.throws(() => ring.write(new Uint8Array(foreignShared)), TypeError);
assert.throws(() => ring.write(new Uint8Array(new ArrayBuffer(1, { maxByteLength: 2 }))), TypeError);
const detached = Uint8Array.of(9);
structuredClone(detached.buffer, { transfer: [detached.buffer] });
assert.throws(() => ring.write(detached), TypeError);
assert.deepEqual(ring.state(), before);
assert.deepEqual([...ring.read()], [42]);
console.log("validation and zero-length: ok");

精确输出:

validation and zero-length: ok

九、用结构不同的参考模型检查随机操作轨迹

最后一步不是再挑一个更大的容量,而是改变验证方式。参考模型使用普通数组保存逻辑顺序,成功写入追加元素,读取用 splice 移走前缀,预览用 slice 复制;它不复用环形实现的两段偏移算法。这样两个实现不容易因为抄了同一个错误公式而一起通过。固定种子的伪随机序列保证失败可以复现,容量一、二、三、五、八覆盖最小容量、奇数容量和常见二次幂容量。

每一步不仅比较返回值,还检查全部内容、已用量、空闲量,以及写位置等于读位置加已用量对容量取余。随机操作包括写入、读取、预览与重置;成功写入后立即修改输入,返回结果也立即修改,以持续攻击所有权边界。六个种子、五种容量、每组一千步,共三万次状态转移。随机测试不是数学证明,也不能代替前面的定向反例;它的价值是探索人工不容易想到的组合顺序,并把每一次失败定位到具体种子、容量与步骤。

示例 9,保存为 09.mjs:

import assert from "node:assert/strict";
import { types } from "node:util";
class ByteRing {
  #bytes; #r = 0; #w = 0; #size = 0;
  constructor(capacity) {
    if (!Number.isSafeInteger(capacity) || capacity < 1)
      throw new RangeError("capacity");
    this.#bytes = new Uint8Array(capacity);
  }
  get capacity() { return this.#bytes.length; }
  get size() { return this.#size; }
  get free() { return this.capacity - this.#size; }
  state() {
    return { read: this.#r, write: this.#w,
      size: this.#size, free: this.free };
  }
  write(source) {
    if (!(source instanceof Uint8Array))
      throw new TypeError("Uint8Array required");
    if (types.isSharedArrayBuffer(source.buffer) || source.buffer.resizable)
      throw new TypeError("fixed non-shared buffer required");
    const n = source.byteLength;
    if (n > this.free) return false;
    const copy = new Uint8Array(source);
    const first = Math.min(n, this.capacity - this.#w);
    this.#bytes.set(copy.subarray(0, first), this.#w);
    this.#bytes.set(copy.subarray(first), 0);
    this.#w = (this.#w + n) % this.capacity;
    this.#size += n;
    return true;
  }
  peek(n = this.#size) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("count");
    if (n > this.#size) return null;
    const out = new Uint8Array(n);
    const first = Math.min(n, this.capacity - this.#r);
    out.set(this.#bytes.subarray(this.#r, this.#r + first));
    out.set(this.#bytes.subarray(0, n - first), first);
    return out;
  }
  read(n = this.#size) {
    const out = this.peek(n);
    if (out === null) return null;
    this.#r = (this.#r + n) % this.capacity;
    this.#size -= n;
    return out;
  }
  reset() {
    this.#bytes.fill(0);
    this.#r = this.#w = this.#size = 0;
  }
}
let steps = 0;
for (const capacity of [1, 2, 3, 5, 8]) {
  for (let seed = 1; seed <= 6; seed++) {
    let random = seed;
    const next = () => (random = (Math.imul(random, 1664525) + 1013904223) >>> 0);
    const ring = new ByteRing(capacity);
    const model = [];
    for (let step = 0; step < 1000; step++) {
      const context = `capacity=${capacity} seed=${seed} step=${step}`;
      const operation = next() % 7;
      const n = next() % (capacity + 3);
      if (operation <= 2) {
        const input = Uint8Array.from({ length: n }, () => next() >>> 24);
        const expected = n <= capacity - model.length;
        assert.equal(ring.write(input), expected, context);
        if (expected) model.push(...input);
        input.fill(255);
      } else if (operation === 6) {
        ring.reset(); model.length = 0;
      } else {
        const consume = operation === 3;
        const output = consume ? ring.read(n) : ring.peek(n);
        const expected = n > model.length ? null
          : consume ? model.splice(0, n) : model.slice(0, n);
        assert.deepEqual(output === null ? null : [...output], expected, context);
        if (output !== null) output.fill(255);
      }
      assert.deepEqual([...ring.peek()], model, context);
      assert.equal(ring.size, model.length, context);
      assert.equal(ring.free, capacity - model.length, context);
      const state = ring.state();
      assert.ok(state.read >= 0 && state.read < capacity, context);
      assert.ok(state.write >= 0 && state.write < capacity, context);
      assert.equal(state.write, (state.read + state.size) % capacity, context);
      steps++;
    }
  }
}
console.log(`model transitions=${steps} mismatches=0`);

精确输出:

model transitions=30000 mismatches=0

交付给 AI 的下一轮修改要求,可以直接围绕这些契约展开:保留任意正容量、禁止覆盖未读数据、拒写保持状态、对外仅交付副本,并让九个示例和参考模型继续通过。等需要批量零复制读取、异步背压或共享内存协议时,再建立新的接口与验证模型。把眼前这个同步字节容器的边界收紧,比先给它塞进更多能力更容易发现真实缺陷。

官方依据与审查边界

ECMAScript:TypedArray.set用于核对偏移复制语义;TypedArray.subarray用于核对共享底层存储;从 TypedArray 初始化新 TypedArray用于核对复制构造路径。

Node.js 24:Buffer 与 TypedArray说明 Buffer 的继承关系与 slice 的兼容性差异;Node.js:严格断言模式是测试使用严格比较的依据。本文的容量、拒写、重置与所有权规则是显式选择的组件契约,官方资料并没有替这些自定义规则背书。

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