AI 代码评审实战:用 JavaScript BigInt 写清 Elias–Fano 单调序列编码

10-20 5阅读

AI 很容易写出一个能往返的小型压缩器,也容易在最后一句顺手宣称常数时间访问、接近理论最优。Elias–Fano 恰好适合拆开这两件事审查:表示本身很简洁,访问代价与物理存储却必须单独核算。本文以 JavaScript BigInt 构造一份可运行、可拒绝畸形输入的参考实现,重点是单调非负整数序列的高低位分离、重复值、规范字节格式和独立测试。

九段代码都能单独保存为 .cjs 并用 Node.js 执行,不读取外部文件,也不依赖第三方包。为保证复制后即运行,涉及完整对象的示例会重复实现。所有输出都来自本机 Node.js v24.19.0 的实际执行。本文只讨论静态序列;它没有把单调性问题转交给排序器,也没有实现通用 rank/select 原语、Wavelet Matrix 或逐整数变长编码。

AI 代码评审实战:用 JavaScript BigInt 写清 Elias–Fano 单调序列编码
AI概念图:单调数列拆为低位流与一元高位流,画面不代表精确位位置。

一、先审输入契约,别让大整数先丢精度

设原数组为 x,长度为 n,要求每个元素都是非负 BigInt,且允许相邻元素相等。排序与去重都不属于编码器职责:自动排序会改变序号含义,自动去重会丢掉重复次数。Number 转成 BigInt 也不能补回已经舍入的整数,因此调用方应从十进制字符串或带 n 的字面量构造值。查询参数可以为负,因为负阈值的 lowerBound 合理地返回零;存储值则不能为负。

下面这段是 AI 代码评审中首先应该单独跑的检查。普通 Number 的位运算会进入三十二位整数规则,BigInt 位运算采用自己的整数语义,两种操作数不能随意混算。我们只把经过证明很小的下标和高位商转成 Number,原始数值始终保留为 BigInt。这个边界必须先于压缩率讨论,否则漂亮的位图可能只是精确编码了错误输入。

'use strict';
function check(a) {
  let prev = 0n;
  for (const x of a) {
    if (typeof x !== 'bigint') throw new TypeError('bigint');
    if (x < prev) throw new RangeError('order');
    prev = x;
  }
  return true;
}
console.log(check([0n, 0n, 9007199254740993n]));
console.log(BigInt('9007199254740993').toString());
for (const a of [[1], [-1n], [2n, 1n]]) {
  try { check(a); } catch (e) { console.log(e.name); }
}
console.log(1 << 40, (1n << 40n).toString());

输出:

true
9007199254740993
TypeError
RangeError
RangeError
256 1099511627776

二、低位宽度由整数除法决定

本文选用最大值 M 作为包含端点的上界。非空数组取 l=max(0,floor(log₂(M/n)));空数组规定 l=0。代码先做 BigInt 整数除法,再逐次右移求宽度,避开 Number、浮点对数和二的幂附近的舍入问题。M 为零或小于 n 时都得到零宽低位,这并不表示数据不存在,而是所有信息暂时都由高位流承担。

每个值拆成 hi=x 右移 l 位以及 lo=x 与低位掩码。重组时左移 hi,再与 lo 合并。低位流按原次序存放恰好 n·l 个逻辑位;零宽字段不占位,不能偷偷补一个零。这里的宽度选择是标准的简单规则,并非逐个尝试所有宽度之后选最短字节串。小数据中,字节对齐和固定头部往往比一两位的理论差异更重要。

'use strict';
const a = [0n, 2n, 7n, 8n, 8n, 21n];
let q = a.at(-1) / BigInt(a.length), l = 0n;
while (q > 1n) { q >>= 1n; l++; }
const mask = (1n << l) - 1n;
console.log('l=' + l);
console.log('hi=' + a.map(x => x >> l).join(','));
console.log('lo=' + a.map(x => x & mask).join(','));
console.log('ok=' + a.every(x => ((x >> l) << l | (x & mask)) === x));

输出:

l=1
hi=0,1,3,4,4,10
lo=0,0,1,0,0,1
ok=true

三、高位一元流为何能保留重复值

采用从零开始的下标,把第 i 个一放在 pᵢ=hiᵢ+i。因为高位商不下降,位置必然严格增加;即使两个值完全相同,它们也占据相邻的两个一,所以不会覆盖。高位流的逻辑长度取最后一个一的位置加一,记为 H=floor(M/2ˡ)+n,不另放结束哨兵,也不保留尾部零。空数组则 H=0。

从左到右扫描时,每遇到一个零,高位商加一;每遇到一个一,就将当前高位与对应低位重组。等价地,第 i 个一之前有 pᵢ-i 个零。这是解码公式的来源,不是可以直接导出常数时间访问的性能保证。下面故意保留容易观察的数组和字符串:它们用于解释表示,不能把字符串长度称为 JavaScript 实际占用的内存位数。

'use strict';
const a = [0n, 2n, 7n, 8n, 8n, 21n], l = 1n;
const low = a.map(x => x & 1n);
const pos = a.map((x, i) => Number(x >> l) + i);
const high = Array(pos.at(-1) + 1).fill(0);
for (const p of pos) high[p] = 1;
let zeros = 0n, i = 0;
const out = [];
for (const b of high) {
  if (b === 0) zeros++;
  else out.push((zeros << l) | low[i++]);
}
console.log(pos.join(','));
console.log(high.join(''));
console.log(out.join(','));

输出:

0,2,5,7,8,15
1010010110000001
0,2,7,8,8,21

四、完整实现:位打包、get 与一次扫描解码

以下实现不依赖外部包。每个字节内部采用最低有效位优先;低位字段内部也从最低位向高位写入。所有可变缓冲区都放在私有字段中,调用方不能直接修改它们。decode 返回新数组,bytes 返回新 Buffer,导入时重新构建对象,避免输入缓冲区与对象共享可变存储。这样才能把构造成功当作后续查询的可信前提。

为使演示有可检查的资源边界,约定 n≤4096、l≤4096。拒绝超出预算是本文文件格式的限制,绝非 Elias–Fano 的数学限制。在所选宽度下,高位商小于 2n,因此 H 小于 3n;这也解释了为何相关 Number 转换是精确的。实现没有 select 索引:get 从头数一,最坏扫描 H 位并读 l 个低位;decode 一次扫描高位流,总计读取 H+n·l 个位。这里说的是位访问和 BigInt 操作的次数,大整数运算本身也不是固定成本。

'use strict';
const MAX_N = 4096, MAX_L = 4096;
const bit = (b, p) => (b[Math.floor(p / 8)] >> (p % 8)) & 1;
const set = (b, p) => { b[Math.floor(p / 8)] |= 1 << (p % 8); };
function lowAt(b, i, l) {
  let x = 0n;
  for (let j = l - 1; j >= 0; j--) x = (x << 1n) | BigInt(bit(b, i * l + j));
  return x;
}
function width(a) {
  let q = a.length ? a.at(-1) / BigInt(a.length) : 0n, l = 0;
  while (q > 1n) { q >>= 1n; if (++l > MAX_L) throw new RangeError('budget'); }
  return l;
}
class EF {
  #n; #l; #h; #lo; #hi;
  constructor(a) {
    if (!Array.isArray(a)) throw new TypeError('array');
    if (a.length > MAX_N) throw new RangeError('budget');
    let prev = 0n;
    for (const x of a) {
      if (typeof x !== 'bigint') throw new TypeError('bigint');
      if (x < prev) throw new RangeError('order');
      prev = x;
    }
    this.#n = a.length; this.#l = width(a);
    const l = BigInt(this.#l);
    this.#h = a.length ? Number(a.at(-1) >> l) + a.length : 0;
    this.#lo = Buffer.alloc(Math.ceil(a.length * this.#l / 8));
    this.#hi = Buffer.alloc(Math.ceil(this.#h / 8));
    a.forEach((x, i) => {
      for (let j = 0; j < this.#l; j++) {
        if ((x >> BigInt(j)) & 1n) set(this.#lo, i * this.#l + j);
      }
      set(this.#hi, Number(x >> l) + i);
    });
  }
  get length() { return this.#n; }
  layout() { return { n: this.#n, l: this.#l, h: this.#h,
    lowBytes: this.#lo.length, highBytes: this.#hi.length }; }
  get(i) {
    if (!Number.isInteger(i) || i < 0 || i >= this.#n) throw new RangeError('index');
    let k = 0;
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      if (k++ === i) return (BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l);
    }
  }
  decode() {
    const a = [];
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      const i = a.length;
      a.push((BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l));
    }
    return a;
  }
  lowerBound(q) {
    if (typeof q !== 'bigint') throw new TypeError('bigint');
    let a = 0, b = this.#n;
    while (a < b) {
      const m = a + Math.floor((b - a) / 2);
      if (this.get(m) < q) a = m + 1; else b = m;
    }
    return a;
  }
  bytes() {
    const h = Buffer.alloc(16);
    h.write('EF01'); h.writeUInt32LE(this.#n, 4);
    h.writeUInt32LE(this.#l, 8); h.writeUInt32LE(this.#h, 12);
    return Buffer.concat([h, this.#lo, this.#hi]);
  }
  static from(b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Buffer');
    if (b.length < 16 || b.toString('latin1', 0, 4) !== 'EF01') throw new RangeError('header');
    const n = b.readUInt32LE(4), l = b.readUInt32LE(8), h = b.readUInt32LE(12);
    if (n > MAX_N || l > MAX_L || h < n || h > 3 * n) throw new RangeError('budget');
    const nb = Math.ceil(n * l / 8), hb = Math.ceil(h / 8);
    if (b.length !== 16 + nb + hb) throw new RangeError('length');
    const lo = b.subarray(16, 16 + nb), hi = b.subarray(16 + nb), a = [];
    for (let p = 0; p < h; p++) if (bit(hi, p)) {
      const i = a.length;
      if (i === n) throw new RangeError('ones');
      a.push((BigInt(p - i) << BigInt(l)) | lowAt(lo, i, l));
    }
    if (a.length !== n) throw new RangeError('ones');
    const ef = new EF(a);
    if (!ef.bytes().equals(b)) throw new RangeError('canonical');
    return ef;
  }
}

const ef = new EF([0n, 2n, 7n, 8n, 8n, 21n]);
console.log(ef.length, ef.get(4).toString());
console.log(ef.decode().join(','));
console.log(JSON.stringify(ef.layout()));
const saved = ef.bytes(); saved.fill(0);
console.log(ef.get(5).toString());

输出:

6 8
0,2,7,8,8,21
{"n":6,"l":1,"h":16,"lowBytes":1,"highBytes":2}
21

五、lowerBound 的正确性与真实代价

lowerBound 返回第一个值不小于阈值的位置;若全部更小,返回 n。区间使用左闭右开的 [a,b),相等时移动右边界,所以有重复值时仍返回最左位置。算法不把阈值转换为 Number,也不对阈值做截断或掩码。空数组、负阈值和超过最大值的查询应当沿用同一个契约,而不是依赖异常当控制流。

本例为便于逐项验证,二分过程调用扫描版 get。访问次数为对数级,最坏位访问量却是 O((H+l)·log(n+1)),不能把它写成 O(log n) 的固定成本查询,更不能宣称 Elias–Fano 自动提供常数时间 select。真正的选择索引或高位跳表需要额外结构和额外存储;要优化时,应连同新的索引字节、构建时间和分布敏感性一起评审。这里宁可保留一个慢而明确的基线。

'use strict';
const MAX_N = 4096, MAX_L = 4096;
const bit = (b, p) => (b[Math.floor(p / 8)] >> (p % 8)) & 1;
const set = (b, p) => { b[Math.floor(p / 8)] |= 1 << (p % 8); };
function lowAt(b, i, l) {
  let x = 0n;
  for (let j = l - 1; j >= 0; j--) x = (x << 1n) | BigInt(bit(b, i * l + j));
  return x;
}
function width(a) {
  let q = a.length ? a.at(-1) / BigInt(a.length) : 0n, l = 0;
  while (q > 1n) { q >>= 1n; if (++l > MAX_L) throw new RangeError('budget'); }
  return l;
}
class EF {
  #n; #l; #h; #lo; #hi;
  constructor(a) {
    if (!Array.isArray(a)) throw new TypeError('array');
    if (a.length > MAX_N) throw new RangeError('budget');
    let prev = 0n;
    for (const x of a) {
      if (typeof x !== 'bigint') throw new TypeError('bigint');
      if (x < prev) throw new RangeError('order');
      prev = x;
    }
    this.#n = a.length; this.#l = width(a);
    const l = BigInt(this.#l);
    this.#h = a.length ? Number(a.at(-1) >> l) + a.length : 0;
    this.#lo = Buffer.alloc(Math.ceil(a.length * this.#l / 8));
    this.#hi = Buffer.alloc(Math.ceil(this.#h / 8));
    a.forEach((x, i) => {
      for (let j = 0; j < this.#l; j++) {
        if ((x >> BigInt(j)) & 1n) set(this.#lo, i * this.#l + j);
      }
      set(this.#hi, Number(x >> l) + i);
    });
  }
  get length() { return this.#n; }
  layout() { return { n: this.#n, l: this.#l, h: this.#h,
    lowBytes: this.#lo.length, highBytes: this.#hi.length }; }
  get(i) {
    if (!Number.isInteger(i) || i < 0 || i >= this.#n) throw new RangeError('index');
    let k = 0;
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      if (k++ === i) return (BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l);
    }
  }
  decode() {
    const a = [];
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      const i = a.length;
      a.push((BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l));
    }
    return a;
  }
  lowerBound(q) {
    if (typeof q !== 'bigint') throw new TypeError('bigint');
    let a = 0, b = this.#n;
    while (a < b) {
      const m = a + Math.floor((b - a) / 2);
      if (this.get(m) < q) a = m + 1; else b = m;
    }
    return a;
  }
  bytes() {
    const h = Buffer.alloc(16);
    h.write('EF01'); h.writeUInt32LE(this.#n, 4);
    h.writeUInt32LE(this.#l, 8); h.writeUInt32LE(this.#h, 12);
    return Buffer.concat([h, this.#lo, this.#hi]);
  }
  static from(b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Buffer');
    if (b.length < 16 || b.toString('latin1', 0, 4) !== 'EF01') throw new RangeError('header');
    const n = b.readUInt32LE(4), l = b.readUInt32LE(8), h = b.readUInt32LE(12);
    if (n > MAX_N || l > MAX_L || h < n || h > 3 * n) throw new RangeError('budget');
    const nb = Math.ceil(n * l / 8), hb = Math.ceil(h / 8);
    if (b.length !== 16 + nb + hb) throw new RangeError('length');
    const lo = b.subarray(16, 16 + nb), hi = b.subarray(16 + nb), a = [];
    for (let p = 0; p < h; p++) if (bit(hi, p)) {
      const i = a.length;
      if (i === n) throw new RangeError('ones');
      a.push((BigInt(p - i) << BigInt(l)) | lowAt(lo, i, l));
    }
    if (a.length !== n) throw new RangeError('ones');
    const ef = new EF(a);
    if (!ef.bytes().equals(b)) throw new RangeError('canonical');
    return ef;
  }
}

const ef = new EF([0n, 2n, 7n, 8n, 8n, 21n]);
for (const q of [-1n, 0n, 3n, 8n, 9n, 22n]) {
  console.log(q + ':' + ef.lowerBound(q));
}
console.log('empty:' + new EF([]).lowerBound(0n));

输出:

-1:0
0:0
3:2
8:3
9:5
22:6
empty:0

六、精确记账:逻辑位、载荷字节与对象内存

这份实现有三种不同的大小。逻辑载荷是 n·l+H 位。两个流分别补齐到字节,载荷字节数是 ceil(n·l/8)+ceil(H/8),不能先把两个位数相加再统一取整。文件还要加十六字节头部。对于主例,低位六位、高位十六位,共二十二位;低位补两位,载荷为三字节,最终文件十九字节。

头部依次为四字节 ASCII 标记 EF01,以及三个四字节小端无符号整数 n、l、H。最大值不另存,因为能够从有效载荷恢复。低位流紧随头部,高位流随后;最后一个字节的未用高位必须为零。全零数组仍用 n 个高位一表示重复次数;空数组只有头部。这样的选择让格式简单且唯一,但绝不意味着空数组压缩得比普通空列表更小。

Buffer.length 只精确描述可见缓冲区字节。对象字段、Buffer 包装、分配器对齐、临时数组和 BigInt 实体还会产生运行时开销,甚至可能涉及底层内存池;不能把十九字节说成整个对象的堆内存。相同地,拿六个任意精度 BigInt 与六个八字节整数直接比较并不公平。下例输出的是格式账本,不是堆内存基准,也没有承诺所有输入都会缩小。

'use strict';
function account(a) {
  const n = a.length;
  let q = n ? a.at(-1) / BigInt(n) : 0n, l = 0;
  while (q > 1n) { q >>= 1n; l++; }
  const h = n ? Number(a.at(-1) >> BigInt(l)) + n : 0;
  const bits = n * l + h;
  const payload = Math.ceil(n * l / 8) + Math.ceil(h / 8);
  return { bits, payload, padding: 8 * payload - bits, file: 16 + payload };
}
for (const a of [[], [0n, 0n, 0n], [0n, 2n, 7n, 8n, 8n, 21n]]) {
  console.log(JSON.stringify(account(a)));
}

输出:

{"bits":0,"payload":0,"padding":0,"file":16}
{"bits":3,"payload":1,"padding":5,"file":17}
{"bits":22,"payload":3,"padding":2,"file":19}

七、导入不是信任:拒绝非规范表示

只要能还原相同数值就接受,会使同一逻辑对象拥有许多不同字节串,影响缓存键、签名输入和去重结果。from 因此先检查类型、标记、预算和精确长度,再扫描有效高位,核对一的数量,恢复数值并交给构造器检查非负和单调性。最后重新编码并逐字节比较,这一步同时拒绝非零填充、尾部零、非规范宽度、空数组的非零宽度等可解码但非唯一的表示。

重新编码比较增加了导入成本,却使规范性条件与唯一的写出路径保持一致。它不是校验和,更不是加密认证:攻击者把载荷改成另一个合法序列时,导入理应成功。若文件用于不可信网络输入,应用仍需传输认证、总请求大小限制和合理的请求速率。示例的预算只能约束每次解码规模,不能替代系统级防护。

'use strict';
const MAX_N = 4096, MAX_L = 4096;
const bit = (b, p) => (b[Math.floor(p / 8)] >> (p % 8)) & 1;
const set = (b, p) => { b[Math.floor(p / 8)] |= 1 << (p % 8); };
function lowAt(b, i, l) {
  let x = 0n;
  for (let j = l - 1; j >= 0; j--) x = (x << 1n) | BigInt(bit(b, i * l + j));
  return x;
}
function width(a) {
  let q = a.length ? a.at(-1) / BigInt(a.length) : 0n, l = 0;
  while (q > 1n) { q >>= 1n; if (++l > MAX_L) throw new RangeError('budget'); }
  return l;
}
class EF {
  #n; #l; #h; #lo; #hi;
  constructor(a) {
    if (!Array.isArray(a)) throw new TypeError('array');
    if (a.length > MAX_N) throw new RangeError('budget');
    let prev = 0n;
    for (const x of a) {
      if (typeof x !== 'bigint') throw new TypeError('bigint');
      if (x < prev) throw new RangeError('order');
      prev = x;
    }
    this.#n = a.length; this.#l = width(a);
    const l = BigInt(this.#l);
    this.#h = a.length ? Number(a.at(-1) >> l) + a.length : 0;
    this.#lo = Buffer.alloc(Math.ceil(a.length * this.#l / 8));
    this.#hi = Buffer.alloc(Math.ceil(this.#h / 8));
    a.forEach((x, i) => {
      for (let j = 0; j < this.#l; j++) {
        if ((x >> BigInt(j)) & 1n) set(this.#lo, i * this.#l + j);
      }
      set(this.#hi, Number(x >> l) + i);
    });
  }
  get length() { return this.#n; }
  layout() { return { n: this.#n, l: this.#l, h: this.#h,
    lowBytes: this.#lo.length, highBytes: this.#hi.length }; }
  get(i) {
    if (!Number.isInteger(i) || i < 0 || i >= this.#n) throw new RangeError('index');
    let k = 0;
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      if (k++ === i) return (BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l);
    }
  }
  decode() {
    const a = [];
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      const i = a.length;
      a.push((BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l));
    }
    return a;
  }
  lowerBound(q) {
    if (typeof q !== 'bigint') throw new TypeError('bigint');
    let a = 0, b = this.#n;
    while (a < b) {
      const m = a + Math.floor((b - a) / 2);
      if (this.get(m) < q) a = m + 1; else b = m;
    }
    return a;
  }
  bytes() {
    const h = Buffer.alloc(16);
    h.write('EF01'); h.writeUInt32LE(this.#n, 4);
    h.writeUInt32LE(this.#l, 8); h.writeUInt32LE(this.#h, 12);
    return Buffer.concat([h, this.#lo, this.#hi]);
  }
  static from(b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Buffer');
    if (b.length < 16 || b.toString('latin1', 0, 4) !== 'EF01') throw new RangeError('header');
    const n = b.readUInt32LE(4), l = b.readUInt32LE(8), h = b.readUInt32LE(12);
    if (n > MAX_N || l > MAX_L || h < n || h > 3 * n) throw new RangeError('budget');
    const nb = Math.ceil(n * l / 8), hb = Math.ceil(h / 8);
    if (b.length !== 16 + nb + hb) throw new RangeError('length');
    const lo = b.subarray(16, 16 + nb), hi = b.subarray(16 + nb), a = [];
    for (let p = 0; p < h; p++) if (bit(hi, p)) {
      const i = a.length;
      if (i === n) throw new RangeError('ones');
      a.push((BigInt(p - i) << BigInt(l)) | lowAt(lo, i, l));
    }
    if (a.length !== n) throw new RangeError('ones');
    const ef = new EF(a);
    if (!ef.bytes().equals(b)) throw new RangeError('canonical');
    return ef;
  }
}

const b = new EF([0n, 2n, 7n, 8n, 8n, 21n]).bytes();
console.log(b.toString('hex'));
console.log(EF.from(b).decode().join(','));
const dirtyPadding = Buffer.from(b); dirtyPadding[16] |= 0x80;
const tests = [b.subarray(0, -1), Buffer.concat([b, Buffer.of(0)]), dirtyPadding];
for (const x of tests) {
  try { EF.from(x); } catch (e) { console.log(e.message); }
}

输出:

4546303106000000010000001000000024a581
0,2,7,8,8,21
length
length
canonical

八、穷举验证,别让编码器给自己作证

只测试 encode 后 decode 等于输入还不够:如果二者共享同一处下标错误,错误可能彼此抵消。下面的独立解码器直接读取导出字节,按高位流中零的累计数量恢复商;低位则用算术除法读取,既不调用 get,也不调用实现中的取位函数。查询预期值来自原数组的线性查找,而不是另一个二分版本。

枚举覆盖长度零至七、元素零至七的全部非下降数组,共六千四百三十五个。这包含空、全零、重复、跨字节边界以及多个宽度切换点。每个序列验证逐项 get、一次解码、独立解码、规范导入再导出,以及阈值负一至九的 lowerBound。确定性全枚举不等于证明,也不覆盖资源预算上限,所以还要接着补上大整数与畸形文件测试。

'use strict';
const MAX_N = 4096, MAX_L = 4096;
const bit = (b, p) => (b[Math.floor(p / 8)] >> (p % 8)) & 1;
const set = (b, p) => { b[Math.floor(p / 8)] |= 1 << (p % 8); };
function lowAt(b, i, l) {
  let x = 0n;
  for (let j = l - 1; j >= 0; j--) x = (x << 1n) | BigInt(bit(b, i * l + j));
  return x;
}
function width(a) {
  let q = a.length ? a.at(-1) / BigInt(a.length) : 0n, l = 0;
  while (q > 1n) { q >>= 1n; if (++l > MAX_L) throw new RangeError('budget'); }
  return l;
}
class EF {
  #n; #l; #h; #lo; #hi;
  constructor(a) {
    if (!Array.isArray(a)) throw new TypeError('array');
    if (a.length > MAX_N) throw new RangeError('budget');
    let prev = 0n;
    for (const x of a) {
      if (typeof x !== 'bigint') throw new TypeError('bigint');
      if (x < prev) throw new RangeError('order');
      prev = x;
    }
    this.#n = a.length; this.#l = width(a);
    const l = BigInt(this.#l);
    this.#h = a.length ? Number(a.at(-1) >> l) + a.length : 0;
    this.#lo = Buffer.alloc(Math.ceil(a.length * this.#l / 8));
    this.#hi = Buffer.alloc(Math.ceil(this.#h / 8));
    a.forEach((x, i) => {
      for (let j = 0; j < this.#l; j++) {
        if ((x >> BigInt(j)) & 1n) set(this.#lo, i * this.#l + j);
      }
      set(this.#hi, Number(x >> l) + i);
    });
  }
  get length() { return this.#n; }
  layout() { return { n: this.#n, l: this.#l, h: this.#h,
    lowBytes: this.#lo.length, highBytes: this.#hi.length }; }
  get(i) {
    if (!Number.isInteger(i) || i < 0 || i >= this.#n) throw new RangeError('index');
    let k = 0;
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      if (k++ === i) return (BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l);
    }
  }
  decode() {
    const a = [];
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      const i = a.length;
      a.push((BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l));
    }
    return a;
  }
  lowerBound(q) {
    if (typeof q !== 'bigint') throw new TypeError('bigint');
    let a = 0, b = this.#n;
    while (a < b) {
      const m = a + Math.floor((b - a) / 2);
      if (this.get(m) < q) a = m + 1; else b = m;
    }
    return a;
  }
  bytes() {
    const h = Buffer.alloc(16);
    h.write('EF01'); h.writeUInt32LE(this.#n, 4);
    h.writeUInt32LE(this.#l, 8); h.writeUInt32LE(this.#h, 12);
    return Buffer.concat([h, this.#lo, this.#hi]);
  }
  static from(b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Buffer');
    if (b.length < 16 || b.toString('latin1', 0, 4) !== 'EF01') throw new RangeError('header');
    const n = b.readUInt32LE(4), l = b.readUInt32LE(8), h = b.readUInt32LE(12);
    if (n > MAX_N || l > MAX_L || h < n || h > 3 * n) throw new RangeError('budget');
    const nb = Math.ceil(n * l / 8), hb = Math.ceil(h / 8);
    if (b.length !== 16 + nb + hb) throw new RangeError('length');
    const lo = b.subarray(16, 16 + nb), hi = b.subarray(16 + nb), a = [];
    for (let p = 0; p < h; p++) if (bit(hi, p)) {
      const i = a.length;
      if (i === n) throw new RangeError('ones');
      a.push((BigInt(p - i) << BigInt(l)) | lowAt(lo, i, l));
    }
    if (a.length !== n) throw new RangeError('ones');
    const ef = new EF(a);
    if (!ef.bytes().equals(b)) throw new RangeError('canonical');
    return ef;
  }
}

const assert = require('node:assert/strict');
function independent(b) {
  const n = b.readUInt32LE(4), l = b.readUInt32LE(8), h = b.readUInt32LE(12);
  const offset = 16 + Math.ceil(n * l / 8), out = [];
  let high = 0n;
  for (let p = 0; p < h; p++) {
    const one = Math.floor(b[offset + Math.floor(p / 8)] / 2 ** (p % 8)) % 2;
    if (!one) { high++; continue; }
    let low = 0n, place = 1n;
    for (let j = 0; j < l; j++, place *= 2n) {
      const k = out.length * l + j;
      const v = Math.floor(b[16 + Math.floor(k / 8)] / 2 ** (k % 8)) % 2;
      if (v) low += place;
    }
    out.push(high * (2n ** BigInt(l)) + low);
  }
  return out;
}
let cases = 0, queries = 0;
function visit(a, min) {
  const ef = new EF(a), b = ef.bytes(); cases++;
  assert.deepEqual(ef.decode(), a);
  assert.deepEqual(independent(b), a);
  assert.deepEqual(EF.from(b).bytes(), b);
  a.forEach((x, i) => assert.equal(ef.get(i), x));
  for (let q = -1n; q <= 9n; q++) {
    const i = a.findIndex(x => x >= q);
    assert.equal(ef.lowerBound(q), i < 0 ? a.length : i); queries++;
  }
  if (a.length < 7) for (let x = min; x <= 7; x++) visit([...a, BigInt(x)], x);
}
visit([], 0);
console.log('arrays=' + cases + ' queries=' + queries + ' PASS');

输出:

arrays=6435 queries=70785 PASS

九、极大值、预算边界与故障输入

最后一组把值推到二的四千零九十六次方,并测试大量相同的零。我们检查上限内的实例确实可用,再检查超预算被明确拒绝,避免把边界测试写成只覆盖失败分支。调用方修改原数组或导出的字节,也不应改动已经构造的对象。非法下标、Number 阈值和下降序列均有清晰的异常契约。

文件测试还覆盖高位填充、空文件非规范宽度、低位造成的局部逆序,以及人为使用另一种宽度编码相同值的情形。顺利通过这些例子,只说明这份参考实现满足所列契约;它没有被包装成生产级压缩库。真正落地时,应先测真实数据的分布、读写比例和运行时内存,再决定是否增加选择索引、分块或流式接口。评审 AI 生成的压缩代码,优先检查不变量与拒绝路径,最后才看漂亮的压缩率数字。

'use strict';
const MAX_N = 4096, MAX_L = 4096;
const bit = (b, p) => (b[Math.floor(p / 8)] >> (p % 8)) & 1;
const set = (b, p) => { b[Math.floor(p / 8)] |= 1 << (p % 8); };
function lowAt(b, i, l) {
  let x = 0n;
  for (let j = l - 1; j >= 0; j--) x = (x << 1n) | BigInt(bit(b, i * l + j));
  return x;
}
function width(a) {
  let q = a.length ? a.at(-1) / BigInt(a.length) : 0n, l = 0;
  while (q > 1n) { q >>= 1n; if (++l > MAX_L) throw new RangeError('budget'); }
  return l;
}
class EF {
  #n; #l; #h; #lo; #hi;
  constructor(a) {
    if (!Array.isArray(a)) throw new TypeError('array');
    if (a.length > MAX_N) throw new RangeError('budget');
    let prev = 0n;
    for (const x of a) {
      if (typeof x !== 'bigint') throw new TypeError('bigint');
      if (x < prev) throw new RangeError('order');
      prev = x;
    }
    this.#n = a.length; this.#l = width(a);
    const l = BigInt(this.#l);
    this.#h = a.length ? Number(a.at(-1) >> l) + a.length : 0;
    this.#lo = Buffer.alloc(Math.ceil(a.length * this.#l / 8));
    this.#hi = Buffer.alloc(Math.ceil(this.#h / 8));
    a.forEach((x, i) => {
      for (let j = 0; j < this.#l; j++) {
        if ((x >> BigInt(j)) & 1n) set(this.#lo, i * this.#l + j);
      }
      set(this.#hi, Number(x >> l) + i);
    });
  }
  get length() { return this.#n; }
  layout() { return { n: this.#n, l: this.#l, h: this.#h,
    lowBytes: this.#lo.length, highBytes: this.#hi.length }; }
  get(i) {
    if (!Number.isInteger(i) || i < 0 || i >= this.#n) throw new RangeError('index');
    let k = 0;
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      if (k++ === i) return (BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l);
    }
  }
  decode() {
    const a = [];
    for (let p = 0; p < this.#h; p++) if (bit(this.#hi, p)) {
      const i = a.length;
      a.push((BigInt(p - i) << BigInt(this.#l)) | lowAt(this.#lo, i, this.#l));
    }
    return a;
  }
  lowerBound(q) {
    if (typeof q !== 'bigint') throw new TypeError('bigint');
    let a = 0, b = this.#n;
    while (a < b) {
      const m = a + Math.floor((b - a) / 2);
      if (this.get(m) < q) a = m + 1; else b = m;
    }
    return a;
  }
  bytes() {
    const h = Buffer.alloc(16);
    h.write('EF01'); h.writeUInt32LE(this.#n, 4);
    h.writeUInt32LE(this.#l, 8); h.writeUInt32LE(this.#h, 12);
    return Buffer.concat([h, this.#lo, this.#hi]);
  }
  static from(b) {
    if (!Buffer.isBuffer(b)) throw new TypeError('Buffer');
    if (b.length < 16 || b.toString('latin1', 0, 4) !== 'EF01') throw new RangeError('header');
    const n = b.readUInt32LE(4), l = b.readUInt32LE(8), h = b.readUInt32LE(12);
    if (n > MAX_N || l > MAX_L || h < n || h > 3 * n) throw new RangeError('budget');
    const nb = Math.ceil(n * l / 8), hb = Math.ceil(h / 8);
    if (b.length !== 16 + nb + hb) throw new RangeError('length');
    const lo = b.subarray(16, 16 + nb), hi = b.subarray(16 + nb), a = [];
    for (let p = 0; p < h; p++) if (bit(hi, p)) {
      const i = a.length;
      if (i === n) throw new RangeError('ones');
      a.push((BigInt(p - i) << BigInt(l)) | lowAt(lo, i, l));
    }
    if (a.length !== n) throw new RangeError('ones');
    const ef = new EF(a);
    if (!ef.bytes().equals(b)) throw new RangeError('canonical');
    return ef;
  }
}

const assert = require('node:assert/strict');
const huge = 1n << 4096n;
for (const a of [[], [0n], [huge], [0n, huge, huge], Array(4096).fill(0n)]) {
  const ef = new EF(a);
  assert.deepEqual(EF.from(ef.bytes()).decode(), a);
  for (const q of [-1n, 0n, huge - 1n, huge, huge + 1n]) {
    const i = a.findIndex(x => x >= q);
    assert.equal(ef.lowerBound(q), i < 0 ? a.length : i);
  }
}
const a = [2n, 2n], ef = new EF(a); a[0] = 100n;
assert.equal(ef.get(0), 2n);
let rejected = 0;
function bad(f) { assert.throws(f); rejected++; }
for (const x of [null, [1], [-1n], [2n, 1n], Array(4097).fill(0n), [1n << 4097n]]) bad(() => new EF(x));
for (const i of [-1, 2, 0.5, NaN]) bad(() => ef.get(i));
bad(() => ef.lowerBound(2));
bad(() => EF.from(new Uint8Array(16)));
const pad = new EF([0n, 1n, 4n]).bytes(); pad[16] |= 0x80;
bad(() => EF.from(pad));
const empty = new EF([]).bytes(); empty.writeUInt32LE(1, 8);
bad(() => EF.from(empty));
const reverse = new EF([4n, 5n]).bytes(); reverse[16] = 1;
bad(() => EF.from(reverse));
const otherWidth = Buffer.alloc(18); otherWidth.write('EF01');
otherWidth.writeUInt32LE(2, 4); otherWidth.writeUInt32LE(1, 8);
otherWidth.writeUInt32LE(3, 12); otherWidth[17] = 5;
bad(() => EF.from(otherWidth));
console.log('boundary roundtrips=5 PASS');
console.log('rejections=' + rejected + ' PASS');

输出:

boundary roundtrips=5 PASS
rejections=16 PASS

来源与实现边界

高低位分解和一元高位表示参考 Sebastiano Vigna 的 Quasi-Succinct Indices,第 4 节。本文的十六字节格式、预算、拒绝策略和测试程序均为独立编写,不能与论文实现的性能结果混同。语言语义核对 ECMAScript BigInt 规范;缓冲区创建、小端整数读写与复制行为核对 Node.js Buffer 官方文档。检索与测试日期:2026 年 10 月 19 日。

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