@sofa-buffers/corelib 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
3
  var __defProp = Object.defineProperty;
5
4
  var __export = (target, all) => {
6
5
  for (var name in all)
@@ -13,26 +12,35 @@ __export(public_exports, {
13
12
  API_VERSION: () => API_VERSION,
14
13
  ARRAY_MAX: () => ARRAY_MAX,
15
14
  ArrayKind: () => ArrayKind,
16
- Cursor: () => Cursor,
15
+ BlobSeq: () => BlobSeq,
17
16
  DecodeStatus: () => DecodeStatus,
17
+ ElementSeq: () => ElementSeq,
18
18
  FIXLEN_MAX: () => FIXLEN_MAX,
19
19
  FixlenSubtype: () => FixlenSubtype,
20
+ FramedSeq: () => FramedSeq,
20
21
  I64_MAX: () => I64_MAX,
21
22
  I64_MIN: () => I64_MIN,
22
23
  ID_MAX: () => ID_MAX,
23
24
  IStream: () => IStream,
24
25
  Long: () => Long,
25
26
  MAX_DEPTH: () => MAX_DEPTH,
27
+ MIN_OUTPUT_BUFFER: () => MIN_OUTPUT_BUFFER,
26
28
  OStream: () => OStream,
29
+ PayloadAcc: () => PayloadAcc,
27
30
  SofabError: () => SofabError,
28
31
  SofabErrorCode: () => SofabErrorCode,
32
+ StringSeq: () => StringSeq,
29
33
  U64_MAX: () => U64_MAX,
34
+ UNBOUNDED: () => UNBOUNDED,
30
35
  WireType: () => WireType,
31
36
  decode: () => decode,
37
+ decodeUtf8: () => decodeUtf8,
38
+ elementsEqual: () => elementsEqual,
39
+ fp32RawBytes: () => fp32RawBytes,
32
40
  getKernel: () => getKernel,
41
+ growingOStream: () => growingOStream,
33
42
  jsKernel: () => jsKernel,
34
- loadNativeKernel: () => loadNativeKernel,
35
- loadWasmKernel: () => loadWasmKernel,
43
+ longElementsEqual: () => longElementsEqual,
36
44
  setKernel: () => setKernel
37
45
  });
38
46
 
@@ -83,6 +91,9 @@ var U64_MAX = 0xffffffffffffffffn;
83
91
  var I64_MIN = -0x8000000000000000n;
84
92
  var I64_MAX = 0x7fffffffffffffffn;
85
93
  var VARINT_MAX_BYTES = 10;
94
+ var MIN_OUTPUT_BUFFER = 1;
95
+ var FP32_HANDLE_MIN = 64;
96
+ var FP64_HANDLE_MIN = 16;
86
97
  var MAX_DEPTH = 255;
87
98
  var DecodeStatus = {
88
99
  /** The bytes ended exactly at a field boundary — a valid message. */
@@ -111,7 +122,8 @@ var SofabErrorCode = {
111
122
  /**
112
123
  * A receiver-configured decode limit was exceeded — a dynamic array, string or
113
124
  * blob on the wire claims more elements / bytes than the caller's
114
- * {@link DecodeLimits} (`maxArrayCount` / `maxStringLen` / `maxBlobLen`)
125
+ * receiver cap (`max_dyn_array_count` / `max_dyn_string_len` /
126
+ * `max_dyn_blob_len`, §6.2.1 — stated by generated code, never by this codec)
115
127
  * allows. Deliberately distinct from {@link SofabErrorCode.InvalidMsg}:
116
128
  * exceeding a limit is *policy*, not wire malformation — the identical bytes
117
129
  * decode fine under a looser limit — so differential fuzzing must not read it
@@ -144,6 +156,34 @@ function limitExceededError(message) {
144
156
  return new SofabError(SofabErrorCode.LimitExceeded, message);
145
157
  }
146
158
 
159
+ // src/varint/bits64.ts
160
+ var SCRATCH = new ArrayBuffer(8);
161
+ var S_U64 = new BigUint64Array(SCRATCH);
162
+ var S_I64 = new BigInt64Array(SCRATCH);
163
+ var S_U32 = new Uint32Array(SCRATCH);
164
+ S_U64[0] = 0n;
165
+ S_U32[0] = 1;
166
+ var LO = S_U64[0] === 1n ? 0 : 1;
167
+ var HI = LO ^ 1;
168
+ function splitU64(value) {
169
+ S_U64[0] = value;
170
+ return S_U64[0] === value;
171
+ }
172
+ function splitI64(value) {
173
+ S_I64[0] = value;
174
+ return S_I64[0] === value;
175
+ }
176
+ function joinU64(lo, hi) {
177
+ S_U32[LO] = lo;
178
+ S_U32[HI] = hi;
179
+ return S_U64[0];
180
+ }
181
+ function joinI64(lo, hi) {
182
+ S_U32[LO] = lo;
183
+ S_U32[HI] = hi;
184
+ return S_I64[0];
185
+ }
186
+
147
187
  // src/long.ts
148
188
  var _Long = class _Long {
149
189
  constructor(low, high) {
@@ -154,9 +194,14 @@ var _Long = class _Long {
154
194
  static fromBits(low, high) {
155
195
  return new _Long(low, high);
156
196
  }
157
- /** Split a `bigint` into its low/high 32-bit halves (two's complement). */
197
+ /**
198
+ * Split a `bigint` into its low/high 32-bit halves (two's complement). The
199
+ * `BigInt64Array` store *is* `ToBigInt64` — reduction modulo 2^64 — so an
200
+ * out-of-range value keeps exactly the halves the masks kept (bits64).
201
+ */
158
202
  static fromBigInt(value) {
159
- return new _Long(Number(value & 0xffffffffn) >>> 0, Number(value >> 32n & 0xffffffffn) >>> 0);
203
+ S_I64[0] = value;
204
+ return new _Long(S_U32[LO], S_U32[HI]);
160
205
  }
161
206
  /** From an integer `number` (`|n| < 2^53`); sign handled via `bigint` once. */
162
207
  static fromNumber(n) {
@@ -169,9 +214,7 @@ var _Long = class _Long {
169
214
  }
170
215
  /** Materialise as a `bigint`. `signed` reads the high bit as two's complement. */
171
216
  toBigInt(signed = false) {
172
- let r = BigInt(this.high >>> 0) << 32n | BigInt(this.low >>> 0);
173
- if (signed && (this.high & 2147483648) !== 0) r -= 0x10000000000000000n;
174
- return r;
217
+ return signed ? joinI64(this.low, this.high) : joinU64(this.low, this.high);
175
218
  }
176
219
  /** Decimal string (`signed` interprets the high bit as two's complement). */
177
220
  toString(signed = false) {
@@ -189,50 +232,40 @@ _Long.ZERO = new _Long(0, 0);
189
232
  var Long = _Long;
190
233
 
191
234
  // src/varint/leb128.ts
192
- function varintSize(value) {
193
- let lo = Number(value & 0xffffffffn) >>> 0;
194
- let hi = Number(value >> 32n & 0xffffffffn) >>> 0;
195
- let n = 0;
196
- while (hi !== 0) {
197
- n++;
198
- const next = (lo >>> 7 | hi << 25) >>> 0;
199
- hi >>>= 7;
200
- lo = next;
235
+ function varintSizeLoHi(lo, hi) {
236
+ if (hi === 0) {
237
+ return lo < 128 ? 1 : lo < 16384 ? 2 : lo < 2097152 ? 3 : lo < 268435456 ? 4 : 5;
201
238
  }
202
- while (lo > 127) {
203
- n++;
204
- lo >>>= 7;
205
- }
206
- return n + 1;
207
- }
208
- function encodeVarint(value, out, pos) {
209
- let lo = Number(value & 0xffffffffn) >>> 0;
210
- let hi = Number(value >> 32n & 0xffffffffn) >>> 0;
211
- while (hi !== 0) {
212
- out[pos++] = lo & 127 | 128;
213
- lo = (lo >>> 7 | hi << 25) >>> 0;
214
- hi >>>= 7;
215
- }
216
- while (lo > 127) {
217
- out[pos++] = lo & 127 | 128;
218
- lo >>>= 7;
219
- }
220
- out[pos++] = lo;
221
- return pos;
239
+ const h = hi >>> 3;
240
+ return h === 0 ? 5 : 5 + (h < 128 ? 1 : h < 16384 ? 2 : h < 2097152 ? 3 : h < 268435456 ? 4 : 5);
222
241
  }
223
242
  function encodeVarintLoHi(lo, hi, out, pos) {
224
243
  lo >>>= 0;
225
244
  hi >>>= 0;
226
- while (hi !== 0) {
227
- out[pos++] = lo & 127 | 128;
228
- lo = (lo >>> 7 | hi << 25) >>> 0;
229
- hi >>>= 7;
245
+ if (hi === 0) {
246
+ while (lo > 127) {
247
+ out[pos++] = lo & 127 | 128;
248
+ lo >>>= 7;
249
+ }
250
+ out[pos++] = lo;
251
+ return pos;
252
+ }
253
+ out[pos++] = lo & 127 | 128;
254
+ out[pos++] = lo >>> 7 & 127 | 128;
255
+ out[pos++] = lo >>> 14 & 127 | 128;
256
+ out[pos++] = lo >>> 21 & 127 | 128;
257
+ const b4 = lo >>> 28 | (hi & 7) << 4;
258
+ let h = hi >>> 3;
259
+ if (h === 0) {
260
+ out[pos++] = b4;
261
+ return pos;
230
262
  }
231
- while (lo > 127) {
232
- out[pos++] = lo & 127 | 128;
233
- lo >>>= 7;
263
+ out[pos++] = b4 | 128;
264
+ while (h > 127) {
265
+ out[pos++] = h & 127 | 128;
266
+ h >>>= 7;
234
267
  }
235
- out[pos++] = lo;
268
+ out[pos++] = h;
236
269
  return pos;
237
270
  }
238
271
  function varintSizeNum(value) {
@@ -262,51 +295,78 @@ function encodeVarintNum(value, out, pos) {
262
295
  }
263
296
 
264
297
  // src/varint/num64.ts
265
- var SCRATCH = new DataView(new ArrayBuffer(8));
298
+ var SCRATCH_BUF = new ArrayBuffer(8);
299
+ var SCRATCH2 = new DataView(SCRATCH_BUF);
300
+ var SCRATCH_BYTES = new Uint8Array(SCRATCH_BUF);
301
+ var SCRATCH_U32 = new Uint32Array(SCRATCH_BUF);
302
+ var SCRATCH_F32 = new Float32Array(SCRATCH_BUF, 0, 1);
303
+ var SCRATCH_F64 = new Float64Array(SCRATCH_BUF);
266
304
  function toBigInt(value) {
267
305
  if (typeof value === "bigint") return value;
268
306
  if (!Number.isInteger(value)) {
269
- throw new RangeError(`expected an integer, got ${value}`);
307
+ throw argumentError(`expected an integer, got ${value}`);
270
308
  }
271
309
  return BigInt(value);
272
310
  }
273
- function inU64(value) {
274
- return value >= 0n && value <= U64_MAX;
275
- }
276
- function inI64(value) {
277
- return value >= I64_MIN && value <= I64_MAX;
278
- }
279
311
  function packFp32(out, pos, value) {
280
- SCRATCH.setFloat32(0, value, true);
281
- out[pos] = SCRATCH.getUint8(0);
282
- out[pos + 1] = SCRATCH.getUint8(1);
283
- out[pos + 2] = SCRATCH.getUint8(2);
284
- out[pos + 3] = SCRATCH.getUint8(3);
312
+ SCRATCH2.setFloat32(0, value, true);
313
+ out[pos] = SCRATCH_BYTES[0];
314
+ out[pos + 1] = SCRATCH_BYTES[1];
315
+ out[pos + 2] = SCRATCH_BYTES[2];
316
+ out[pos + 3] = SCRATCH_BYTES[3];
285
317
  return pos + 4;
286
318
  }
287
319
  function packFp64(out, pos, value) {
288
- SCRATCH.setFloat64(0, value, true);
289
- for (let i = 0; i < 8; i++) out[pos + i] = SCRATCH.getUint8(i);
320
+ SCRATCH2.setFloat64(0, value, true);
321
+ out[pos] = SCRATCH_BYTES[0];
322
+ out[pos + 1] = SCRATCH_BYTES[1];
323
+ out[pos + 2] = SCRATCH_BYTES[2];
324
+ out[pos + 3] = SCRATCH_BYTES[3];
325
+ out[pos + 4] = SCRATCH_BYTES[4];
326
+ out[pos + 5] = SCRATCH_BYTES[5];
327
+ out[pos + 6] = SCRATCH_BYTES[6];
328
+ out[pos + 7] = SCRATCH_BYTES[7];
290
329
  return pos + 8;
291
330
  }
292
- function unpackFp32(buf, pos) {
293
- SCRATCH.setUint8(0, buf[pos]);
294
- SCRATCH.setUint8(1, buf[pos + 1]);
295
- SCRATCH.setUint8(2, buf[pos + 2]);
296
- SCRATCH.setUint8(3, buf[pos + 3]);
297
- return SCRATCH.getFloat32(0, true);
331
+ function fp32Bits(value) {
332
+ SCRATCH2.setFloat32(0, value, true);
333
+ return SCRATCH2.getUint32(0, true);
334
+ }
335
+ function fp64BitsLo(value) {
336
+ SCRATCH2.setFloat64(0, value, true);
337
+ return SCRATCH2.getUint32(0, true);
338
+ }
339
+ function fp64BitsHi(value) {
340
+ SCRATCH2.setFloat64(0, value, true);
341
+ return SCRATCH2.getUint32(4, true);
298
342
  }
299
- function unpackFp64(buf, pos) {
300
- for (let i = 0; i < 8; i++) SCRATCH.setUint8(i, buf[pos + i]);
301
- return SCRATCH.getFloat64(0, true);
343
+ function fp32FromBits(bits) {
344
+ SCRATCH_U32[0] = bits;
345
+ return SCRATCH_F32[0];
346
+ }
347
+ function fp32RawBytes(bits) {
348
+ const out = new Uint8Array(4);
349
+ out[0] = bits & 255;
350
+ out[1] = bits >>> 8 & 255;
351
+ out[2] = bits >>> 16 & 255;
352
+ out[3] = bits >>> 24 & 255;
353
+ return out;
354
+ }
355
+ function fp64FromBits(lo, hi) {
356
+ SCRATCH_U32[LO] = lo;
357
+ SCRATCH_U32[HI] = hi;
358
+ return SCRATCH_F64[0];
302
359
  }
303
360
 
304
361
  // src/varint/zigzag.ts
305
- function zigzagEncode(value) {
306
- return (value << 1n ^ value >> 63n) & U64_MAX;
307
- }
308
- function zigzagDecode(value) {
309
- return value >> 1n ^ -(value & 1n);
362
+ function encodeZigzagVarintLoHi(lo, hi, out, pos) {
363
+ const sgn = -(hi >>> 31) >>> 0;
364
+ return encodeVarintLoHi(
365
+ (lo << 1 >>> 0 ^ sgn) >>> 0,
366
+ ((hi << 1 | lo >>> 31) >>> 0 ^ sgn) >>> 0,
367
+ out,
368
+ pos
369
+ );
310
370
  }
311
371
 
312
372
  // src/backend/js.ts
@@ -314,36 +374,161 @@ var SIGNED_FAST_MAX = 4503599627370496;
314
374
  var jsKernel = {
315
375
  name: "js",
316
376
  encodeUnsignedVarints(values, out, pos) {
317
- for (let i = 0; i < values.length; i++) {
377
+ const n = values.length;
378
+ const ctor = values.constructor;
379
+ if (ctor === BigUint64Array) {
380
+ const a = values;
381
+ const h = new Uint32Array(a.buffer, a.byteOffset, a.length * 2);
382
+ for (let i = 0; i < n; i++) {
383
+ pos = encodeVarintLoHi(h[i * 2 + LO], h[i * 2 + HI], out, pos);
384
+ }
385
+ return pos;
386
+ }
387
+ if (ctor === Uint8Array || ctor === Uint16Array || ctor === Uint32Array) {
388
+ const a = values;
389
+ for (let i = 0; i < n; i++) {
390
+ let v = a[i];
391
+ while (v > 127) {
392
+ out[pos++] = v & 127 | 128;
393
+ v >>>= 7;
394
+ }
395
+ out[pos++] = v;
396
+ }
397
+ return pos;
398
+ }
399
+ for (let i = 0; i < n; i++) {
318
400
  const v = values[i];
319
401
  if (typeof v === "number" && v >= 0 && v <= Number.MAX_SAFE_INTEGER && Number.isInteger(v)) {
320
402
  pos = encodeVarintNum(v, out, pos);
321
- } else {
322
- pos = encodeVarint(toBigInt(v), out, pos);
403
+ continue;
404
+ }
405
+ const b = toBigInt(v);
406
+ if (!splitU64(b)) throw argumentError(`unsigned value ${b} out of range`);
407
+ let lo = S_U32[LO];
408
+ const hi = S_U32[HI];
409
+ if (hi === 0) {
410
+ while (lo > 127) {
411
+ out[pos++] = lo & 127 | 128;
412
+ lo >>>= 7;
413
+ }
414
+ out[pos++] = lo;
415
+ continue;
323
416
  }
417
+ out[pos++] = lo & 127 | 128;
418
+ out[pos++] = lo >>> 7 & 127 | 128;
419
+ out[pos++] = lo >>> 14 & 127 | 128;
420
+ out[pos++] = lo >>> 21 & 127 | 128;
421
+ const b4 = lo >>> 28 | (hi & 7) << 4;
422
+ let h = hi >>> 3;
423
+ if (h === 0) {
424
+ out[pos++] = b4;
425
+ continue;
426
+ }
427
+ out[pos++] = b4 | 128;
428
+ while (h > 127) {
429
+ out[pos++] = h & 127 | 128;
430
+ h >>>= 7;
431
+ }
432
+ out[pos++] = h;
324
433
  }
325
434
  return pos;
326
435
  },
327
436
  encodeSignedVarints(values, out, pos) {
437
+ const ctorS = values.constructor;
438
+ if (ctorS === BigInt64Array) {
439
+ const a = values;
440
+ const h = new Uint32Array(a.buffer, a.byteOffset, a.length * 2);
441
+ for (let i = 0; i < a.length; i++) {
442
+ pos = encodeZigzagVarintLoHi(h[i * 2 + LO], h[i * 2 + HI], out, pos);
443
+ }
444
+ return pos;
445
+ }
446
+ if (ctorS === Int8Array || ctorS === Int16Array || ctorS === Int32Array) {
447
+ const a = values;
448
+ const n = a.length;
449
+ for (let i = 0; i < n; i++) {
450
+ const x = a[i];
451
+ let z = (x << 1 ^ x >> 31) >>> 0;
452
+ while (z > 127) {
453
+ out[pos++] = z & 127 | 128;
454
+ z >>>= 7;
455
+ }
456
+ out[pos++] = z;
457
+ }
458
+ return pos;
459
+ }
328
460
  for (let i = 0; i < values.length; i++) {
329
461
  const v = values[i];
330
462
  if (typeof v === "number" && v >= -SIGNED_FAST_MAX && v <= SIGNED_FAST_MAX && Number.isInteger(v)) {
331
463
  pos = encodeVarintNum(v >= 0 ? v * 2 : -v * 2 - 1, out, pos);
332
464
  } else {
333
- pos = encodeVarint(zigzagEncode(toBigInt(v)), out, pos);
465
+ const b = toBigInt(v);
466
+ if (!splitI64(b)) throw argumentError(`signed value ${b} out of range`);
467
+ pos = encodeZigzagVarintLoHi(S_U32[LO], S_U32[HI], out, pos);
334
468
  }
335
469
  }
336
470
  return pos;
337
471
  },
472
+ // Both float packers take one `DataView` over the destination *once the run is
473
+ // long enough to pay for it* — the language-forced handle of CORELIB_PLAN §6.6.2,
474
+ // and the only way to place an IEEE-754 value at a byte offset. It carries no
475
+ // message bytes (the storage is the caller's) and no wire number sizes it.
476
+ //
477
+ // The threshold is arithmetic, not taste. Measured on Node 24:
478
+ // `new DataView(buf.buffer, off, len)` costs **129 ns**, while the handle saves
479
+ // 1.9 ns per `fp32` (4.11 -> 2.23) and 7.3 ns per `fp64` (10.48 -> 3.20). So it
480
+ // breaks even at ~68 `fp32` and ~18 `fp64` elements; below that the scratch route
481
+ // wins, and a two-element array through a handle is a pessimisation.
338
482
  packFp32Array(values, out, pos) {
339
- for (let i = 0; i < values.length; i++) {
340
- pos = packFp32(out, pos, values[i]);
483
+ const n = values.length;
484
+ if (values instanceof Float32Array) {
485
+ if (n < FP32_HANDLE_MIN) {
486
+ let w2 = null;
487
+ for (let i = 0; i < n; i++) {
488
+ const v = values[i];
489
+ if (v === v) {
490
+ pos = packFp32(out, pos, v);
491
+ continue;
492
+ }
493
+ if (w2 === null) w2 = new Uint32Array(values.buffer, values.byteOffset, n);
494
+ const x = w2[i];
495
+ out[pos] = x;
496
+ out[pos + 1] = x >>> 8;
497
+ out[pos + 2] = x >>> 16;
498
+ out[pos + 3] = x >>> 24;
499
+ pos += 4;
500
+ }
501
+ return pos;
502
+ }
503
+ const w = new Uint32Array(values.buffer, values.byteOffset, n);
504
+ const dv2 = new DataView(out.buffer, out.byteOffset, out.byteLength);
505
+ for (let i = 0; i < n; i++) {
506
+ dv2.setUint32(pos, w[i], true);
507
+ pos += 4;
508
+ }
509
+ return pos;
510
+ }
511
+ if (n < FP32_HANDLE_MIN) {
512
+ for (let i = 0; i < n; i++) pos = packFp32(out, pos, values[i]);
513
+ return pos;
514
+ }
515
+ const dv = new DataView(out.buffer, out.byteOffset, out.byteLength);
516
+ for (let i = 0; i < n; i++) {
517
+ dv.setFloat32(pos, values[i], true);
518
+ pos += 4;
341
519
  }
342
520
  return pos;
343
521
  },
344
522
  packFp64Array(values, out, pos) {
345
- for (let i = 0; i < values.length; i++) {
346
- pos = packFp64(out, pos, values[i]);
523
+ const n = values.length;
524
+ if (n < FP64_HANDLE_MIN) {
525
+ for (let i = 0; i < n; i++) pos = packFp64(out, pos, values[i]);
526
+ return pos;
527
+ }
528
+ const dv = new DataView(out.buffer, out.byteOffset, out.byteLength);
529
+ for (let i = 0; i < n; i++) {
530
+ dv.setFloat64(pos, values[i], true);
531
+ pos += 8;
347
532
  }
348
533
  return pos;
349
534
  }
@@ -373,19 +558,18 @@ function validateKernel(kernel) {
373
558
  }
374
559
 
375
560
  // src/encode/fixlen.ts
376
- var UTF8 = new TextEncoder();
377
561
  function unpairedSurrogate(index) {
378
562
  return argumentError(
379
563
  `unpaired surrogate at index ${index}: string value is not valid UTF-8`
380
564
  );
381
565
  }
382
- function encodeUtf8(text) {
383
- utf8Length(text);
384
- return UTF8.encode(text);
385
- }
386
566
  function utf8Length(text) {
387
- let len = 0;
388
- for (let i = 0; i < text.length; i++) {
567
+ const n = text.length;
568
+ let a = 0;
569
+ while (a < n && text.charCodeAt(a) < 128) a++;
570
+ if (a === n) return n;
571
+ let len = a;
572
+ for (let i = a; i < n; i++) {
389
573
  const c = text.charCodeAt(i);
390
574
  if (c < 128) {
391
575
  len += 1;
@@ -408,7 +592,17 @@ function utf8Length(text) {
408
592
  return len;
409
593
  }
410
594
  function utf8Write(text, out, pos) {
411
- for (let i = 0; i < text.length; i++) {
595
+ const n = text.length;
596
+ let a = 0;
597
+ while (a < n) {
598
+ const c = text.charCodeAt(a);
599
+ if (c >= 128) break;
600
+ out[pos + a] = c;
601
+ a++;
602
+ }
603
+ pos += a;
604
+ if (a === n) return pos;
605
+ for (let i = a; i < n; i++) {
412
606
  let c = text.charCodeAt(i);
413
607
  if (c < 128) {
414
608
  out[pos++] = c;
@@ -437,68 +631,139 @@ function utf8Write(text, out, pos) {
437
631
  }
438
632
  return pos;
439
633
  }
634
+ function utf8WriteSink(text, sink) {
635
+ const n = text.length;
636
+ for (let i = 0; i < n; i++) {
637
+ let c = text.charCodeAt(i);
638
+ if (c < 128) {
639
+ sink.putByte(c);
640
+ } else if (c < 2048) {
641
+ sink.putByte(192 | c >> 6);
642
+ sink.putByte(128 | c & 63);
643
+ } else if (c >= 55296 && c <= 56319) {
644
+ const c2 = i + 1 < n ? text.charCodeAt(i + 1) : 0;
645
+ if (c2 >= 56320 && c2 <= 57343) {
646
+ i++;
647
+ c = 65536 + (c - 55296 << 10) + (c2 - 56320);
648
+ sink.putByte(240 | c >> 18);
649
+ sink.putByte(128 | c >> 12 & 63);
650
+ sink.putByte(128 | c >> 6 & 63);
651
+ sink.putByte(128 | c & 63);
652
+ } else {
653
+ throw unpairedSurrogate(i);
654
+ }
655
+ } else if (c >= 56320 && c <= 57343) {
656
+ throw unpairedSurrogate(i);
657
+ } else {
658
+ sink.putByte(224 | c >> 12);
659
+ sink.putByte(128 | c >> 6 & 63);
660
+ sink.putByte(128 | c & 63);
661
+ }
662
+ }
663
+ }
440
664
 
441
665
  // src/encode/ostream.ts
442
- var DEFAULT_CAPACITY = 256;
443
666
  var SIGNED_FAST_MAX2 = 4503599627370496;
667
+ function checkHandover(buffer, offset, streaming, carried) {
668
+ if (offset < 0 || offset > buffer.length) {
669
+ throw argumentError(`offset ${offset} out of range`);
670
+ }
671
+ if (!Number.isInteger(carried) || carried < 0 || carried > offset) {
672
+ throw argumentError(`carried ${carried} out of range 0..${offset}`);
673
+ }
674
+ if (streaming && buffer.length - offset < MIN_OUTPUT_BUFFER) {
675
+ throw argumentError(
676
+ `output buffer with a flush sink has ${buffer.length - offset} usable byte(s), below MIN_OUTPUT_BUFFER (${MIN_OUTPUT_BUFFER})`
677
+ );
678
+ }
679
+ }
444
680
  var OStream = class {
681
+ /**
682
+ * Encoder over a caller buffer, optionally draining to `flush` as it fills.
683
+ *
684
+ * Those are the only two buffer models there are (CORELIB_PLAN §5.1.1): the
685
+ * buffer the caller hands over, and whatever a sink installs in its place
686
+ * (§5.1.5). There is no third parameter through which the encoder could be
687
+ * given something to enlarge — growing a destination from a write path is what
688
+ * §6.6's second violation row names, whoever owns the allocator.
689
+ *
690
+ * Constructing one is the only allocating step (§6.6): it sizes the hold-back
691
+ * run from `MAX_DEPTH` and reads the active kernel once. No `write*` call after
692
+ * that allocates anything.
693
+ */
445
694
  constructor(buffer, offset = 0, flush) {
446
695
  this.depth = 0;
447
- /**
448
- * Ids of the innermost open sequences whose header has not been written yet
449
- * (MESSAGE_SPEC §2 lazy framing, {@link OStream.writeSequenceBeginLazy}).
450
- * Always a contiguous suffix of the open sequences: writing any field commits
451
- * the whole run at once, so {@link OStream.writeSequenceEnd} can drop the
452
- * innermost one by dropping the last entry. Held-back ids are encoder state,
453
- * never buffer content, so a flush can never split a run.
454
- *
455
- * Storage plus an explicit count rather than `push`/`pop`, so the slots are
456
- * reused across messages (no allocation on a pooled encoder) and so
457
- * {@link OStream.commitPending} can zero the count *before* it writes.
458
- *
459
- * The array grows on demand and is bounded only by `MAX_DEPTH` — there is no
460
- * fixed hold-back window and hence no eager-framing fallback, which is what
461
- * CORELIB_PLAN §6 ("How deep the hold-back reaches") demands of an
462
- * implementation that can allocate: canonical output at *every* depth.
463
- */
464
- this.pending = [];
465
696
  /** Valid entries in {@link OStream.pending}. */
466
697
  this.nPending = 0;
698
+ /**
699
+ * How many buffer installations {@link OStream.setBuffer} has made. Only ever
700
+ * compared for equality across the flush callback, which is how
701
+ * {@link OStream.flush} tells "the sink copied and returned" from "the sink
702
+ * took the buffer and installed a replacement" — the one distinction §5.1
703
+ * rests the handover contract on, and the one that decides whether the start
704
+ * offset was consumed or re-armed.
705
+ */
706
+ this.installs = 0;
467
707
  this.kernel = getKernel();
468
- if (buffer === void 0) {
469
- this.buf = new Uint8Array(DEFAULT_CAPACITY);
470
- this.start = 0;
471
- this.pos = 0;
472
- this.flushSink = void 0;
473
- this.canGrow = true;
474
- } else {
475
- if (offset < 0 || offset > buffer.length) {
476
- throw argumentError(`offset ${offset} out of range`);
477
- }
478
- this.buf = buffer;
479
- this.start = offset;
480
- this.pos = offset;
481
- this.flushSink = flush;
482
- this.canGrow = false;
483
- }
708
+ this.pending = new Array(MAX_DEPTH);
709
+ checkHandover(buffer, offset, flush !== void 0, 0);
710
+ this.buf = buffer;
711
+ this.start = offset;
712
+ this.origin = offset;
713
+ this.pos = offset;
714
+ this.flushSink = flush;
484
715
  }
485
- /** Bytes currently held in the buffer (since construction or the last flush). */
716
+ /** Bytes of the message currently held in the buffer (see {@link bytes}). */
486
717
  get bytesUsed() {
487
- return this.pos - this.start;
718
+ return this.pos - this.origin;
488
719
  }
489
720
  /**
490
- * The encoded message so far, as a view into the working buffer.
491
- * Meaningful for the in-memory mode; in streaming mode it is only the
492
- * not-yet-flushed tail. The view is valid until the next write.
721
+ * The encoded message so far, as a view into the working buffer: everything
722
+ * written since construction, the last {@link reset}, or the last flush the
723
+ * sink returned from without installing a buffer. With a flush sink that is
724
+ * normally only the not-yet-flushed tail; on a stream whose sink hands back a
725
+ * replacement carrying the earlier bytes — the accumulator `growingOStream`
726
+ * builds — it is the whole message. The view is valid until the next write.
493
727
  */
494
728
  bytes() {
495
- return this.buf.subarray(this.start, this.pos);
729
+ return this.buf.subarray(this.origin, this.pos);
496
730
  }
497
- /** Drain buffered bytes to the flush sink (no-op without one). */
731
+ /**
732
+ * Drain buffered bytes to the flush sink (no-op without one).
733
+ *
734
+ * A sink that returns **without** installing a buffer has copied what it was
735
+ * handed, so the encoder keeps writing into the same buffer — resuming at
736
+ * offset **0**. The start offset belongs to the *installation*, not to the
737
+ * buffer (CORELIB_PLAN §5.1): the buffer-set that armed it — the constructor
738
+ * or {@link OStream.setBuffer} — reserved room in the unit it began, and
739
+ * handing that unit over consumes the reservation. A sink that wants header
740
+ * room in *every* unit re-arms it by calling `setBuffer(buf, offset)` from
741
+ * inside the callback, a new installation like any other; a bare return must
742
+ * not do it implicitly, or the leading bytes would be capacity the rest of the
743
+ * stream could never use and the two shapes would be indistinguishable.
744
+ */
498
745
  flush() {
746
+ this.drain(0);
747
+ }
748
+ /**
749
+ * {@link flush}, plus the number of contiguous bytes the caller wants at the
750
+ * cursor afterwards — `0` when it wants none in particular.
751
+ *
752
+ * Split out from the public `flush` so the figure cannot be invented by a
753
+ * caller: it is the encoder's own reserve request, and a sink that sizes a
754
+ * replacement from it (`growingOStream`) has to be able to trust it. Everything
755
+ * else is identical, including that a sink which returns without installing has
756
+ * *copied* and the cursor resumes at `0`.
757
+ */
758
+ drain(needed) {
499
759
  if (this.flushSink && this.pos > this.start) {
500
- this.flushSink(this.buf.subarray(this.start, this.pos));
501
- this.pos = this.start;
760
+ const installed = this.installs;
761
+ this.flushSink(this.buf, this.start, this.pos, needed);
762
+ if (this.installs === installed) {
763
+ this.start = 0;
764
+ this.origin = 0;
765
+ this.pos = 0;
766
+ }
502
767
  }
503
768
  }
504
769
  /**
@@ -508,14 +773,42 @@ var OStream = class {
508
773
  * without interruption. `offset` reserves space at the front of the new
509
774
  * buffer. Any not-yet-flushed bytes in the old buffer are dropped, so
510
775
  * {@link flush} first (the flush callback fires before you swap).
776
+ *
777
+ * Every call is a **new installation**, and its `offset` applies to the unit
778
+ * it begins and is consumed when that unit is flushed (CORELIB_PLAN §5.1).
779
+ * Passing the buffer the encoder already has is an installation like any
780
+ * other: that is how a sink gets header room in *every* flushed unit — one
781
+ * framing header per packet — where returning bare would resume at `0`.
782
+ *
783
+ * On a stream that has a flush sink the new buffer must leave at least
784
+ * {@link MIN_OUTPUT_BUFFER} usable bytes (`buffer.length - offset`); a smaller
785
+ * one is rejected here, with {@link SofabErrorCode.Argument}, leaving the
786
+ * encoder on the buffer it already had. A sink-less stream has no minimum.
787
+ *
788
+ * `carried` says how many bytes **immediately before `offset`** the
789
+ * replacement already holds of *this* message — normally `0`, because a fresh
790
+ * buffer holds none. A caller that keeps the whole message in one growing
791
+ * store passes the length it copied across, so {@link bytes} keeps reporting
792
+ * the message rather than only the piece written after the swap. It changes
793
+ * nothing on the wire and nothing about flushing: the next flush still begins
794
+ * at `offset`. `growingOStream` is the caller this exists for; it is the
795
+ * §5.1.5 handover, not a growth hook inside the encoder (§6.6).
796
+ *
797
+ * The accumulating stream `growingOStream` builds is an ordinary streaming
798
+ * stream, so this works on it too, and means exactly what it means anywhere
799
+ * else: the not-yet-flushed bytes in the old buffer are dropped, encoding
800
+ * continues into yours, and its sink takes over growing *that* one from the
801
+ * next flush — reserve offset included, since what it copies out is the
802
+ * message rather than the buffer. Encode into a plain
803
+ * `new OStream(buffer, offset, flush?)` to keep the buffer yours instead.
511
804
  */
512
- setBuffer(buffer, offset = 0) {
513
- if (offset < 0 || offset > buffer.length) {
514
- throw argumentError(`offset ${offset} out of range`);
515
- }
805
+ setBuffer(buffer, offset = 0, carried = 0) {
806
+ checkHandover(buffer, offset, this.flushSink !== void 0, carried);
516
807
  this.buf = buffer;
517
808
  this.start = offset;
809
+ this.origin = offset - carried;
518
810
  this.pos = offset;
811
+ this.installs++;
519
812
  }
520
813
  /**
521
814
  * Rewind the encoder to empty, reusing the existing buffer. Lets a caller pool
@@ -523,7 +816,8 @@ var OStream = class {
523
816
  * encode. Any view previously returned by {@link bytes} is invalidated.
524
817
  */
525
818
  reset() {
526
- this.pos = this.start;
819
+ this.pos = this.origin;
820
+ this.start = this.origin;
527
821
  this.depth = 0;
528
822
  this.nPending = 0;
529
823
  }
@@ -536,9 +830,11 @@ var OStream = class {
536
830
  return;
537
831
  }
538
832
  const v = toBigInt(value);
539
- if (!inU64(v)) throw argumentError(`unsigned value ${v} out of 64-bit range`);
833
+ if (!splitU64(v)) throw argumentError(`unsigned value ${v} out of 64-bit range`);
834
+ const lo = S_U32[LO];
835
+ const hi = S_U32[HI];
540
836
  this.header(id, WireType.Unsigned);
541
- this.putVarint(v);
837
+ this.putVarintLoHi(lo, hi);
542
838
  }
543
839
  /** Write a signed integer field (zig-zag encoded). */
544
840
  writeSigned(id, value) {
@@ -548,9 +844,44 @@ var OStream = class {
548
844
  return;
549
845
  }
550
846
  const v = toBigInt(value);
551
- if (!inI64(v)) throw argumentError(`signed value ${v} out of 64-bit range`);
847
+ if (!splitI64(v)) throw argumentError(`signed value ${v} out of 64-bit range`);
848
+ const lo = S_U32[LO];
849
+ const hi = S_U32[HI];
850
+ const sgn = -(hi >>> 31) >>> 0;
851
+ const zLo = (lo << 1 >>> 0 ^ sgn) >>> 0;
852
+ const zHi = ((hi << 1 | lo >>> 31) >>> 0 ^ sgn) >>> 0;
853
+ this.header(id, WireType.Signed);
854
+ this.putVarintLoHi(zLo, zHi);
855
+ }
856
+ /**
857
+ * Write an unsigned 64-bit scalar from a {@link Long} — the `bigint`-free twin
858
+ * of {@link writeUnsigned}, and the scalar counterpart of
859
+ * {@link writeUnsignedArrayLong}. Produces the identical wire.
860
+ *
861
+ * There is no range check and no scratch round-trip: a `Long` *is* two 32-bit
862
+ * halves, so it is in the `uint64` domain by construction — which is the whole
863
+ * of what `splitU64` decides for a `number | bigint`. The halves go straight
864
+ * into the varint writer, so nothing is allocated per value. Nothing needs
865
+ * copying out ahead of `header` either, for the same reason the array writers
866
+ * do not: the halves come off a caller-owned immutable `Long`, not the shared
867
+ * scratch a re-entrant flush sink could overwrite.
868
+ */
869
+ writeUnsignedLong(id, value) {
870
+ this.header(id, WireType.Unsigned);
871
+ this.putVarintLoHi(value.low, value.high);
872
+ }
873
+ /**
874
+ * Write a signed 64-bit scalar (zig-zag) from a {@link Long} — the
875
+ * `bigint`-free twin of {@link writeSigned}, and the scalar counterpart of
876
+ * {@link writeSignedArrayLong}. Zig-zag `(n << 1) ^ (n >> 63)` is computed on
877
+ * the lo/hi pair, so the varint goes out at its exact size (a fixed caller
878
+ * buffer must not see a 10-byte demand for a 2-byte field) and no `bigint` is
879
+ * created. A `Long` carries exactly 64 bits, so as in {@link writeUnsignedLong}
880
+ * there is nothing left to range-check.
881
+ */
882
+ writeSignedLong(id, value) {
552
883
  this.header(id, WireType.Signed);
553
- this.putVarint(zigzagEncode(v));
884
+ this.putZigzagVarintLoHi(value.low, value.high);
554
885
  }
555
886
  /** Write a boolean field (encoded as the unsigned value 0 or 1). */
556
887
  writeBoolean(id, value) {
@@ -560,69 +891,161 @@ var OStream = class {
560
891
  /** Write an IEEE-754 32-bit float field. */
561
892
  writeFp32(id, value) {
562
893
  this.fixlenHead(id, 4, FixlenSubtype.Fp32);
563
- this.ensure(4);
564
- this.pos = packFp32(this.buf, this.pos, value);
894
+ this.putFp32(value);
895
+ }
896
+ /**
897
+ * Write an fp32 field from its raw wire bits — the 4 little-endian payload
898
+ * bytes as one 32-bit word, which is exactly what {@link Visitor.fp32} delivers
899
+ * as `bits`.
900
+ *
901
+ * This is the re-encode half of the bit-exactness rule (CORELIB_PLAN §6.5). A JS
902
+ * `number` is a 64-bit double, and widening an fp32 **signaling** NaN into one
903
+ * quiets it, so re-encoding through {@link writeFp32} cannot reproduce such a
904
+ * payload; the bits go out verbatim here, so decode → re-encode is byte-for-byte
905
+ * for every fp32 value, sNaN included. §6.5 requires this path of every
906
+ * double-only target, and names it: "a 32-bit bits accessor".
907
+ */
908
+ writeFp32Bits(id, bits) {
909
+ this.fixlenHead(id, 4, FixlenSubtype.Fp32);
910
+ this.putFp32Bits(bits >>> 0);
565
911
  }
566
912
  /** Write an IEEE-754 64-bit double field. */
567
913
  writeFp64(id, value) {
568
914
  this.fixlenHead(id, 8, FixlenSubtype.Fp64);
569
- this.ensure(8);
570
- this.pos = packFp64(this.buf, this.pos, value);
915
+ this.putFp64(value);
571
916
  }
572
917
  /** Write a UTF-8 string field. */
573
918
  writeString(id, text) {
574
- if (this.canGrow) {
575
- const byteLen = utf8Length(text);
576
- if (byteLen > FIXLEN_MAX) {
577
- throw argumentError(`fixlen length ${byteLen} exceeds ${FIXLEN_MAX}`);
919
+ const n = text.length;
920
+ let a = 0;
921
+ while (a < n && text.charCodeAt(a) < 128) a++;
922
+ if (a === n) {
923
+ if (n > FIXLEN_MAX) {
924
+ throw argumentError(`fixlen length ${n} exceeds ${FIXLEN_MAX}`);
925
+ }
926
+ this.fixlenHead(id, n, FixlenSubtype.String);
927
+ if (this.reserveBulk(n)) {
928
+ const buf = this.buf;
929
+ const p = this.pos;
930
+ for (let k = 0; k < n; k++) buf[p + k] = text.charCodeAt(k);
931
+ this.pos = p + n;
932
+ return;
578
933
  }
579
- this.fixlenHead(id, byteLen, FixlenSubtype.String);
580
- this.ensure(byteLen);
934
+ utf8WriteSink(text, this);
935
+ return;
936
+ }
937
+ const byteLen = utf8Length(text);
938
+ if (byteLen > FIXLEN_MAX) {
939
+ throw argumentError(`fixlen length ${byteLen} exceeds ${FIXLEN_MAX}`);
940
+ }
941
+ this.fixlenHead(id, byteLen, FixlenSubtype.String);
942
+ if (this.reserveBulk(byteLen)) {
581
943
  this.pos = utf8Write(text, this.buf, this.pos);
582
944
  return;
583
945
  }
584
- this.writeFixlen(id, encodeUtf8(text), FixlenSubtype.String);
946
+ utf8WriteSink(text, this);
585
947
  }
586
948
  /** Write a blob (arbitrary bytes) field. */
587
949
  writeBlob(id, data) {
588
950
  this.writeFixlen(id, data, FixlenSubtype.Blob);
589
951
  }
590
- /** Write a fixed-length field of the given subtype from raw bytes. */
952
+ /**
953
+ * Write a fixed-length field of the given subtype from raw bytes.
954
+ *
955
+ * This is the byte-level entry point — the one writer that takes the subtype
956
+ * from the caller rather than picking it — so the payload is checked
957
+ * **against that subtype** before a byte is written, and it cannot emit a
958
+ * `fixlen_word` a conformant decoder must reject (`ARGUMENT`, §6.3):
959
+ *
960
+ * * subtypes `0x4`–`0x7` are **reserved** — a decoder must treat a field
961
+ * carrying one as malformed (`INVALID`, §4.6/§5.2);
962
+ * * `Fp32` / `Fp64` payloads are **exactly** 4 / 8 bytes — any other declared
963
+ * length for those subtypes is malformed, rejected the moment the word is
964
+ * read (§4.6);
965
+ * * `String` / `Blob` take any length up to `FIXLEN_MAX`.
966
+ *
967
+ * The typed writers ({@link writeFp32}, {@link writeFp64},
968
+ * {@link writeString}) are correct by construction and go straight to the
969
+ * header; only {@link writeBlob}, whose subtype is unconstrained anyway,
970
+ * shares this path.
971
+ */
591
972
  writeFixlen(id, data, subtype) {
592
- if (data.length > FIXLEN_MAX) {
973
+ if (subtype >>> 0 > FixlenSubtype.Blob || !Number.isInteger(subtype)) {
974
+ throw argumentError(`fixlen subtype ${subtype} is reserved (\xA74.6: 0x0..0x3)`);
975
+ }
976
+ if (subtype === FixlenSubtype.Fp32 || subtype === FixlenSubtype.Fp64) {
977
+ const want = subtype === FixlenSubtype.Fp32 ? 4 : 8;
978
+ if (data.length !== want) {
979
+ throw argumentError(
980
+ `fixlen ${subtype === FixlenSubtype.Fp32 ? "fp32" : "fp64"} payload must be exactly ${want} bytes, got ${data.length}`
981
+ );
982
+ }
983
+ } else if (data.length > FIXLEN_MAX) {
593
984
  throw argumentError(`fixlen length ${data.length} exceeds ${FIXLEN_MAX}`);
594
985
  }
595
986
  this.fixlenHead(id, data.length, subtype);
596
987
  this.writeRaw(data);
597
988
  }
598
989
  // --- arrays -------------------------------------------------------------
599
- /** Write an array of unsigned integers (each a varint). */
990
+ /**
991
+ * Write an array of unsigned integers (each a varint).
992
+ *
993
+ * **The bulk kernel writes a whole array in one pass and cannot flush**, so it
994
+ * runs only where everything is known to fit. Three cases, and none of them
995
+ * asks the source how wide its elements are:
996
+ *
997
+ * * **block mode** (no sink) — the buffer is meant to hold the whole message,
998
+ * so the kernel always runs and the buffer's length is the bound, checked
999
+ * after the fact. A message that does not fit is `BUFFER_FULL`, which is
1000
+ * precisely this mode's answer.
1001
+ * * **a stream with room** — `VARINT_MAX_BYTES` per element is the true
1002
+ * worst case for any 64-bit value, and a *growing* stream always satisfies
1003
+ * it because it grows to whatever is asked.
1004
+ * * **a chunk too small for that** — fill it to the last byte, hand it over,
1005
+ * carry on, splitting an element where it falls. That is not a fallback but
1006
+ * the mode's contract: `MIN_OUTPUT_BUFFER` is 1.
1007
+ *
1008
+ * What is gone is the fourth case, which asked `values.constructor` for a
1009
+ * narrower bound so the kernel would run on a tightly-sized chunk. `constructor`
1010
+ * is an ordinary property, an `ArrayLike` can claim any width, and a wrong
1011
+ * answer silently truncated the message — §5.1's "partial output handed back as
1012
+ * complete". The block mode now reaches the kernel without needing the number
1013
+ * at all, which is where a tightly-sized buffer actually lives.
1014
+ */
600
1015
  writeUnsignedArray(id, values) {
601
1016
  this.arrayHead(id, WireType.ArrayUnsigned, values.length);
602
- if (this.canGrow) {
603
- this.ensure(values.length * VARINT_MAX_BYTES);
1017
+ if (this.flushSink === void 0) {
1018
+ this.pos = this.bulkEnd(
1019
+ this.kernel.encodeUnsignedVarints(values, this.buf, this.pos),
1020
+ values.length
1021
+ );
1022
+ } else if (this.reserveBulk(values.length * VARINT_MAX_BYTES)) {
604
1023
  this.pos = this.kernel.encodeUnsignedVarints(values, this.buf, this.pos);
605
1024
  } else {
606
1025
  for (let i = 0; i < values.length; i++) {
607
1026
  const v = toBigInt(values[i]);
608
- if (!inU64(v)) throw argumentError(`unsigned value ${v} out of range`);
609
- this.ensure(VARINT_MAX_BYTES);
610
- this.pos = encodeVarint(v, this.buf, this.pos);
1027
+ if (!splitU64(v)) throw argumentError(`unsigned value ${v} out of range`);
1028
+ const lo = S_U32[LO];
1029
+ const hi = S_U32[HI];
1030
+ this.putVarintLoHi(lo, hi);
611
1031
  }
612
1032
  }
613
1033
  }
614
- /** Write an array of signed integers (each zig-zag + varint). */
1034
+ /** Write an array of signed integers (each zig-zag + varint). See {@link writeUnsignedArray}. */
615
1035
  writeSignedArray(id, values) {
616
1036
  this.arrayHead(id, WireType.ArraySigned, values.length);
617
- if (this.canGrow) {
618
- this.ensure(values.length * VARINT_MAX_BYTES);
1037
+ if (this.flushSink === void 0) {
1038
+ this.pos = this.bulkEnd(
1039
+ this.kernel.encodeSignedVarints(values, this.buf, this.pos),
1040
+ values.length
1041
+ );
1042
+ } else if (this.reserveBulk(values.length * VARINT_MAX_BYTES)) {
619
1043
  this.pos = this.kernel.encodeSignedVarints(values, this.buf, this.pos);
620
1044
  } else {
621
1045
  for (let i = 0; i < values.length; i++) {
622
1046
  const v = toBigInt(values[i]);
623
- if (!inI64(v)) throw argumentError(`signed value ${v} out of range`);
624
- this.ensure(VARINT_MAX_BYTES);
625
- this.pos = encodeVarint(zigzagEncode(v), this.buf, this.pos);
1047
+ if (!splitI64(v)) throw argumentError(`signed value ${v} out of range`);
1048
+ this.putZigzagVarintLoHi(S_U32[LO], S_U32[HI]);
626
1049
  }
627
1050
  }
628
1051
  }
@@ -633,14 +1056,20 @@ var OStream = class {
633
1056
  */
634
1057
  writeUnsignedArrayLong(id, values) {
635
1058
  this.arrayHead(id, WireType.ArrayUnsigned, values.length);
636
- this.ensure(values.length * VARINT_MAX_BYTES);
637
- let pos = this.pos;
638
- const buf = this.buf;
639
- for (let i = 0; i < values.length; i++) {
640
- const v = values[i];
641
- pos = encodeVarintLoHi(v.low, v.high, buf, pos);
1059
+ if (this.reserveBulk(values.length * VARINT_MAX_BYTES)) {
1060
+ let pos = this.pos;
1061
+ const buf = this.buf;
1062
+ for (let i = 0; i < values.length; i++) {
1063
+ const v = values[i];
1064
+ pos = encodeVarintLoHi(v.low, v.high, buf, pos);
1065
+ }
1066
+ this.pos = pos;
1067
+ } else {
1068
+ for (let i = 0; i < values.length; i++) {
1069
+ const v = values[i];
1070
+ this.putVarintLoHi(v.low, v.high);
1071
+ }
642
1072
  }
643
- this.pos = pos;
644
1073
  }
645
1074
  /**
646
1075
  * Write a signed 64-bit array (zig-zag) from {@link Long}[] — the `bigint`-free
@@ -648,32 +1077,33 @@ var OStream = class {
648
1077
  */
649
1078
  writeSignedArrayLong(id, values) {
650
1079
  this.arrayHead(id, WireType.ArraySigned, values.length);
651
- this.ensure(values.length * VARINT_MAX_BYTES);
652
- let pos = this.pos;
653
- const buf = this.buf;
654
- for (let i = 0; i < values.length; i++) {
655
- const v = values[i];
656
- const lo = v.low;
657
- const hi = v.high;
658
- const sgn = -(hi >>> 31) >>> 0;
659
- const zLo = (lo << 1 >>> 0 ^ sgn) >>> 0;
660
- const zHi = ((hi << 1 | lo >>> 31) >>> 0 ^ sgn) >>> 0;
661
- pos = encodeVarintLoHi(zLo, zHi, buf, pos);
1080
+ if (this.reserveBulk(values.length * VARINT_MAX_BYTES)) {
1081
+ let pos = this.pos;
1082
+ const buf = this.buf;
1083
+ for (let i = 0; i < values.length; i++) {
1084
+ const v = values[i];
1085
+ pos = encodeZigzagVarintLoHi(v.low, v.high, buf, pos);
1086
+ }
1087
+ this.pos = pos;
1088
+ } else {
1089
+ for (let i = 0; i < values.length; i++) {
1090
+ const v = values[i];
1091
+ this.putZigzagVarintLoHi(v.low, v.high);
1092
+ }
662
1093
  }
663
- this.pos = pos;
664
1094
  }
665
1095
  /** Write an array of IEEE-754 32-bit floats. */
666
1096
  writeFp32Array(id, values) {
1097
+ if (values instanceof Float32Array) {
1098
+ this.writeFp32Words(id, values);
1099
+ return;
1100
+ }
667
1101
  this.arrayHead(id, WireType.ArrayFixlen, values.length);
668
1102
  this.putVarintNum(4 * 8 + FixlenSubtype.Fp32);
669
- if (this.canGrow) {
670
- this.ensure(values.length * 4);
1103
+ if (this.reserveBulk(values.length * 4)) {
671
1104
  this.pos = this.kernel.packFp32Array(values, this.buf, this.pos);
672
1105
  } else {
673
- for (let i = 0; i < values.length; i++) {
674
- this.ensure(4);
675
- this.pos = packFp32(this.buf, this.pos, values[i]);
676
- }
1106
+ for (let i = 0; i < values.length; i++) this.putFp32(values[i]);
677
1107
  }
678
1108
  }
679
1109
  /**
@@ -697,14 +1127,10 @@ var OStream = class {
697
1127
  writeFp64Array(id, values) {
698
1128
  this.arrayHead(id, WireType.ArrayFixlen, values.length);
699
1129
  this.putVarintNum(8 * 8 + FixlenSubtype.Fp64);
700
- if (this.canGrow) {
701
- this.ensure(values.length * 8);
1130
+ if (this.reserveBulk(values.length * 8)) {
702
1131
  this.pos = this.kernel.packFp64Array(values, this.buf, this.pos);
703
1132
  } else {
704
- for (let i = 0; i < values.length; i++) {
705
- this.ensure(8);
706
- this.pos = packFp64(this.buf, this.pos, values[i]);
707
- }
1133
+ for (let i = 0; i < values.length; i++) this.putFp64(values[i]);
708
1134
  }
709
1135
  }
710
1136
  // --- sequences ----------------------------------------------------------
@@ -728,7 +1154,7 @@ var OStream = class {
728
1154
  if (this.depth >= MAX_DEPTH) {
729
1155
  throw argumentError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
730
1156
  }
731
- if (id < 0 || id > ID_MAX || !Number.isInteger(id)) {
1157
+ if (id >>> 0 !== id || id > ID_MAX) {
732
1158
  throw argumentError(`field id ${id} out of range 0..${ID_MAX}`);
733
1159
  }
734
1160
  this.pending[this.nPending++] = id;
@@ -786,15 +1212,230 @@ var OStream = class {
786
1212
  if (this.depth > 0) this.depth--;
787
1213
  }
788
1214
  // --- internals ----------------------------------------------------------
789
- /** Ensure exactly `value`'s varint size, then write it (bigint path). */
790
- putVarint(value) {
791
- this.ensure(varintSize(value));
792
- this.pos = encodeVarint(value, this.buf, this.pos);
793
- }
794
1215
  /** Ensure exactly `value`'s varint size, then write it (number fast path). */
795
1216
  putVarintNum(value) {
796
- this.ensure(varintSizeNum(value));
797
- this.pos = encodeVarintNum(value, this.buf, this.pos);
1217
+ const pos = this.pos;
1218
+ if (value < 128 && pos < this.buf.length) {
1219
+ this.buf[pos] = value;
1220
+ this.pos = pos + 1;
1221
+ return;
1222
+ }
1223
+ this.putVarintNumSlow(value);
1224
+ }
1225
+ /**
1226
+ * The multi-byte / needs-room tail of {@link putVarintNum}, kept in its own
1227
+ * method so the single-byte test above stays small enough for the JIT to
1228
+ * inline into every `header` / `fixlenHead` / `arrayHead` call site.
1229
+ */
1230
+ putVarintNumSlow(value) {
1231
+ if (this.tryEnsure(varintSizeNum(value))) {
1232
+ this.pos = encodeVarintNum(value, this.buf, this.pos);
1233
+ return;
1234
+ }
1235
+ while (value > 127) {
1236
+ this.putByte(value % 128 | 128);
1237
+ value = Math.floor(value / 128);
1238
+ }
1239
+ this.putByte(value);
1240
+ }
1241
+ /**
1242
+ * Write a 64-bit value, held as two 32-bit halves, as a varint.
1243
+ *
1244
+ * Deliberately just a bounds check and two calls: this is what the array
1245
+ * loops call per element, and it only pays its way while it is small enough
1246
+ * for the JIT to inline. Spelling the drain case out here instead — three
1247
+ * more lines — cost 16-19% on an array streamed through a 32/64-byte buffer,
1248
+ * where most elements take the fast path and want it inlined.
1249
+ */
1250
+ putVarintLoHi(lo, hi) {
1251
+ if (this.buf.length - this.pos >= VARINT_MAX_BYTES) {
1252
+ this.pos = encodeVarintLoHi(lo, hi, this.buf, this.pos);
1253
+ return;
1254
+ }
1255
+ this.putVarintLoHiSlow(lo, hi);
1256
+ }
1257
+ /**
1258
+ * A full buffer that is nonetheless wide enough to hold any varint: drain it
1259
+ * and retry the worst case, which is exactly what `ensure(VARINT_MAX_BYTES)`
1260
+ * did before §5.1 and is still the common streaming case. Sizing the value
1261
+ * first instead — the narrow-buffer path in {@link putVarintLoHiTight} — cost
1262
+ * +125 instructions on every element of an array streamed through a
1263
+ * one-element-wide buffer.
1264
+ */
1265
+ putVarintLoHiSlow(lo, hi) {
1266
+ if (this.buf.length - this.start >= VARINT_MAX_BYTES) {
1267
+ this.flush();
1268
+ if (this.buf.length - this.pos >= VARINT_MAX_BYTES) {
1269
+ this.pos = encodeVarintLoHi(lo, hi, this.buf, this.pos);
1270
+ return;
1271
+ }
1272
+ }
1273
+ this.putVarintLoHiTight(lo, hi);
1274
+ }
1275
+ /**
1276
+ * Zig-zag {@link putVarintLoHi}: `(n << 1) ^ (n >> 63)` on the halves. Keeps
1277
+ * its own worst-case fast path so the signed array loop reaches the combined
1278
+ * zig-zag-and-encode writer directly, exactly as it did before; the drain and
1279
+ * narrow-buffer cases are the same for both signs, so they are shared.
1280
+ */
1281
+ putZigzagVarintLoHi(lo, hi) {
1282
+ if (this.buf.length - this.pos >= VARINT_MAX_BYTES) {
1283
+ this.pos = encodeZigzagVarintLoHi(lo, hi, this.buf, this.pos);
1284
+ return;
1285
+ }
1286
+ const sgn = -(hi >>> 31) >>> 0;
1287
+ this.putVarintLoHi(
1288
+ (lo << 1 >>> 0 ^ sgn) >>> 0,
1289
+ ((hi << 1 | lo >>> 31) >>> 0 ^ sgn) >>> 0
1290
+ );
1291
+ }
1292
+ /**
1293
+ * The narrow-buffer tail of {@link putVarintLoHi}: the buffer could not hold a
1294
+ * worst-case varint even empty. Sizing the value exactly keeps such a buffer
1295
+ * from flushing for room it does not need; only when it cannot hold the varint
1296
+ * *at all* does the value get split across flushes, seven bits at a time.
1297
+ */
1298
+ putVarintLoHiTight(lo, hi) {
1299
+ lo >>>= 0;
1300
+ hi >>>= 0;
1301
+ if (this.tryEnsure(varintSizeLoHi(lo, hi))) {
1302
+ this.pos = encodeVarintLoHi(lo, hi, this.buf, this.pos);
1303
+ return;
1304
+ }
1305
+ for (; ; ) {
1306
+ const more = hi !== 0 || lo > 127;
1307
+ this.putByte(more ? lo & 127 | 128 : lo);
1308
+ if (!more) return;
1309
+ lo = (lo >>> 7 | hi << 25) >>> 0;
1310
+ hi >>>= 7;
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Write the 4 little-endian bytes of an fp32 (§4.6).
1315
+ *
1316
+ * Through the shared scratch, not a `DataView` over the buffer: building that
1317
+ * handle costs ~129 ns against the ~2 ns it saves on one value (§6.6.2 allows the
1318
+ * handle, arithmetic forbids it here). The bulk array path amortizes one over the
1319
+ * whole run instead — see the kernel.
1320
+ */
1321
+ putFp32(value) {
1322
+ if (this.buf.length - this.pos >= 4) {
1323
+ this.pos = packFp32(this.buf, this.pos, value);
1324
+ return;
1325
+ }
1326
+ this.putFp32Slow(value);
1327
+ }
1328
+ putFp32Slow(value) {
1329
+ if (this.tryEnsure(4)) {
1330
+ this.pos = packFp32(this.buf, this.pos, value);
1331
+ return;
1332
+ }
1333
+ this.putFp32Bits(fp32Bits(value));
1334
+ }
1335
+ /**
1336
+ * Write the 4 little-endian bytes of an fp32 held as a 32-bit word (§4.6) — the
1337
+ * path {@link OStream.writeFp32Bits} takes, and the tail of
1338
+ * {@link OStream.putFp32Slow}.
1339
+ */
1340
+ putFp32Bits(bits) {
1341
+ if (this.buf.length - this.pos >= 4) {
1342
+ const buf = this.buf;
1343
+ let p = this.pos;
1344
+ buf[p++] = bits & 255;
1345
+ buf[p++] = bits >>> 8 & 255;
1346
+ buf[p++] = bits >>> 16 & 255;
1347
+ buf[p++] = bits >>> 24;
1348
+ this.pos = p;
1349
+ return;
1350
+ }
1351
+ this.putByte(bits & 255);
1352
+ this.putByte(bits >>> 8 & 255);
1353
+ this.putByte(bits >>> 16 & 255);
1354
+ this.putByte(bits >>> 24);
1355
+ }
1356
+ /**
1357
+ * {@link writeFp32Array} for a `Float32Array` source: its own 32-bit words go
1358
+ * out, never a `number`, which is what keeps a signaling NaN intact (§6.5) —
1359
+ * on the bulk path (the kernel copies words too) and on the streamed one alike,
1360
+ * so a small buffer produces the one-shot bytes (§5.1.4).
1361
+ *
1362
+ * Kept to the header and the bulk call, the streaming loop in its own method:
1363
+ * with the loop in this body an 8-element one-shot array cost +416 Ir/op
1364
+ * (+8.8%) over the pre-#185 encoder, split like this +1.1% (Callgrind).
1365
+ */
1366
+ writeFp32Words(id, values) {
1367
+ this.arrayHead(id, WireType.ArrayFixlen, values.length);
1368
+ this.putVarintNum(4 * 8 + FixlenSubtype.Fp32);
1369
+ if (this.reserveBulk(values.length * 4)) {
1370
+ this.pos = this.kernel.packFp32Array(values, this.buf, this.pos);
1371
+ } else {
1372
+ this.putFp32Words(values);
1373
+ }
1374
+ }
1375
+ /**
1376
+ * The streamed half of {@link writeFp32Words}: one `Uint32Array` over the
1377
+ * source per call, the same handle the bulk kernel takes (§6.6.2); reading it gives each word's value whatever the
1378
+ * host byte order, and the shifts below store it little-endian. The words go
1379
+ * out one run per stretch of free buffer, with `buf`/`pos` in locals, and the
1380
+ * split points are {@link putFp32}'s: drain when fewer than 4 bytes are free,
1381
+ * split an element byte by byte only when the buffer itself is narrower than 4.
1382
+ */
1383
+ putFp32Words(values) {
1384
+ const w = new Uint32Array(values.buffer, values.byteOffset, values.length);
1385
+ const n = w.length;
1386
+ let i = 0;
1387
+ while (i < n) {
1388
+ if (this.buf.length - this.pos < 4 && !this.tryEnsure(4)) {
1389
+ this.putFp32Bits(w[i++]);
1390
+ continue;
1391
+ }
1392
+ const buf = this.buf;
1393
+ let p = this.pos;
1394
+ const end = Math.min(n, i + (buf.length - p >> 2));
1395
+ for (; i < end; i++) {
1396
+ const b = w[i];
1397
+ buf[p] = b & 255;
1398
+ buf[p + 1] = b >>> 8 & 255;
1399
+ buf[p + 2] = b >>> 16 & 255;
1400
+ buf[p + 3] = b >>> 24;
1401
+ p += 4;
1402
+ }
1403
+ this.pos = p;
1404
+ }
1405
+ }
1406
+ /** Write the 8 little-endian bytes of an fp64 (§4.6) — see {@link putFp32}. */
1407
+ putFp64(value) {
1408
+ if (this.buf.length - this.pos >= 8) {
1409
+ this.pos = packFp64(this.buf, this.pos, value);
1410
+ return;
1411
+ }
1412
+ this.putFp64Slow(value);
1413
+ }
1414
+ putFp64Slow(value) {
1415
+ if (this.tryEnsure(8)) {
1416
+ this.pos = packFp64(this.buf, this.pos, value);
1417
+ return;
1418
+ }
1419
+ const lo = fp64BitsLo(value);
1420
+ const hi = fp64BitsHi(value);
1421
+ this.putByte(lo & 255);
1422
+ this.putByte(lo >>> 8 & 255);
1423
+ this.putByte(lo >>> 16 & 255);
1424
+ this.putByte(lo >>> 24);
1425
+ this.putByte(hi & 255);
1426
+ this.putByte(hi >>> 8 & 255);
1427
+ this.putByte(hi >>> 16 & 255);
1428
+ this.putByte(hi >>> 24);
1429
+ }
1430
+ /**
1431
+ * Append one byte, draining to the sink first when the buffer is full.
1432
+ *
1433
+ * @internal Public only because {@link utf8WriteSink} writes through it — the
1434
+ * narrow-buffer string path (§5.1.3). Not part of the field-writing API.
1435
+ */
1436
+ putByte(b) {
1437
+ if (this.pos === this.buf.length) this.ensureSome(1);
1438
+ this.buf[this.pos++] = b;
798
1439
  }
799
1440
  /**
800
1441
  * Write a field header, the `(id << 3) | wireType` tag, as a varint.
@@ -813,7 +1454,7 @@ var OStream = class {
813
1454
  * {@link OStream.writeSequenceBeginLazy}, which writes no byte at all.
814
1455
  */
815
1456
  header(id, type) {
816
- if (id < 0 || id > ID_MAX || !Number.isInteger(id)) {
1457
+ if (id >>> 0 !== id || id > ID_MAX) {
817
1458
  throw argumentError(`field id ${id} out of range 0..${ID_MAX}`);
818
1459
  }
819
1460
  if (this.nPending !== 0) this.commitPending();
@@ -830,8 +1471,9 @@ var OStream = class {
830
1471
  commitPending() {
831
1472
  const n = this.nPending;
832
1473
  this.nPending = 0;
1474
+ const pending = this.pending;
833
1475
  for (let i = 0; i < n; i++) {
834
- this.putVarintNum(this.pending[i] * 8 + WireType.SequenceStart);
1476
+ this.putVarintNum(pending[i] * 8 + WireType.SequenceStart);
835
1477
  }
836
1478
  }
837
1479
  fixlenHead(id, length, subtype) {
@@ -845,332 +1487,335 @@ var OStream = class {
845
1487
  this.header(id, type);
846
1488
  this.putVarintNum(count);
847
1489
  }
848
- /** Copy `data` out, flushing/growing as needed (large payloads stay chunked). */
1490
+ /**
1491
+ * Copy `data` out, flushing/growing as needed (large payloads stay chunked).
1492
+ *
1493
+ * The whole-payload case — the common one, and the only one on a buffer sized
1494
+ * from `MAX_SIZE` or on the accumulator — is a single `set` of the caller's
1495
+ * array: a `memcpy`, and no view at all.
1496
+ *
1497
+ * **A payload split across flushes takes a per-piece view: a language-forced
1498
+ * handle under CORELIB_PLAN §6.6.2.** `TypedArray.set` is the only `memcpy`
1499
+ * this language exposes and it takes a *typed array* as its source, so copying a
1500
+ * *range* of one needs a `subarray` — §6.6.2's "the only way to name a region of
1501
+ * the caller's buffer is a wrapper over it". It has the two properties that
1502
+ * clause requires: it carries no message bytes (the storage is the caller's, on
1503
+ * both ends) and no wire number sizes it (a handle over a thousand bytes costs
1504
+ * what a handle over ten costs). The allocation-free alternative is a byte loop,
1505
+ * measured at 358 MB/s against 10,963 MB/s for `set`.
1506
+ *
1507
+ * It never leaves this method: `set` consumes it and no caller can reach it, so
1508
+ * §6.7's ban on exposing a value that outlives its callback is untouched — and so
1509
+ * is §5.1.6, which is why the copy happens at all rather than the payload being
1510
+ * handed to the sink. §6.6.2 asks the port to make such handles visible rather
1511
+ * than invisible: the README itemises it (§9.6) and `heap-free-codec.test.ts`
1512
+ * pins its count and kind.
1513
+ */
849
1514
  writeRaw(data) {
1515
+ const total = data.length;
850
1516
  let off = 0;
851
- while (off < data.length) {
852
- const room = this.ensureSome(data.length - off);
853
- this.buf.set(data.subarray(off, off + room), this.pos);
1517
+ while (off < total) {
1518
+ const room = this.ensureSome(total - off);
1519
+ if (off === 0 && room === total) {
1520
+ this.buf.set(data, this.pos);
1521
+ } else {
1522
+ this.buf.set(data.subarray(off, off + room), this.pos);
1523
+ }
854
1524
  this.pos += room;
855
1525
  off += room;
856
1526
  }
857
1527
  }
858
- /** Ensure `n` contiguous bytes are free at `pos`; returns `pos` for chaining. */
859
- ensure(n) {
860
- if (this.buf.length - this.pos >= n) return this.pos;
861
- this.flush();
862
- if (this.buf.length - this.pos >= n) return this.pos;
863
- if (this.canGrow) {
864
- this.growTo(this.pos + n);
865
- return this.pos;
866
- }
867
- throw bufferFullError(
868
- `output buffer full: need ${n} more bytes, have ${this.buf.length - this.pos}`
869
- );
1528
+ /**
1529
+ * Make room for `n` contiguous bytes at `pos` if the buffer can hold them at
1530
+ * all: `true` when it can (flushing or growing as needed), `false` when a
1531
+ * fixed caller buffer is simply smaller than `n` and the value must be split
1532
+ * across flushes instead — CORELIB_PLAN §5.1 puts the floor on the output
1533
+ * buffer at a single byte, so no write may demand a contiguous run.
1534
+ *
1535
+ * The one case that still fails is a buffer with no sink to drain to: there is
1536
+ * nowhere for a split to put the earlier bytes, so it reports BufferFull here,
1537
+ * before anything is written, exactly as {@link ensure} did.
1538
+ */
1539
+ tryEnsure(n) {
1540
+ if (this.buf.length - this.pos >= n) return true;
1541
+ this.drain(n);
1542
+ if (this.buf.length - this.pos >= n) return true;
1543
+ if (this.flushSink === void 0) {
1544
+ throw bufferFullError(
1545
+ `output buffer full: need ${n} more bytes, have ${this.buf.length - this.pos}`
1546
+ );
1547
+ }
1548
+ return false;
870
1549
  }
871
- /** Ensure *some* room (up to `want`); returns how many bytes are available. */
872
- ensureSome(want) {
873
- let room = this.buf.length - this.pos;
874
- if (room === 0) {
875
- this.flush();
876
- room = this.buf.length - this.pos;
877
- if (room === 0) {
878
- if (this.canGrow) {
879
- this.growTo(this.pos + want);
880
- room = this.buf.length - this.pos;
881
- } else {
882
- throw bufferFullError("output buffer full");
883
- }
884
- }
885
- }
886
- return Math.min(room, want);
887
- }
888
- growTo(needed) {
889
- let cap = this.buf.length * 2;
890
- if (cap < needed) cap = needed;
891
- const next = new Uint8Array(cap);
892
- next.set(this.buf.subarray(0, this.pos));
893
- this.buf = next;
1550
+ /**
1551
+ * Reserve `n` contiguous bytes for a bulk write — the whole payload of an
1552
+ * array or a string, written in one pass into a buffer that cannot move under
1553
+ * it. Every caller has an element-at-a-time route to fall back on when this
1554
+ * says no, producing the identical bytes, so a `false` here is never an error.
1555
+ *
1556
+ * The room already at the cursor counts on **any** buffer, which is what makes
1557
+ * the one-shot `new OStream(buf)` case — a caller buffer sized from the
1558
+ * schema's `MAX_SIZE`, the shape CORELIB_PLAN §5.1 puts first — the fast one:
1559
+ * without it a message encoded into a caller's own buffer took `TextEncoder`
1560
+ * for every string and the element loop for every array, measured at 1.9 µs
1561
+ * against 0.16 µs for the same five-field message.
1562
+ *
1563
+ * Beyond that room only a **sink** may be asked, and only by draining. Emptying
1564
+ * the buffer is the one thing that can produce room without an allocation
1565
+ * anywhere (§6.6), and it is legal wherever this is called — every caller has
1566
+ * just written a complete header, so the cursor is on a boundary between atomic
1567
+ * units (§5.1.3). A sink that installs a larger replacement (§5.1.5) therefore
1568
+ * re-opens the bulk route by itself, which is how the accumulating helper keeps
1569
+ * it. Nothing is *demanded*: a `false` sends the caller down its
1570
+ * element-at-a-time route, which produces the identical bytes, so a fixed
1571
+ * buffer too narrow for the worst case never turns into a spurious
1572
+ * `BUFFER_FULL`.
1573
+ */
1574
+ reserveBulk(n) {
1575
+ if (this.buf.length - this.pos >= n) return true;
1576
+ if (this.flushSink === void 0) return false;
1577
+ this.drain(n);
1578
+ return this.buf.length - this.pos >= n;
894
1579
  }
895
- };
896
-
897
- // src/decode/fast.ts
898
- var TWO32 = 4294967296;
899
- function decodeContiguous(buf, root, limits) {
900
- new FastDecoder(buf, limits).run(root);
901
- }
902
- var FastDecoder = class {
903
- constructor(buf, limits) {
904
- this.p = 0;
905
- // Last varint, as two unsigned 32-bit halves (see readVarint).
906
- this.lo = 0;
907
- this.hi = 0;
908
- this.buf = buf;
909
- this.n = buf.length;
910
- this.view = new DataView(buf.buffer, buf.byteOffset, buf.length);
911
- this.maxArrayCount = limits?.maxArrayCount ?? Infinity;
912
- this.maxStringLen = limits?.maxStringLen ?? Infinity;
913
- this.maxBlobLen = limits?.maxBlobLen ?? Infinity;
914
- }
915
- run(root) {
916
- const stack = [root];
917
- let top = root;
918
- while (this.p < this.n) {
919
- this.readVarint();
920
- const type = this.lo & 7;
921
- if (type === WireType.SequenceEnd) {
922
- if (stack.length <= 1) throw invalidMsgError("unbalanced sequence end");
923
- top.sequenceEnd?.();
924
- stack.pop();
925
- top = stack[stack.length - 1];
926
- continue;
927
- }
928
- const id = this.upper();
929
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
930
- switch (type) {
931
- case WireType.Unsigned: {
932
- this.readVarint();
933
- top.unsigned?.(id, this.unsignedValue());
934
- break;
935
- }
936
- case WireType.Signed: {
937
- this.readVarint();
938
- top.signed?.(id, this.signedValue());
939
- break;
940
- }
941
- case WireType.Fixlen: {
942
- this.readVarint();
943
- const sub = this.lo & 7;
944
- const len = this.upper();
945
- if (sub > FixlenSubtype.Blob) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
946
- if (len > FIXLEN_MAX) throw invalidMsgError("fixlen length out of range");
947
- if (sub === FixlenSubtype.String && len > this.maxStringLen) {
948
- throw limitExceededError(`string length ${len} exceeds maxStringLen ${this.maxStringLen}`);
949
- }
950
- if (sub === FixlenSubtype.Blob && len > this.maxBlobLen) {
951
- throw limitExceededError(`blob length ${len} exceeds maxBlobLen ${this.maxBlobLen}`);
952
- }
953
- if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
954
- const want = sub === FixlenSubtype.Fp32 ? 4 : 8;
955
- if (len !== want) throw invalidMsgError("fixlen float length mismatch");
956
- if (sub === FixlenSubtype.Fp32) {
957
- const p = this.p;
958
- const value = this.readFp32();
959
- top.fp32?.(id, value, top.fp32Raw ? this.buf.subarray(p, p + 4) : void 0);
960
- } else {
961
- const value = this.readFp64();
962
- top.fp64?.(id, value);
963
- }
964
- } else {
965
- const chunk = this.take(len);
966
- if (sub === FixlenSubtype.String) top.string?.(id, len, 0, chunk);
967
- else top.blob?.(id, len, 0, chunk);
968
- }
969
- break;
970
- }
971
- case WireType.ArrayUnsigned: {
972
- const count = this.arrayCount();
973
- top.arrayBegin?.(id, ArrayKind.Unsigned, count);
974
- for (let i = 0; i < count; i++) {
975
- this.readVarint();
976
- top.arrayUnsigned?.(id, i, this.unsignedValue());
977
- }
978
- top.arrayEnd?.(id);
979
- break;
980
- }
981
- case WireType.ArraySigned: {
982
- const count = this.arrayCount();
983
- top.arrayBegin?.(id, ArrayKind.Signed, count);
984
- for (let i = 0; i < count; i++) {
985
- this.readVarint();
986
- top.arraySigned?.(id, i, this.signedValue());
987
- }
988
- top.arrayEnd?.(id);
989
- break;
990
- }
991
- case WireType.ArrayFixlen: {
992
- const count = this.arrayCount();
993
- this.readVarint();
994
- const sub = this.lo & 7;
995
- const size = this.upper();
996
- let kind;
997
- if (sub === FixlenSubtype.Fp32 && size === 4) kind = ArrayKind.Fp32;
998
- else if (sub === FixlenSubtype.Fp64 && size === 8) kind = ArrayKind.Fp64;
999
- else throw invalidMsgError("invalid fixlen array element type");
1000
- top.arrayBegin?.(id, kind, count);
1001
- if (kind === ArrayKind.Fp32) {
1002
- const wantRaw = top.fp32Raw === true;
1003
- for (let i = 0; i < count; i++) {
1004
- const p = this.p;
1005
- const value = this.readFp32();
1006
- top.arrayFp32?.(id, i, value, wantRaw ? this.buf.subarray(p, p + 4) : void 0);
1007
- }
1008
- } else {
1009
- for (let i = 0; i < count; i++) {
1010
- const value = this.readFp64();
1011
- top.arrayFp64?.(id, i, value);
1012
- }
1013
- }
1014
- top.arrayEnd?.(id);
1015
- break;
1016
- }
1017
- case WireType.SequenceStart: {
1018
- if (stack.length - 1 >= MAX_DEPTH) {
1019
- throw invalidMsgError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
1020
- }
1021
- const child = top.sequenceBegin?.(id);
1022
- top = child ?? top;
1023
- stack.push(top);
1024
- break;
1025
- }
1026
- default:
1027
- throw invalidMsgError(`invalid wire type ${type}`);
1028
- }
1029
- }
1030
- if (stack.length > 1) throw incompleteError("truncated message: unbalanced sequence");
1031
- }
1032
- // --- field helpers ------------------------------------------------------
1033
- /** Read and validate an array count word (0..ARRAY_MAX; §4.7/§4.8). */
1034
- arrayCount() {
1035
- this.readVarint();
1036
- const count = this.num();
1037
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1038
- if (count > this.maxArrayCount) {
1039
- throw limitExceededError(`array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`);
1040
- }
1041
- return count;
1042
- }
1043
- /** Hand back a zero-copy view of the next `len` bytes, advancing the cursor. */
1044
- take(len) {
1045
- const start = this.p;
1046
- const end = start + len;
1047
- if (end > this.n) throw incompleteError("truncated fixlen payload");
1048
- this.p = end;
1049
- return this.buf.subarray(start, end);
1050
- }
1051
- readFp32() {
1052
- const p = this.p;
1053
- if (p + 4 > this.n) throw incompleteError("truncated fp32");
1054
- this.p = p + 4;
1055
- return this.view.getFloat32(p, true);
1056
- }
1057
- readFp64() {
1058
- const p = this.p;
1059
- if (p + 8 > this.n) throw incompleteError("truncated fp64");
1060
- this.p = p + 8;
1061
- return this.view.getFloat64(p, true);
1062
- }
1063
- // --- varint reading -----------------------------------------------------
1064
- /** The last varint's full value as a `bigint` (64-bit fidelity). */
1065
- big() {
1066
- return this.hi === 0 ? BigInt(this.lo >>> 0) : BigInt(this.hi >>> 0) << 32n | BigInt(this.lo >>> 0);
1067
- }
1068
- /**
1069
- * The last varint as an unsigned value, number-first: a `number` when it fits
1070
- * exactly (`≤ 2^53-1` — all ids, u8..u32 and small u64s), a `bigint` only
1071
- * beyond that. Skips the per-value bigint allocation on the common path.
1072
- */
1073
- unsignedValue() {
1074
- const hi = this.hi >>> 0;
1075
- return hi <= 2097151 ? hi * TWO32 + (this.lo >>> 0) : this.big();
1076
- }
1077
- /** The last zig-zag varint as a signed value, number-first (see {@link unsignedValue}). */
1078
- signedValue() {
1079
- const hi = this.hi >>> 0;
1080
- if (hi <= 2097151) {
1081
- const r = hi * TWO32 + (this.lo >>> 0);
1082
- return r % 2 === 0 ? r / 2 : -(r + 1) / 2;
1580
+ /**
1581
+ * Commit the position a bulk kernel returned, in the **block** mode.
1582
+ *
1583
+ * Nothing reserves room in front of that kernel, and nothing could: the bytes an
1584
+ * array takes are only known once it is encoded, and the estimate that used to
1585
+ * stand in — the source's own `constructor`, which any object can set — silently
1586
+ * truncated the message when it was wrong (§5.1). Here the bound is the buffer's
1587
+ * own length, applied afterwards. The varint kernels stop writing at
1588
+ * `out.length` and keep counting (see {@link Kernel}), so a `pos` past the end
1589
+ * is the exact shortfall and nothing was written outside the buffer.
1590
+ *
1591
+ * This is the block mode's error and only its: the buffer is meant to hold the
1592
+ * whole message, so one that does not fit is exactly what `BUFFER_FULL` means.
1593
+ * The streaming mode never gets here, and `BUFFER_FULL` is unreachable there by
1594
+ * contract.
1595
+ */
1596
+ bulkEnd(pos, count) {
1597
+ if (pos > this.buf.length) {
1598
+ throw bufferFullError(
1599
+ `output buffer full: an array of ${count} elements needs ${pos - this.buf.length} more bytes`
1600
+ );
1083
1601
  }
1084
- return zigzagDecode(this.big());
1085
- }
1086
- /** The last varint's value as a JS number — exact for ids/lengths/counts. */
1087
- num() {
1088
- return this.hi * TWO32 + (this.lo >>> 0);
1089
- }
1090
- /** The last varint with its low 3 tag bits stripped (`value >> 3`). */
1091
- upper() {
1092
- return (this.hi >>> 0) * (TWO32 / 8) + (this.lo >>> 3);
1602
+ return pos;
1093
1603
  }
1094
1604
  /**
1095
- * Decode one LEB128 varint at the cursor into {@link lo} / {@link hi} (each an
1096
- * unsigned 32-bit half), advancing {@link p}. Throws on truncation or a value
1097
- * spilling past 64 bits (>10 bytes). Unrolled, number-only — no `bigint`.
1605
+ * Ensure `n` contiguous bytes are free at `pos`; returns `pos` for chaining.
1606
+ *
1607
+ * The only remaining caller is the one-byte sequence-end marker, which is
1608
+ * indivisible: there is no smaller piece to split it into, so a buffer that
1609
+ * cannot take it has nothing left to report but `BUFFER_FULL`.
1098
1610
  */
1099
- readVarint() {
1100
- const buf = this.buf;
1101
- const n = this.n;
1102
- let p = this.p;
1103
- let b;
1104
- let lo;
1105
- let hi = 0;
1106
- if (p >= n) throw incompleteError("truncated varint");
1107
- b = buf[p++];
1108
- lo = b & 127;
1109
- if (b < 128) return this.set(lo, 0, p);
1110
- if (p >= n) throw incompleteError("truncated varint");
1111
- b = buf[p++];
1112
- lo |= (b & 127) << 7;
1113
- if (b < 128) return this.set(lo, 0, p);
1114
- if (p >= n) throw incompleteError("truncated varint");
1115
- b = buf[p++];
1116
- lo |= (b & 127) << 14;
1117
- if (b < 128) return this.set(lo, 0, p);
1118
- if (p >= n) throw incompleteError("truncated varint");
1119
- b = buf[p++];
1120
- lo |= (b & 127) << 21;
1121
- if (b < 128) return this.set(lo, 0, p);
1122
- if (p >= n) throw incompleteError("truncated varint");
1123
- b = buf[p++];
1124
- lo |= (b & 15) << 28;
1125
- hi = b >> 4 & 7;
1126
- if (b < 128) return this.set(lo, hi, p);
1127
- if (p >= n) throw incompleteError("truncated varint");
1128
- b = buf[p++];
1129
- hi |= (b & 127) << 3;
1130
- if (b < 128) return this.set(lo, hi, p);
1131
- if (p >= n) throw incompleteError("truncated varint");
1132
- b = buf[p++];
1133
- hi |= (b & 127) << 10;
1134
- if (b < 128) return this.set(lo, hi, p);
1135
- if (p >= n) throw incompleteError("truncated varint");
1136
- b = buf[p++];
1137
- hi |= (b & 127) << 17;
1138
- if (b < 128) return this.set(lo, hi, p);
1139
- if (p >= n) throw incompleteError("truncated varint");
1140
- b = buf[p++];
1141
- hi |= (b & 127) << 24;
1142
- if (b < 128) return this.set(lo, hi, p);
1143
- if (p >= n) throw incompleteError("truncated varint");
1144
- b = buf[p++];
1145
- if ((b & 127) >> 1 !== 0) throw invalidMsgError("varint overflow");
1146
- hi |= (b & 127) << 31;
1147
- if (b < 128) return this.set(lo, hi, p);
1148
- throw invalidMsgError("varint overflow");
1611
+ ensure(n) {
1612
+ if (!this.tryEnsure(n)) {
1613
+ throw bufferFullError(
1614
+ `output buffer full: need ${n} more bytes, have ${this.buf.length - this.pos}`
1615
+ );
1616
+ }
1617
+ return this.pos;
1149
1618
  }
1150
- set(lo, hi, p) {
1151
- this.lo = lo;
1152
- this.hi = hi;
1153
- this.p = p;
1619
+ /** Ensure *some* room (up to `want`); returns how many bytes are available. */
1620
+ ensureSome(want) {
1621
+ let room = this.buf.length - this.pos;
1622
+ if (room === 0) {
1623
+ this.flush();
1624
+ room = this.buf.length - this.pos;
1625
+ if (room === 0) throw bufferFullError("output buffer full");
1626
+ }
1627
+ return Math.min(room, want);
1154
1628
  }
1155
1629
  };
1156
1630
 
1631
+ // src/encode/accumulate.ts
1632
+ var DEFAULT_CAPACITY = 256;
1633
+ var MIN_WINDOW = 16;
1634
+ var SLAB_BYTES = 8192;
1635
+ var SLAB_MAX_TAKE = SLAB_BYTES >>> 1;
1636
+ var slab = null;
1637
+ var slabUsed = 0;
1638
+ function accumulatorBuffer(n) {
1639
+ if (n > SLAB_MAX_TAKE) return new Uint8Array(n);
1640
+ let s = slab;
1641
+ if (s === null || s.length - slabUsed < n) {
1642
+ s = slab = new Uint8Array(SLAB_BYTES);
1643
+ slabUsed = 0;
1644
+ }
1645
+ const from = slabUsed;
1646
+ slabUsed = from + n;
1647
+ return s.subarray(from, slabUsed);
1648
+ }
1649
+ var ACCUMULATE = function(buffer, _start, end, needed = 0) {
1650
+ const used = this.bytesUsed;
1651
+ const window = needed > MIN_WINDOW ? needed : MIN_WINDOW;
1652
+ if (buffer.length - end >= window) {
1653
+ this.setBuffer(buffer, end, used);
1654
+ return;
1655
+ }
1656
+ let cap = buffer.length * 2;
1657
+ const want = used + window;
1658
+ if (cap < want) cap = want;
1659
+ const next = accumulatorBuffer(cap);
1660
+ next.set(buffer.subarray(end - used, end));
1661
+ this.setBuffer(next, used, used);
1662
+ };
1663
+ function growingOStream(initialCapacity = DEFAULT_CAPACITY) {
1664
+ if (!Number.isInteger(initialCapacity) || initialCapacity < 1) {
1665
+ throw argumentError(`initial capacity ${initialCapacity} must be a positive integer`);
1666
+ }
1667
+ return new OStream(accumulatorBuffer(initialCapacity), 0, ACCUMULATE);
1668
+ }
1669
+
1670
+ // src/decode/skip.ts
1671
+ var SKIP = Object.freeze({});
1672
+
1157
1673
  // src/decode/state.ts
1158
- var TWO322 = 4294967296;
1674
+ var TWO32 = 4294967296;
1675
+ var TYPED_CAPACITY = /* @__PURE__ */ new Map([
1676
+ [Uint8Array, { min: 0, max: 255 }],
1677
+ [Uint16Array, { min: 0, max: 65535 }],
1678
+ [Uint32Array, { min: 0, max: 4294967295 }],
1679
+ [Int8Array, { min: -128, max: 127 }],
1680
+ [Int16Array, { min: -32768, max: 32767 }],
1681
+ [Int32Array, { min: -2147483648, max: 2147483647 }],
1682
+ // The 64-bit pair is the accumulator's own range on both sides, so any bound a
1683
+ // caller can state fits: `min`/`max` here are the sentinels the fit test needs,
1684
+ // not numbers anything is compared against (the fill writes raw halves).
1685
+ [BigUint64Array, { min: 0, max: Number.POSITIVE_INFINITY }],
1686
+ [BigInt64Array, { min: Number.NEGATIVE_INFINITY, max: Number.POSITIVE_INFINITY }]
1687
+ ]);
1688
+ function typedCapacity(ctor) {
1689
+ if (ctor === Uint8Array) return CAP_U8;
1690
+ if (ctor === Int8Array) return CAP_I8;
1691
+ if (ctor === Uint16Array) return CAP_U16;
1692
+ if (ctor === Int16Array) return CAP_I16;
1693
+ if (ctor === Uint32Array) return CAP_U32;
1694
+ if (ctor === Int32Array) return CAP_I32;
1695
+ return TYPED_CAPACITY.get(ctor);
1696
+ }
1697
+ var CAP_U8 = TYPED_CAPACITY.get(Uint8Array);
1698
+ var CAP_I8 = TYPED_CAPACITY.get(Int8Array);
1699
+ var CAP_U16 = TYPED_CAPACITY.get(Uint16Array);
1700
+ var CAP_I16 = TYPED_CAPACITY.get(Int16Array);
1701
+ var CAP_U32 = TYPED_CAPACITY.get(Uint32Array);
1702
+ var CAP_I32 = TYPED_CAPACITY.get(Int32Array);
1703
+ function is64(d) {
1704
+ return d instanceof BigUint64Array || d instanceof BigInt64Array;
1705
+ }
1159
1706
  var DecoderState = class {
1160
- constructor(limits) {
1707
+ constructor(visitor = SKIP) {
1708
+ /**
1709
+ * Depth at which the current skipped subtree was opened, or `-1` when nothing
1710
+ * is being skipped. The scope that returned `false` from
1711
+ * {@link Visitor.sequenceBegin} closes at this depth, and skipping ends there.
1712
+ */
1713
+ this.skipFrom = -1;
1714
+ /**
1715
+ * **No receiver cap lives here** (§6.2.1). This decoder used to hold
1716
+ * `maxArrayCount` / `maxStringLen` / `maxBlobLen`, defaulted to the format
1717
+ * ceilings when the caller supplied none — which is precisely the shape §6.2.1
1718
+ * forbids: "a codec **MUST NOT** hold a limit of its own, **MUST NOT** supply a
1719
+ * default for one it was not given, **MUST NOT** read an omitted argument as
1720
+ * *unlimited*, and **MUST NOT** clamp to one", and "a format ceiling (§6.2)
1721
+ * reached because no cap was stated is the **format's** bound, not a receiver
1722
+ * cap, and a port **MUST NOT** present it as one". Reporting `LimitExceeded`
1723
+ * against `ARRAY_MAX`/`FIXLEN_MAX` did exactly that.
1724
+ *
1725
+ * The caps now have **one implementation** and it is not here: generated code
1726
+ * compares them in its own flat visitor, at `arrayBegin` / `fixlenBegin` — both
1727
+ * of which this decoder raises at the count / length header, before a byte of
1728
+ * payload is emitted and behind the MESSAGE_SPEC §7.3 tag test — and a wrapper
1729
+ * array's elements, which reach no visitor callback, are capped by the
1730
+ * `StringSeq` / `BlobSeq` collectors from bounds passed to their
1731
+ * constructors. §6.2.1: "A port whose codec offers the check **MUST NOT** also
1732
+ * emit it into the generated layer, and a port that enforces it in generated
1733
+ * code **MUST NOT** ask the codec to enforce it too."
1734
+ *
1735
+ * The format ceilings below (`ARRAY_MAX`, `FIXLEN_MAX`, `MAX_DEPTH`, the varint
1736
+ * bound) are *not* receiver caps and stay here: they bound what the wire may
1737
+ * express, and exceeding one is `INVALID` (§6.2).
1738
+ */
1739
+ /**
1740
+ * The id of every open sequence, indexed by the depth it was opened at, so a
1741
+ * scope close can name the sequence it closes. Fixed size, sized from
1742
+ * {@link MAX_DEPTH} at construction — the "fixed-size parse stack" §6.6.2
1743
+ * allows, and the reason nothing here grows a stack per message.
1744
+ *
1745
+ * A plain array rather than an `Int32Array`, and the difference is 3 µs: V8
1746
+ * keeps a typed array's bytes inside the JS heap only up to 64 bytes, so a
1747
+ * 255-slot one is an *external* allocation — measured at ~3.1 µs on Node 24,
1748
+ * against ~5 ns for this. That is paid per decoder, and the one-shot
1749
+ * {@link decode} builds a decoder per message, so it was the whole cost of
1750
+ * decoding a small one. Slots are written before they are read (a scope is
1751
+ * opened before it closes), so the array is never read holey.
1752
+ */
1753
+ this.seqIds = new Array(MAX_DEPTH);
1754
+ /** Number of nested sequences currently open — 0 at the root scope. */
1755
+ this.depth = 0;
1161
1756
  this.state = 0 /* Header */;
1162
- this.stack = [];
1163
- // current field
1757
+ /**
1758
+ * The terminal-refusal latch: the rejection this stream was stopped by, or
1759
+ * `null` while it is still healthy. **One latch, two codes** — §5.3.1 gives the
1760
+ * rule one implementation, and §6.3 makes both of these rejections terminal:
1761
+ *
1762
+ * - `INVALID_MSG` (§5.2.1: "malformed **regardless of what follows** … no —
1763
+ * terminal") — no later bytes can make malformed input valid;
1764
+ * - `LIMIT_EXCEEDED` (§6.3: "A **terminal**, receiver-local **policy**
1765
+ * rejection") — well-formed bytes the receiver's cap refuses.
1766
+ *
1767
+ * They are latched together and **kept apart by their code**, which is the
1768
+ * distinction §6.3 requires: a limit rejection "**MUST NOT** be reported as
1769
+ * `InvalidMessage`", so the code is re-raised as itself and each stays the
1770
+ * refusal it was.
1771
+ *
1772
+ * Latching is not bookkeeping, it is the terminality: both rejections are
1773
+ * raised *mid-field* — the UTF-8 check inside a payload piece, a cap inside the
1774
+ * count or length callback — so the machine is left at a position the visitor
1775
+ * never finished. Resume it and the refused field's own bytes are re-read as
1776
+ * headers, delivering fields that were never on the wire.
1777
+ *
1778
+ * The rejection is written here by {@link latch} and nowhere else: this
1779
+ * machine's own malformation findings arrive through {@link fail}, and the ones
1780
+ * raised above it — the §6.4.5 UTF-8 verdict, and the receiver caps §6.2.1
1781
+ * keeps out of this codec — arrive as a throw out of a visitor callback, caught
1782
+ * once in {@link push}.
1783
+ */
1784
+ this.refusal = null;
1785
+ /**
1786
+ * A `DataView` over the chunk currently being fed, and the chunk it addresses —
1787
+ * the **language-forced handle** of CORELIB_PLAN §6.6.2, and the only way
1788
+ * JavaScript lets a reader take an IEEE-754 value from a byte offset. Without it
1789
+ * a float costs four or eight byte loads, a shift ladder and a round trip
1790
+ * through a scratch word; with it, one call.
1791
+ *
1792
+ * It qualifies because it carries no message bytes (it addresses the *caller's*
1793
+ * chunk) and no wire number sizes it (its extent is the chunk's). Built lazily
1794
+ * and only where it pays: a float **array** whose remaining run inside this chunk
1795
+ * clears {@link FP32_HANDLE_MIN} / {@link FP64_HANDLE_MIN}. A scalar float, a
1796
+ * short array, a message with no float at all, and a byte-at-a-time feed each
1797
+ * build none. Once built it is kept while the same chunk is being fed, and it
1798
+ * never leaves this class.
1799
+ */
1800
+ this.view = null;
1801
+ this.viewOf = null;
1802
+ /** The current field's id. */
1164
1803
  this.id = 0;
1165
- // Resumable varint accumulator, as two unsigned 32-bit halves (vLo / vHi)
1166
- // plus the byte count so far. Number-only: a `bigint` is built once, at the
1167
- // end, and only for full 64-bit *values* (not ids, lengths or counts).
1804
+ // Resumable varint accumulator, as two unsigned 32-bit halves (vLo / vHi) plus
1805
+ // the byte count so far. Number-only: a `bigint` is built once, at the end, and
1806
+ // only for full 64-bit *values* (never for ids, lengths or counts).
1168
1807
  this.vLo = 0;
1169
1808
  this.vHi = 0;
1170
1809
  this.vBytes = 0;
1171
1810
  this.vComplete = false;
1172
- // fixlen / fp scratch
1173
- this.scratch = new Uint8Array(8);
1811
+ /**
1812
+ * Resumable fp32 / fp64 accumulator, as two little-endian 32-bit words rather
1813
+ * than a byte array: a typed array would be a per-decoder allocation, and two
1814
+ * number fields hold the same 8 bytes. Byte `k` lands in bits `8*k` of `fpLo`
1815
+ * (k < 4) or of `fpHi`, so the pair is already in wire (little-endian) order.
1816
+ */
1817
+ this.fpLo = 0;
1818
+ this.fpHi = 0;
1174
1819
  this.need = 0;
1175
1820
  this.have = 0;
1176
1821
  // fixlen string/blob streaming
@@ -1182,98 +1827,249 @@ var DecoderState = class {
1182
1827
  this.arrIsFixlen = false;
1183
1828
  this.arrCount = 0;
1184
1829
  this.arrIndex = 0;
1185
- this.maxArrayCount = limits?.maxArrayCount ?? Infinity;
1186
- this.maxStringLen = limits?.maxStringLen ?? Infinity;
1187
- this.maxBlobLen = limits?.maxBlobLen ?? Infinity;
1830
+ /**
1831
+ * The destination the visitor handed over for the array being decoded, or
1832
+ * `null` while no hand-off is in force — which is every array the visitor
1833
+ * declined, and every array at all for a visitor that declares no
1834
+ * {@link Visitor.arrayBulk}.
1835
+ *
1836
+ * **The one reference this machine keeps into the caller's storage between
1837
+ * `feed` calls.** Everything else it holds past a callback is its own (§6.6):
1838
+ * a payload is reported as coordinates into the caller's chunk and never
1839
+ * retained. An array that straddles chunks has to remember where its elements
1840
+ * go, so this lives from the hand-off to `arrayEnd` — and is dropped there,
1841
+ * by {@link endArray}, and by {@link release} for a machine going back to the
1842
+ * pool.
1843
+ */
1844
+ this.bulk = null;
1845
+ /** Which destination {@link bulk} named; meaningless while it is `null`. */
1846
+ this.bulkMode = 0 /* Values */;
1847
+ /**
1848
+ * The `Uint32Array` over a 64-bit typed destination (see {@link BM.Typed64}),
1849
+ * or over an `f32` destination once it has taken a NaN (see {@link f32StoreWord}).
1850
+ */
1851
+ this.bulk64 = null;
1852
+ this.root = visitor;
1853
+ this.cur = visitor;
1854
+ this.begin(visitor);
1188
1855
  }
1189
- /** Feed `input` to the machine, dispatching to `root` and its sub-visitors. */
1190
- push(input, root) {
1191
- if (this.stack.length === 0) this.stack.push(root);
1192
- let i = 0;
1856
+ /**
1857
+ * (Re)bind this machine to a visitor, clearing every trace of whatever it
1858
+ * decoded before.
1859
+ *
1860
+ * Constructing a decoder is the one allocating step (§6.6), and the one-shot
1861
+ * {@link decode} would otherwise pay it per message — which on a 37-byte message
1862
+ * is most of the cost. So {@link decode} keeps one machine and re-binds it here;
1863
+ * this method is what makes that indistinguishable from a fresh one.
1864
+ *
1865
+ * **Only the fields a fresh decode can *read* are cleared**, and the list is
1866
+ * exhaustive by construction rather than by inspection: every other field is
1867
+ * written before it is read, on every path that reads it — `id` at each header,
1868
+ * `vLo`/`vHi` by whichever varint reader ran (a fresh accumulation starts from
1869
+ * zero because `vBytes` is 0), `vComplete` by the `varintStep` whose result is
1870
+ * being tested, `fpLo`/`fpHi`/`need` by {@link fpBegin}, `fix*` by
1871
+ * {@link fixlenWord}, `arrKind`/`arrIsFixlen` by {@link dispatch} and
1872
+ * `arrCount`/`arrIndex` by the count word and `bulkMode` by the hand-off the
1873
+ * same word makes (`bulk` *is* cleared: it is the caller's storage, and a
1874
+ * machine that starts a fresh decode must not still be pointing at the last
1875
+ * one's), `seqIds[d]` when the scope at `d`
1876
+ * opens. `have` is the one exception and *is* cleared: the `S.ArrayFp` bulk loop
1877
+ * reads it to decide whether an element is half-arrived.
1878
+ *
1879
+ * `view`/`viewOf` are not cleared either, and deliberately: {@link dataView}
1880
+ * keys the cached handle on the chunk it addresses, so a stale one is rebuilt the
1881
+ * moment a different chunk arrives and reused — correctly — when the same buffer
1882
+ * is decoded again. {@link release} still drops it, which is where it matters:
1883
+ * a pooled machine must not keep the caller's last chunk alive between calls.
1884
+ *
1885
+ * Clearing them all anyway cost 5573 → 5324 Ir/op on `decode: typical message`
1886
+ * (~4.5%), which is what a 21-field wipe costs when the message is 37 bytes. The
1887
+ * invariant is held by `pooled-decoder-state.test.ts`, which aborts a decode in
1888
+ * every construct and then reuses the machine.
1889
+ */
1890
+ begin(visitor) {
1891
+ this.root = visitor;
1892
+ this.cur = visitor;
1893
+ this.skipFrom = -1;
1894
+ this.depth = 0;
1895
+ this.state = 0 /* Header */;
1896
+ this.refusal = null;
1897
+ this.vBytes = 0;
1898
+ this.have = 0;
1899
+ this.bulk = null;
1900
+ this.bulk64 = null;
1901
+ }
1902
+ /**
1903
+ * Drop the references a pooled machine would otherwise keep alive: the caller's
1904
+ * visitor, and the handle onto the caller's chunk.
1905
+ */
1906
+ release() {
1907
+ this.root = SKIP;
1908
+ this.cur = SKIP;
1909
+ this.view = null;
1910
+ this.viewOf = null;
1911
+ this.bulk = null;
1912
+ this.bulk64 = null;
1913
+ }
1914
+ /** Feed `input` to the machine, dispatching to the bound visitor. */
1915
+ push(input) {
1916
+ const latched = this.refusal;
1917
+ if (latched !== null) throw new SofabError(latched.code, latched.message);
1918
+ try {
1919
+ this.run(input);
1920
+ } catch (e) {
1921
+ if (this.refusal === null && e instanceof SofabError && (e.code === SofabErrorCode.InvalidMsg || e.code === SofabErrorCode.LimitExceeded || e.code === SofabErrorCode.Argument)) {
1922
+ this.latch(e);
1923
+ }
1924
+ throw e;
1925
+ }
1926
+ }
1927
+ /**
1928
+ * The decode loop itself. {@link push} wraps it, so the terminal-refusal latch
1929
+ * is applied in exactly one place — including to a rejection the visitor raised
1930
+ * — and this stays the plain state machine.
1931
+ */
1932
+ run(input) {
1193
1933
  const n = input.length;
1934
+ let i = 0;
1194
1935
  while (i < n) {
1936
+ if (this.state === 0 /* Header */ && this.vBytes === 0) {
1937
+ let h;
1938
+ const hb = input[i];
1939
+ if (hb < 128) {
1940
+ this.vLo = hb;
1941
+ this.vHi = 0;
1942
+ h = i + 1;
1943
+ } else h = this.varintQuick(input, i, n);
1944
+ if (h >= 0) {
1945
+ i = h;
1946
+ const type = this.vLo & 7;
1947
+ const id = this.vHi === 0 ? this.vLo >>> 3 : this.vUpper();
1948
+ if (id > ID_MAX) this.fail(`field id ${id} out of range`);
1949
+ if (type === WireType.SequenceEnd) {
1950
+ this.endSequence();
1951
+ continue;
1952
+ }
1953
+ this.id = id;
1954
+ this.cur.fieldBegin?.(id, type);
1955
+ if (type === WireType.Unsigned) {
1956
+ let v;
1957
+ const b0 = i < n ? input[i] : 128;
1958
+ if (b0 < 128) {
1959
+ this.vLo = b0;
1960
+ this.vHi = 0;
1961
+ v = i + 1;
1962
+ } else v = this.varintQuick(input, i, n);
1963
+ if (v < 0) {
1964
+ this.state = 1 /* ScalarU */;
1965
+ continue;
1966
+ }
1967
+ i = v;
1968
+ const lo = this.vLo >>> 0;
1969
+ const hi = this.vHi >>> 0;
1970
+ this.cur.unsigned?.(
1971
+ id,
1972
+ hi <= 2097151 ? hi * TWO32 + lo : joinU64(lo, hi),
1973
+ lo,
1974
+ hi
1975
+ );
1976
+ continue;
1977
+ }
1978
+ if (type === WireType.Signed) {
1979
+ let v;
1980
+ const b0 = i < n ? input[i] : 128;
1981
+ if (b0 < 128) {
1982
+ this.vLo = b0;
1983
+ this.vHi = 0;
1984
+ v = i + 1;
1985
+ } else v = this.varintQuick(input, i, n);
1986
+ if (v < 0) {
1987
+ this.state = 2 /* ScalarS */;
1988
+ continue;
1989
+ }
1990
+ i = v;
1991
+ const lo = this.vLo >>> 0;
1992
+ const hi = this.vHi >>> 0;
1993
+ const mask = -(lo & 1) >>> 0;
1994
+ this.cur.signed?.(
1995
+ id,
1996
+ this.vSigned(),
1997
+ ((lo >>> 1 | hi << 31) >>> 0 ^ mask) >>> 0,
1998
+ (hi >>> 1 ^ mask) >>> 0
1999
+ );
2000
+ continue;
2001
+ }
2002
+ if (type === WireType.Fixlen) {
2003
+ const w = this.varintQuick(input, i, n);
2004
+ if (w < 0) {
2005
+ this.state = 3 /* FixlenWord */;
2006
+ continue;
2007
+ }
2008
+ i = this.fixlenWord(input, w, n);
2009
+ continue;
2010
+ }
2011
+ this.dispatch(type);
2012
+ continue;
2013
+ }
2014
+ }
1195
2015
  switch (this.state) {
1196
2016
  case 0 /* Header */: {
1197
2017
  i = this.varintStep(input, i);
1198
2018
  if (!this.vComplete) return;
1199
- const type = this.vTag();
2019
+ const type = this.vLo & 7;
2020
+ const id = this.vUpper();
2021
+ if (id > ID_MAX) this.fail(`field id ${id} out of range`);
1200
2022
  if (type === WireType.SequenceEnd) {
1201
- this.resetVarint();
1202
2023
  this.endSequence();
1203
2024
  break;
1204
2025
  }
1205
- const id = this.vUpper();
1206
- this.resetVarint();
1207
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
1208
2026
  this.id = id;
2027
+ this.cur.fieldBegin?.(id, type);
1209
2028
  this.dispatch(type);
1210
2029
  break;
1211
2030
  }
1212
2031
  case 1 /* ScalarU */: {
1213
2032
  i = this.varintStep(input, i);
1214
2033
  if (!this.vComplete) return;
1215
- const value = this.vUnsigned();
1216
- this.resetVarint();
1217
- this.top().unsigned?.(this.id, value);
1218
2034
  this.state = 0 /* Header */;
2035
+ this.cur.unsigned?.(this.id, this.vUnsigned(), this.vLo >>> 0, this.vHi >>> 0);
1219
2036
  break;
1220
2037
  }
1221
2038
  case 2 /* ScalarS */: {
1222
2039
  i = this.varintStep(input, i);
1223
2040
  if (!this.vComplete) return;
1224
- const value = this.vSigned();
1225
- this.resetVarint();
1226
- this.top().signed?.(this.id, value);
1227
2041
  this.state = 0 /* Header */;
2042
+ const lo = this.vLo >>> 0;
2043
+ const hi = this.vHi >>> 0;
2044
+ const mask = -(lo & 1) >>> 0;
2045
+ this.cur.signed?.(
2046
+ this.id,
2047
+ this.vSigned(),
2048
+ ((lo >>> 1 | hi << 31) >>> 0 ^ mask) >>> 0,
2049
+ (hi >>> 1 ^ mask) >>> 0
2050
+ );
1228
2051
  break;
1229
2052
  }
1230
- case 3 /* FixlenLen */: {
2053
+ case 3 /* FixlenWord */: {
1231
2054
  i = this.varintStep(input, i);
1232
2055
  if (!this.vComplete) return;
1233
- const sub = this.vTag();
1234
- const len = this.vUpper();
1235
- this.resetVarint();
1236
- if (sub > FixlenSubtype.Blob) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1237
- if (len > FIXLEN_MAX) throw invalidMsgError("fixlen length out of range");
1238
- if (sub === FixlenSubtype.String && len > this.maxStringLen) {
1239
- throw limitExceededError(`string length ${len} exceeds maxStringLen ${this.maxStringLen}`);
1240
- }
1241
- if (sub === FixlenSubtype.Blob && len > this.maxBlobLen) {
1242
- throw limitExceededError(`blob length ${len} exceeds maxBlobLen ${this.maxBlobLen}`);
1243
- }
1244
- this.fixSub = sub;
1245
- this.fixLen = len;
1246
- this.fixOff = 0;
1247
- if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
1248
- const want = sub === FixlenSubtype.Fp32 ? 4 : 8;
1249
- if (this.fixLen !== want) throw invalidMsgError("fixlen float length mismatch");
1250
- this.need = want;
1251
- this.have = 0;
1252
- this.state = 4 /* FixlenFp */;
1253
- } else {
1254
- if (this.fixLen === 0) {
1255
- this.emitBytes(input.subarray(0, 0));
1256
- this.state = 0 /* Header */;
1257
- } else {
1258
- this.state = 5 /* FixlenBytes */;
1259
- }
1260
- }
2056
+ i = this.fixlenWord(input, i, n);
1261
2057
  break;
1262
2058
  }
1263
2059
  case 4 /* FixlenFp */: {
1264
- i = this.fpStep(input, i);
2060
+ i = this.fpStep(input, i, n);
1265
2061
  if (this.have < this.need) return;
1266
- const value = this.fixSub === FixlenSubtype.Fp32 ? unpackFp32(this.scratch, 0) : unpackFp64(this.scratch, 0);
1267
- if (this.fixSub === FixlenSubtype.Fp32) {
1268
- const top = this.top();
1269
- top.fp32?.(this.id, value, top.fp32Raw ? this.scratch.subarray(0, 4) : void 0);
1270
- } else this.top().fp64?.(this.id, value);
1271
2062
  this.state = 0 /* Header */;
2063
+ if (this.fixSub === FixlenSubtype.Fp32) {
2064
+ this.cur.fp32?.(this.id, fp32FromBits(this.fpLo), this.fpLo >>> 0);
2065
+ } else {
2066
+ this.cur.fp64?.(this.id, fp64FromBits(this.fpLo, this.fpHi));
2067
+ }
1272
2068
  break;
1273
2069
  }
1274
2070
  case 5 /* FixlenBytes */: {
1275
2071
  const take = Math.min(n - i, this.fixLen - this.fixOff);
1276
- this.emitBytes(input.subarray(i, i + take));
2072
+ this.emitBytes(input, i, i + take);
1277
2073
  i += take;
1278
2074
  this.fixOff += take;
1279
2075
  if (this.fixOff === this.fixLen) this.state = 0 /* Header */;
@@ -1283,77 +2079,95 @@ var DecoderState = class {
1283
2079
  i = this.varintStep(input, i);
1284
2080
  if (!this.vComplete) return;
1285
2081
  const count = this.vNum();
1286
- this.resetVarint();
1287
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1288
- if (count > this.maxArrayCount) {
1289
- throw limitExceededError(`array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`);
1290
- }
2082
+ if (count > ARRAY_MAX) this.fail("array count out of range");
1291
2083
  this.arrCount = count;
1292
2084
  this.arrIndex = 0;
1293
2085
  if (this.arrIsFixlen) {
1294
- this.state = 9 /* ArrayElemLen */;
2086
+ this.state = 8 /* ArrayElemWord */;
1295
2087
  } else if (count === 0) {
1296
- this.top().arrayBegin?.(this.id, this.arrKind, 0);
1297
- this.top().arrayEnd?.(this.id);
1298
- this.state = 0 /* Header */;
2088
+ this.cur.arrayBegin?.(this.id, this.arrKind, 0);
2089
+ this.askBulk(this.arrKind, 0);
2090
+ this.endArray();
1299
2091
  } else {
1300
- this.top().arrayBegin?.(this.id, this.arrKind, this.arrCount);
1301
- this.state = this.arrKind === ArrayKind.Unsigned ? 7 /* ArrayUElem */ : 8 /* ArraySElem */;
2092
+ this.state = 7 /* ArrayElem */;
2093
+ this.cur.arrayBegin?.(this.id, this.arrKind, count);
2094
+ this.askBulk(this.arrKind, count);
1302
2095
  }
1303
2096
  break;
1304
2097
  }
1305
- case 7 /* ArrayUElem */: {
1306
- i = this.varintStep(input, i);
1307
- if (!this.vComplete) return;
1308
- const value = this.vUnsigned();
1309
- this.resetVarint();
1310
- this.top().arrayUnsigned?.(this.id, this.arrIndex, value);
1311
- this.advanceArray();
1312
- break;
1313
- }
1314
- case 8 /* ArraySElem */: {
2098
+ case 7 /* ArrayElem */: {
2099
+ const count = this.arrCount;
2100
+ const safeEnd = n - VARINT_MAX_BYTES;
2101
+ if (this.bulk !== null) {
2102
+ i = this.arrKind === ArrayKind.Unsigned ? this.uBulkArm(input, i, n, count, safeEnd) : this.sBulkArm(input, i, n, count, safeEnd);
2103
+ break;
2104
+ }
2105
+ let idx = this.arrIndex;
2106
+ if (this.vBytes === 0) {
2107
+ while (idx < count && i <= safeEnd) {
2108
+ i = this.varintFull(input, i);
2109
+ idx++;
2110
+ }
2111
+ this.arrIndex = idx;
2112
+ }
2113
+ if (idx === count) {
2114
+ this.state = 0 /* Header */;
2115
+ this.cur.arrayEnd?.(this.id);
2116
+ break;
2117
+ }
2118
+ if (i >= n) break;
1315
2119
  i = this.varintStep(input, i);
1316
2120
  if (!this.vComplete) return;
1317
- const value = this.vSigned();
1318
- this.resetVarint();
1319
- this.top().arraySigned?.(this.id, this.arrIndex, value);
1320
2121
  this.advanceArray();
1321
2122
  break;
1322
2123
  }
1323
- case 9 /* ArrayElemLen */: {
2124
+ case 8 /* ArrayElemWord */: {
1324
2125
  i = this.varintStep(input, i);
1325
2126
  if (!this.vComplete) return;
1326
- const sub = this.vTag();
2127
+ const sub = this.vLo & 7;
1327
2128
  const size = this.vUpper();
1328
- this.resetVarint();
1329
2129
  if (sub === FixlenSubtype.Fp32 && size === 4) {
1330
2130
  this.arrKind = ArrayKind.Fp32;
1331
- this.need = 4;
2131
+ this.fpBegin(4);
1332
2132
  } else if (sub === FixlenSubtype.Fp64 && size === 8) {
1333
2133
  this.arrKind = ArrayKind.Fp64;
1334
- this.need = 8;
2134
+ this.fpBegin(8);
1335
2135
  } else {
1336
- throw invalidMsgError("invalid fixlen array element type");
2136
+ this.fail("invalid fixlen array element type");
1337
2137
  }
1338
- this.top().arrayBegin?.(this.id, this.arrKind, this.arrCount);
1339
2138
  if (this.arrCount === 0) {
1340
- this.top().arrayEnd?.(this.id);
1341
- this.state = 0 /* Header */;
2139
+ this.cur.arrayBegin?.(this.id, this.arrKind, 0);
2140
+ this.askBulk(this.arrKind, 0);
2141
+ this.endArray();
1342
2142
  } else {
1343
- this.have = 0;
1344
- this.state = 10 /* ArrayFp */;
2143
+ this.state = 9 /* ArrayFp */;
2144
+ this.cur.arrayBegin?.(this.id, this.arrKind, this.arrCount);
2145
+ this.askBulk(this.arrKind, this.arrCount);
1345
2146
  }
1346
2147
  break;
1347
2148
  }
1348
- case 10 /* ArrayFp */: {
1349
- i = this.fpStep(input, i);
2149
+ case 9 /* ArrayFp */: {
2150
+ const count = this.arrCount;
2151
+ const size = this.need;
2152
+ if (this.bulk !== null) {
2153
+ const is32 = this.arrKind === ArrayKind.Fp32;
2154
+ i = this.fpBulkArm(input, i, n, count, size, is32);
2155
+ break;
2156
+ }
2157
+ if (this.have === 0) {
2158
+ const run = Math.min(count - this.arrIndex, (n - i) / size | 0);
2159
+ i += run * size;
2160
+ this.arrIndex += run;
2161
+ }
2162
+ if (this.arrIndex === count) {
2163
+ this.state = 0 /* Header */;
2164
+ this.cur.arrayEnd?.(this.id);
2165
+ break;
2166
+ }
2167
+ if (i >= n) break;
2168
+ i = this.fpStep(input, i, n);
1350
2169
  if (this.have < this.need) return;
1351
- const value = this.arrKind === ArrayKind.Fp32 ? unpackFp32(this.scratch, 0) : unpackFp64(this.scratch, 0);
1352
- if (this.arrKind === ArrayKind.Fp32) {
1353
- const top = this.top();
1354
- top.arrayFp32?.(this.id, this.arrIndex, value, top.fp32Raw ? this.scratch.subarray(0, 4) : void 0);
1355
- } else this.top().arrayFp64?.(this.id, this.arrIndex, value);
1356
- this.have = 0;
2170
+ this.fpBegin(size);
1357
2171
  this.advanceArray();
1358
2172
  break;
1359
2173
  }
@@ -1361,20 +2175,104 @@ var DecoderState = class {
1361
2175
  }
1362
2176
  }
1363
2177
  /**
1364
- * Report the terminal decode outcome (MESSAGE_SPEC §7) *without* promoting it
1365
- * to an error. Returns {@link DecodeStatus.Complete} when the stream ended
1366
- * exactly at a field boundary, or {@link DecodeStatus.Incomplete} when it
1367
- * ended inside a field (a partial varint, an unfinished payload / array, or a
1368
- * still-open nested sequence). This is a pure accessor — the finish-less spec
1369
- * has no finalize step, and a trailing `Incomplete` is a truncation the caller
1370
- * decides how to treat, not an error this machine raises. A genuinely
1371
- * malformed message has already thrown from {@link push}.
2178
+ * Where the decode stands (§5.2.1), *without* promoting it to an error:
2179
+ * {@link DecodeStatus.Complete} when the stream ended exactly at a field
2180
+ * boundary, {@link DecodeStatus.Incomplete} when it ended inside a field (a
2181
+ * partial varint, an unfinished payload / array, or a still-open nested
2182
+ * sequence). A trailing `Incomplete` is a truncation the caller decides how to
2183
+ * treat (§5.2.4), not an error this machine raises.
2184
+ *
2185
+ * **Only these two, and only on a healthy machine.** This is read in exactly
2186
+ * one place — after a {@link push} that returned — and a push that met a
2187
+ * terminal refusal does not return: it throws, this call is never reached, and
2188
+ * the verdict travels out on the error it threw. So `Invalid` is not a value
2189
+ * this can produce, and neither is the "refused by a cap" state the outcome
2190
+ * triple cannot name (§6.3). Nothing here re-reports a latched refusal, because
2191
+ * nothing needs to: the throw is the whole report, and a report with one
2192
+ * carrier has nothing to drift out of step with.
2193
+ *
2194
+ * The cursor's own answer would be wrong for a refused stream, which is why the
2195
+ * refusal must not fall through to it: a cap is compared in `arrayBegin` /
2196
+ * `fixlenBegin`, raised with the header and the count / length word consumed and
2197
+ * the payload not yet entered — a cursor that reads as a clean field boundary,
2198
+ * and so as `Complete`. {@link push}'s latch is what keeps that unreachable.
1372
2199
  */
1373
- finish() {
1374
- const atBoundary = this.state === 0 /* Header */ && this.vBytes === 0 && this.stack.length <= 1;
2200
+ outcome() {
2201
+ const atBoundary = this.state === 0 /* Header */ && this.vBytes === 0 && this.depth === 0;
1375
2202
  return atBoundary ? DecodeStatus.Complete : DecodeStatus.Incomplete;
1376
2203
  }
1377
2204
  // --- helpers ------------------------------------------------------------
2205
+ /**
2206
+ * Reject the input as malformed: latch the terminal `INVALID` verdict and throw
2207
+ * `INVALID_MSG`. Every malformation *this machine* finds goes through here, so
2208
+ * none of them can be caught and then decoded past — §5.2.1's "no — terminal".
2209
+ * Declared `never` so a call ends control flow exactly like the `throw` it
2210
+ * replaced.
2211
+ */
2212
+ fail(message) {
2213
+ throw this.latch(invalidMsgError(message));
2214
+ }
2215
+ /**
2216
+ * Record `e` as the terminal refusal that stopped this stream, and hand it back
2217
+ * to be thrown. The only writer of {@link refusal} — §5.3.1's one
2218
+ * implementation of the rule — for a rejection raised here and for one raised
2219
+ * above this machine and caught in {@link push} alike. The error is stored, not
2220
+ * its text: the code travels with it, so `INVALID_MSG` and `LIMIT_EXCEEDED`
2221
+ * each stay themselves (§6.3).
2222
+ */
2223
+ latch(e) {
2224
+ this.refusal = e;
2225
+ this.bulk = null;
2226
+ this.bulk64 = null;
2227
+ return e;
2228
+ }
2229
+ /**
2230
+ * Act on a complete `fixlen_word` sitting in the varint accumulator: validate
2231
+ * it, announce the field, and either read the float inline (when its bytes are
2232
+ * in this chunk) or set up the resumable payload state. Shared by the fast lane
2233
+ * and the `S.FixlenWord` arm, so the §4.6 rules exist once.
2234
+ */
2235
+ fixlenWord(input, i, n) {
2236
+ const sub = this.vLo & 7;
2237
+ const len = this.vUpper();
2238
+ if (sub > FixlenSubtype.Blob) this.fail(`invalid fixlen subtype ${sub}`);
2239
+ if (len > FIXLEN_MAX) this.fail("fixlen length out of range");
2240
+ if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
2241
+ const want = sub === FixlenSubtype.Fp32 ? 4 : 8;
2242
+ if (len !== want) this.fail("fixlen float length mismatch");
2243
+ this.fixSub = sub;
2244
+ if (n - i >= want) {
2245
+ this.state = 0 /* Header */;
2246
+ const lo = u32le(input, i);
2247
+ if (want === 4) {
2248
+ this.cur.fp32?.(this.id, fp32FromBits(lo), lo);
2249
+ } else {
2250
+ this.cur.fp64?.(this.id, fp64FromBits(lo, u32le(input, i + 4)));
2251
+ }
2252
+ return i + want;
2253
+ }
2254
+ this.fpBegin(want);
2255
+ this.state = 4 /* FixlenFp */;
2256
+ return i;
2257
+ }
2258
+ this.fixSub = sub;
2259
+ this.fixLen = len;
2260
+ this.fixOff = 0;
2261
+ this.cur.fixlenBegin?.(this.id, this.fixSub, len);
2262
+ if (len === 0) {
2263
+ this.emitBytes(input, i, i);
2264
+ this.state = 0 /* Header */;
2265
+ return i;
2266
+ }
2267
+ const take = Math.min(n - i, len);
2268
+ if (take > 0) {
2269
+ this.emitBytes(input, i, i + take);
2270
+ this.fixOff = take;
2271
+ i += take;
2272
+ }
2273
+ this.state = this.fixOff === len ? 0 /* Header */ : 5 /* FixlenBytes */;
2274
+ return i;
2275
+ }
1378
2276
  dispatch(type) {
1379
2277
  switch (type) {
1380
2278
  case WireType.Unsigned:
@@ -1384,7 +2282,7 @@ var DecoderState = class {
1384
2282
  this.state = 2 /* ScalarS */;
1385
2283
  break;
1386
2284
  case WireType.Fixlen:
1387
- this.state = 3 /* FixlenLen */;
2285
+ this.state = 3 /* FixlenWord */;
1388
2286
  break;
1389
2287
  case WireType.ArrayUnsigned:
1390
2288
  this.arrKind = ArrayKind.Unsigned;
@@ -1400,778 +2298,1293 @@ var DecoderState = class {
1400
2298
  this.arrIsFixlen = true;
1401
2299
  this.state = 6 /* ArrayCount */;
1402
2300
  break;
1403
- case WireType.SequenceStart: {
1404
- if (this.stack.length - 1 >= MAX_DEPTH) {
1405
- throw invalidMsgError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
1406
- }
1407
- const child = this.top().sequenceBegin?.(this.id);
1408
- this.stack.push(child ?? this.top());
1409
- this.state = 0 /* Header */;
2301
+ case WireType.SequenceStart:
2302
+ this.beginSequence();
1410
2303
  break;
1411
- }
1412
2304
  default:
1413
- throw invalidMsgError(`invalid wire type ${type}`);
2305
+ this.fail(`invalid wire type ${type}`);
2306
+ }
2307
+ }
2308
+ /**
2309
+ * Open a nested sequence: offer it to the visitor, note its id, and descend.
2310
+ *
2311
+ * A visitor that answers `false` declines the whole subtree — no callback of
2312
+ * any kind fires inside it, its own {@link Visitor.sequenceEnd} included, and a
2313
+ * scope opened within it is never offered either. The subtree is still *parsed*
2314
+ * (a sequence is framed by markers, not by a length, so its end has to be
2315
+ * found) and every format ceiling still applies; what stops is delivery.
2316
+ */
2317
+ beginSequence() {
2318
+ const d = this.depth;
2319
+ if (d >= MAX_DEPTH) this.fail(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
2320
+ if (this.cur !== SKIP && this.root.sequenceBegin?.(this.id, d + 1) === false) {
2321
+ this.skipFrom = d;
2322
+ this.cur = SKIP;
1414
2323
  }
2324
+ this.seqIds[d] = this.id;
2325
+ this.depth = d + 1;
2326
+ this.state = 0 /* Header */;
1415
2327
  }
1416
2328
  endSequence() {
1417
- if (this.stack.length <= 1) throw invalidMsgError("unbalanced sequence end");
1418
- this.top().sequenceEnd?.();
1419
- this.stack.pop();
2329
+ const d = this.depth;
2330
+ if (d === 0) this.fail("unbalanced sequence end");
1420
2331
  this.state = 0 /* Header */;
2332
+ const closed = d - 1;
2333
+ this.depth = closed;
2334
+ if (this.skipFrom >= 0) {
2335
+ if (this.skipFrom === closed) {
2336
+ this.skipFrom = -1;
2337
+ this.cur = this.root;
2338
+ }
2339
+ return;
2340
+ }
2341
+ this.root.sequenceEnd?.(this.seqIds[closed], d);
1421
2342
  }
1422
2343
  advanceArray() {
1423
- this.arrIndex++;
1424
- if (this.arrIndex === this.arrCount) {
1425
- this.top().arrayEnd?.(this.id);
2344
+ if (++this.arrIndex === this.arrCount) {
1426
2345
  this.state = 0 /* Header */;
2346
+ this.cur.arrayEnd?.(this.id);
1427
2347
  }
1428
2348
  }
1429
- emitBytes(chunk) {
1430
- const v = this.top();
1431
- if (this.fixSub === FixlenSubtype.String) v.string?.(this.id, this.fixLen, this.fixOff, chunk);
1432
- else v.blob?.(this.id, this.fixLen, this.fixOff, chunk);
2349
+ /**
2350
+ * Close an array delivered through the hand-off: back to the header state, drop
2351
+ * the visitor's destination, announce the end. Every bulk array ends here, so
2352
+ * the reference into the caller's storage cannot outlive the array it was made
2353
+ * for (§6.6; see {@link bulk}).
2354
+ *
2355
+ * The per-element arms keep their own two lines instead of calling this: they
2356
+ * can never hold a destination — the hand-off's arms have already taken over
2357
+ * before they run — and the call showed up on `decode: typical`.
2358
+ */
2359
+ endArray() {
2360
+ this.state = 0 /* Header */;
2361
+ const t = this.bulk;
2362
+ if (t !== null) this.trimPlain(t, this.arrIndex);
2363
+ this.bulk = null;
2364
+ this.bulk64 = null;
2365
+ this.cur.arrayEnd?.(this.id);
2366
+ }
2367
+ /**
2368
+ * Cut a plain-array destination to the `written` elements this array actually
2369
+ * put in it, so a destination reused across arrays — the shape the hand-off
2370
+ * exists for — can never hand back the previous array's tail, and its `length`
2371
+ * always means "elements of *this* array".
2372
+ *
2373
+ * At the end rather than at the hand-off, and that is measured: clearing it up
2374
+ * front turns every element write into a grow (`array<u16>` 181 583 -> 231 815
2375
+ * Ir/op, worse than the per-element path it replaces), where one length store
2376
+ * per array costs nothing. A pre-sized destination — the fast shape, every write
2377
+ * in bounds — is left exactly as it was.
2378
+ *
2379
+ * The typed destinations are not trimmed and cannot be: their length is the
2380
+ * caller's allocation, checked against `count` at the hand-off, and `count` is
2381
+ * how far this fill wrote.
2382
+ */
2383
+ trimPlain(t, written) {
2384
+ const mode = this.bulkMode;
2385
+ if (mode !== 0 /* Values */ && mode !== 1 /* Values32 */ && mode !== 5 /* Longs */) return;
2386
+ const out = mode === 5 /* Longs */ ? t.longs : t.values;
2387
+ if (out.length > written) out.length = written;
1433
2388
  }
1434
- top() {
1435
- return this.stack[this.stack.length - 1];
2389
+ /**
2390
+ * Offer the bulk hand-off for the array that just began, and resolve the answer
2391
+ * once (CORELIB_PLAN §5.3.1's one implementation, and {@link ArrayTarget}'s
2392
+ * contract): after this, the element loops know which destination to write to
2393
+ * from {@link bulkMode} and re-decide nothing per element.
2394
+ *
2395
+ * Raised after `arrayBegin` and before the first element, so a receiver cap on
2396
+ * the count (§6.2.1) is still compared in `arrayBegin` and a rejected array is
2397
+ * never offered. A visitor that declares no `arrayBulk` pays one short-circuited
2398
+ * optional call per array.
2399
+ *
2400
+ * **An empty array is offered too**, with `count` of 0. There is nothing to
2401
+ * write, but there is something to say: a destination held across fields would
2402
+ * otherwise still be holding the last array's elements, and its length is the
2403
+ * only place this one's emptiness could show up (see {@link trimPlain}).
2404
+ */
2405
+ askBulk(kind, count) {
2406
+ const t = this.cur.arrayBulk?.(this.id, kind, count) ?? null;
2407
+ if (t === null) {
2408
+ this.bulk = null;
2409
+ this.bulk64 = null;
2410
+ return;
2411
+ }
2412
+ this.bulk64 = null;
2413
+ this.bulkMode = this.resolveTarget(t, kind, count);
2414
+ this.bulk = t;
1436
2415
  }
1437
2416
  /**
1438
- * Consume varint bytes from `input` at `i` into the {@link vLo} / {@link vHi}
1439
- * accumulator, resuming across chunk boundaries; sets {@link vComplete} when a
1440
- * terminator byte arrives. Number-only — no per-byte `bigint`.
2417
+ * Which destination `t` names — or an `Argument` refusal if it names none, more
2418
+ * than one, one that contradicts the array's element kind, or one too short to
2419
+ * hold `count` elements.
2420
+ *
2421
+ * These are caller mistakes rather than message verdicts, so they are
2422
+ * `InvalidArgument` (§6.3) and not `INVALID_MSG`: the same bytes decode fine for
2423
+ * a visitor that hands over a destination it can actually fill. Checked once per
2424
+ * array, which is why the fill loops need no guard of their own.
1441
2425
  */
1442
- varintStep(input, i) {
1443
- let lo = this.vLo;
1444
- let hi = this.vHi;
1445
- let k = this.vBytes;
1446
- const n = input.length;
1447
- while (i < n) {
1448
- if (k >= VARINT_MAX_BYTES) throw invalidMsgError("varint overflow");
1449
- const b = input[i++];
1450
- if (k < 4) lo |= (b & 127) << 7 * k;
1451
- else if (k === 4) {
1452
- lo |= (b & 15) << 28;
1453
- hi |= b >> 4 & 7;
1454
- } else {
1455
- if (k === 9 && (b & 127) >> 1 !== 0) throw invalidMsgError("varint overflow");
1456
- hi |= (b & 127) << 7 * k - 32;
2426
+ resolveTarget(t, kind, count) {
2427
+ if (kind === ArrayKind.Fp32 || kind === ArrayKind.Fp64) {
2428
+ const f = t;
2429
+ const is32 = kind === ArrayKind.Fp32;
2430
+ const dest = is32 ? f.f32 ?? f.bits : f.f64;
2431
+ const named2 = (f.f32 !== void 0 ? 1 : 0) + (f.bits !== void 0 ? 1 : 0) + (f.f64 !== void 0 ? 1 : 0) + (t.bool !== void 0 ? 1 : 0);
2432
+ const want = is32 ? "f32 or bits" : "f64";
2433
+ if (dest === void 0 || named2 !== 1) {
2434
+ throw argumentError(
2435
+ `array ${this.id}: an ${is32 ? "fp32" : "fp64"} array needs exactly the ${want} destination`
2436
+ );
1457
2437
  }
1458
- k++;
1459
- if ((b & 128) === 0) {
1460
- this.vLo = lo;
1461
- this.vHi = hi;
1462
- this.vBytes = k;
1463
- this.vComplete = true;
1464
- return i;
2438
+ if (dest.length < count) {
2439
+ throw argumentError(
2440
+ `array ${this.id}: ${is32 ? "fp32" : "fp64"} destination holds ${dest.length} of ${count} elements`
2441
+ );
1465
2442
  }
2443
+ if (!is32) return 9 /* F64 */;
2444
+ return f.bits !== void 0 ? 8 /* F32Bits */ : 7 /* F32 */;
1466
2445
  }
1467
- this.vLo = lo;
1468
- this.vHi = hi;
1469
- this.vBytes = k;
1470
- this.vComplete = false;
1471
- return i;
2446
+ const bt = t;
2447
+ if (bt.bool !== void 0) {
2448
+ const other = t;
2449
+ const float = t;
2450
+ if (other.values !== void 0 || other.longs !== void 0 || other.typed !== void 0 || other.lo !== void 0 || other.hi !== void 0 || float.f32 !== void 0 || float.bits !== void 0 || float.f64 !== void 0) {
2451
+ throw argumentError(`array ${this.id}: an array target needs exactly one destination`);
2452
+ }
2453
+ if (kind !== ArrayKind.Unsigned) {
2454
+ throw argumentError(`array ${this.id}: a bool destination needs an unsigned array`);
2455
+ }
2456
+ if (bt.bool.length < count) {
2457
+ throw argumentError(
2458
+ `array ${this.id}: bool destination holds ${bt.bool.length} of ${count} elements`
2459
+ );
2460
+ }
2461
+ return 4 /* Bool */;
2462
+ }
2463
+ const it = t;
2464
+ const halves = it.lo !== void 0 || it.hi !== void 0;
2465
+ const named = (it.values !== void 0 ? 1 : 0) + (it.longs !== void 0 ? 1 : 0) + (it.typed !== void 0 ? 1 : 0) + (halves ? 1 : 0);
2466
+ if (named !== 1) {
2467
+ throw argumentError(
2468
+ `array ${this.id}: an integer array target needs exactly one destination (values, typed, longs, or lo+hi), got ${named}`
2469
+ );
2470
+ }
2471
+ if (it.minLo >>> 0 !== it.minLo || it.minHi >>> 0 !== it.minHi || it.maxLo >>> 0 !== it.maxLo || it.maxHi >>> 0 !== it.maxHi) {
2472
+ throw argumentError(
2473
+ `array ${this.id}: the element bound must be four unsigned 32-bit halves`
2474
+ );
2475
+ }
2476
+ const signed = kind === ArrayKind.Signed;
2477
+ const minHi = signed ? it.minHi | 0 : it.minHi;
2478
+ const maxHi = signed ? it.maxHi | 0 : it.maxHi;
2479
+ if (minHi > maxHi || minHi === maxHi && it.minLo > it.maxLo) {
2480
+ throw argumentError(
2481
+ `array ${this.id}: the element bound is empty (min ${it.minHi}:${it.minLo} > max ${it.maxHi}:${it.maxLo})`
2482
+ );
2483
+ }
2484
+ if (it.typed !== void 0) {
2485
+ return kind === ArrayKind.Signed ? this.typedModeS(it, it.typed, kind, count) : this.typedModeU(it, it.typed, kind, count);
2486
+ }
2487
+ if (halves) {
2488
+ const lo = it.lo;
2489
+ const hi = it.hi;
2490
+ if (lo === void 0 || hi === void 0) {
2491
+ throw argumentError(`array ${this.id}: the halves destination needs both lo and hi`);
2492
+ }
2493
+ if (lo.length < count || hi.length < count) {
2494
+ throw argumentError(
2495
+ `array ${this.id}: halves destination holds ${Math.min(lo.length, hi.length)} of ${count} elements`
2496
+ );
2497
+ }
2498
+ return 6 /* Halves */;
2499
+ }
2500
+ if (it.longs !== void 0) {
2501
+ if (!Array.isArray(it.longs)) {
2502
+ throw argumentError(`array ${this.id}: the longs destination must be an Array`);
2503
+ }
2504
+ return 5 /* Longs */;
2505
+ }
2506
+ if (!Array.isArray(it.values)) {
2507
+ throw argumentError(`array ${this.id}: the values destination must be an Array`);
2508
+ }
2509
+ return it.minHi === 0 && it.maxHi === 0 ? 1 /* Values32 */ : 0 /* Values */;
1472
2510
  }
1473
- resetVarint() {
1474
- this.vLo = 0;
1475
- this.vHi = 0;
1476
- this.vBytes = 0;
2511
+ /** The typed-destination check of {@link resolveTarget} for an unsigned array. */
2512
+ typedModeU(it, d, kind, count) {
2513
+ if (d.length < count) {
2514
+ throw argumentError(
2515
+ `array ${this.id}: typed destination holds ${d.length} of ${count} elements`
2516
+ );
2517
+ }
2518
+ const cap = typedCapacity(d.constructor);
2519
+ const signed = kind === ArrayKind.Signed;
2520
+ if ((cap === void 0 || cap.max === Number.POSITIVE_INFINITY) && is64(d)) {
2521
+ if (signed !== d instanceof BigInt64Array) {
2522
+ throw argumentError(
2523
+ `array ${this.id}: a 64-bit typed destination must match the array's signedness`
2524
+ );
2525
+ }
2526
+ this.bulk64 = new Uint32Array(d.buffer, d.byteOffset, d.length * 2);
2527
+ return 3 /* Typed64 */;
2528
+ }
2529
+ const minV = signed ? (it.minHi | 0) * TWO32 + it.minLo : it.minHi * TWO32 + it.minLo;
2530
+ const maxV = signed ? (it.maxHi | 0) * TWO32 + it.maxLo : it.maxHi * TWO32 + it.maxLo;
2531
+ if (cap === void 0) {
2532
+ throw argumentError(`array ${this.id}: unsupported typed destination`);
2533
+ }
2534
+ if (minV < cap.min || maxV > cap.max) {
2535
+ throw argumentError(
2536
+ `array ${this.id}: the element bound ${minV}..${maxV} does not fit the typed destination (${cap.min}..${cap.max})`
2537
+ );
2538
+ }
2539
+ return 2 /* Typed */;
2540
+ }
2541
+ /** The signed twin of {@link typedModeU}: textually identical, for its own inline caches. */
2542
+ typedModeS(it, d, kind, count) {
2543
+ if (d.length < count) {
2544
+ throw argumentError(
2545
+ `array ${this.id}: typed destination holds ${d.length} of ${count} elements`
2546
+ );
2547
+ }
2548
+ const cap = typedCapacity(d.constructor);
2549
+ const signed = kind === ArrayKind.Signed;
2550
+ if ((cap === void 0 || cap.max === Number.POSITIVE_INFINITY) && is64(d)) {
2551
+ if (signed !== d instanceof BigInt64Array) {
2552
+ throw argumentError(
2553
+ `array ${this.id}: a 64-bit typed destination must match the array's signedness`
2554
+ );
2555
+ }
2556
+ this.bulk64 = new Uint32Array(d.buffer, d.byteOffset, d.length * 2);
2557
+ return 3 /* Typed64 */;
2558
+ }
2559
+ const minV = signed ? (it.minHi | 0) * TWO32 + it.minLo : it.minHi * TWO32 + it.minLo;
2560
+ const maxV = signed ? (it.maxHi | 0) * TWO32 + it.maxLo : it.maxHi * TWO32 + it.maxLo;
2561
+ if (cap === void 0) {
2562
+ throw argumentError(`array ${this.id}: unsupported typed destination`);
2563
+ }
2564
+ if (minV < cap.min || maxV > cap.max) {
2565
+ throw argumentError(
2566
+ `array ${this.id}: the element bound ${minV}..${maxV} does not fit the typed destination (${cap.min}..${cap.max})`
2567
+ );
2568
+ }
2569
+ return 2 /* Typed */;
2570
+ }
2571
+ /**
2572
+ * The whole `S.ArrayUElem` arm for an array whose destination was handed over:
2573
+ * drain what this chunk holds, store a straddling tail element, close the array
2574
+ * when it ends. Returns the new read position; the caller's `break` then either
2575
+ * re-enters this state for the next chunk or leaves it, exactly as before.
2576
+ *
2577
+ * **Out of line, for the reason {@link fpDrain} already gives.** Everything
2578
+ * written into {@link push}'s switch is paid for by every decode that never
2579
+ * reaches it, so this arm is three lines at the call site and a method here.
2580
+ * Carrying its body in the switch instead cost `decode: typical` 5092 -> 5099
2581
+ * Ir/op and `decode: u64 array` 705.0k -> 708.5k; giving each bulk arm a state
2582
+ * of its own — which keeps the per-element arms untouched but adds three labels
2583
+ * — cost 5163 on `typical`, worse than either. What is left is what the
2584
+ * hand-off costs a decode that never takes it: 0.34% (5075 -> 5092, 702.5k ->
2585
+ * 705.0k), in the loop's own size.
2586
+ *
2587
+ * Suspension needs no signal of its own: a varint that did not complete consumed
2588
+ * the chunk to its end, so the returned position is `n` and the decode loop exits
2589
+ * on its own condition.
2590
+ *
2591
+ * **One loop per destination**, chosen once (see {@link bulkMode}) rather than
2592
+ * branched on per element: the shapes differ only in what a stored element *is*,
2593
+ * and a loop deciding that per element would give back what the hand-off saves.
2594
+ * `arrIndex` is likewise written once per drain instead of once per element,
2595
+ * which is part of why a bulk fill costs less than *discarding* the same
2596
+ * elements. A refusal mid-loop leaves it at the last committed value; nothing
2597
+ * reads it afterwards, because that verdict is terminal (§5.2.1).
2598
+ */
2599
+ uBulkArm(input, i, n, count, safeEnd) {
2600
+ const t = this.bulk;
2601
+ const mode = this.bulkMode;
2602
+ const minLo = t.minLo;
2603
+ const minHi = t.minHi;
2604
+ const maxLo = t.maxLo;
2605
+ const maxHi = t.maxHi;
2606
+ for (; ; ) {
2607
+ if (this.vBytes === 0) {
2608
+ let idx = this.arrIndex;
2609
+ if (mode === 1 /* Values32 */) {
2610
+ const out = t.values;
2611
+ while (idx < count && i <= safeEnd) {
2612
+ i = this.varintFull(input, i);
2613
+ const lo = this.vLo >>> 0;
2614
+ if (this.vHi !== 0 || lo < minLo || lo > maxLo) this.outOfBound(idx);
2615
+ out[idx++] = lo;
2616
+ }
2617
+ } else if (mode === 2 /* Typed */) {
2618
+ const out = t.typed;
2619
+ while (idx < count && i <= safeEnd) {
2620
+ i = this.varintFull(input, i);
2621
+ const lo = this.vLo >>> 0;
2622
+ if (this.vHi !== 0 || lo < minLo || lo > maxLo) this.outOfBound(idx);
2623
+ out[idx++] = lo;
2624
+ }
2625
+ } else if (mode === 3 /* Typed64 */) {
2626
+ const out = this.bulk64;
2627
+ while (idx < count && i <= safeEnd) {
2628
+ i = this.varintFull(input, i);
2629
+ const lo = this.vLo >>> 0;
2630
+ const hi = this.vHi >>> 0;
2631
+ if (hi < minHi || hi === minHi && lo < minLo || hi > maxHi || hi === maxHi && lo > maxLo) {
2632
+ this.outOfBound(idx);
2633
+ }
2634
+ out[idx * 2 + LO] = lo;
2635
+ out[idx * 2 + HI] = hi;
2636
+ idx++;
2637
+ }
2638
+ } else if (mode === 4 /* Bool */) {
2639
+ const out = this.bulk.bool;
2640
+ while (idx < count && i <= safeEnd) {
2641
+ i = this.varintFull(input, i);
2642
+ out[idx++] = this.vLo !== 0 || this.vHi !== 0 ? 1 : 0;
2643
+ }
2644
+ } else if (mode === 0 /* Values */) {
2645
+ const out = t.values;
2646
+ while (idx < count && i <= safeEnd) {
2647
+ i = this.varintFull(input, i);
2648
+ const lo = this.vLo >>> 0;
2649
+ const hi = this.vHi >>> 0;
2650
+ if (hi < minHi || hi === minHi && lo < minLo || hi > maxHi || hi === maxHi && lo > maxLo) {
2651
+ this.outOfBound(idx);
2652
+ }
2653
+ out[idx++] = hi <= 2097151 ? hi * TWO32 + lo : joinU64(lo, hi);
2654
+ }
2655
+ } else if (mode === 5 /* Longs */) {
2656
+ const out = t.longs;
2657
+ while (idx < count && i <= safeEnd) {
2658
+ i = this.varintFull(input, i);
2659
+ const lo = this.vLo >>> 0;
2660
+ const hi = this.vHi >>> 0;
2661
+ if (hi < minHi || hi === minHi && lo < minLo || hi > maxHi || hi === maxHi && lo > maxLo) {
2662
+ this.outOfBound(idx);
2663
+ }
2664
+ out[idx++] = new Long(lo, hi);
2665
+ }
2666
+ } else {
2667
+ const oLo = t.lo;
2668
+ const oHi = t.hi;
2669
+ while (idx < count && i <= safeEnd) {
2670
+ i = this.varintFull(input, i);
2671
+ const lo = this.vLo >>> 0;
2672
+ const hi = this.vHi >>> 0;
2673
+ if (hi < minHi || hi === minHi && lo < minLo || hi > maxHi || hi === maxHi && lo > maxLo) {
2674
+ this.outOfBound(idx);
2675
+ }
2676
+ oLo[idx] = lo;
2677
+ oHi[idx] = hi;
2678
+ idx++;
2679
+ }
2680
+ }
2681
+ this.arrIndex = idx;
2682
+ }
2683
+ if (this.arrIndex === count) {
2684
+ this.endArray();
2685
+ return i;
2686
+ }
2687
+ if (i >= n) return i;
2688
+ i = this.varintStep(input, i);
2689
+ if (!this.vComplete) return i;
2690
+ this.bulkStoreU(this.arrIndex, this.vLo >>> 0, this.vHi >>> 0);
2691
+ if (++this.arrIndex === count) {
2692
+ this.endArray();
2693
+ return i;
2694
+ }
2695
+ }
2696
+ }
2697
+ /** The signed twin of {@link uBulkArm}: the same shape, with the zig-zag undone. */
2698
+ sBulkArm(input, i, n, count, safeEnd) {
2699
+ const t = this.bulk;
2700
+ const mode = this.bulkMode;
2701
+ const minLo = t.minLo;
2702
+ const minHi = t.minHi | 0;
2703
+ const maxLo = t.maxLo;
2704
+ const maxHi = t.maxHi | 0;
2705
+ for (; ; ) {
2706
+ if (this.vBytes === 0) {
2707
+ let idx = this.arrIndex;
2708
+ while (idx < count && i <= safeEnd) {
2709
+ i = this.varintFull(input, i);
2710
+ const raw = this.vLo >>> 0;
2711
+ const rawHi = this.vHi >>> 0;
2712
+ const mask = -(raw & 1) >>> 0;
2713
+ const lo = ((raw >>> 1 | rawHi << 31) >>> 0 ^ mask) >>> 0;
2714
+ const hi = (rawHi >>> 1 ^ mask) >>> 0;
2715
+ const shi = hi | 0;
2716
+ if (shi < minHi || shi === minHi && lo < minLo || shi > maxHi || shi === maxHi && lo > maxLo) {
2717
+ this.outOfBound(idx);
2718
+ }
2719
+ if (mode === 2 /* Typed */) {
2720
+ t.typed[idx] = lo | 0;
2721
+ } else if (mode === 3 /* Typed64 */) {
2722
+ const o = this.bulk64;
2723
+ o[idx * 2 + LO] = lo;
2724
+ o[idx * 2 + HI] = hi;
2725
+ } else if (mode === 0 /* Values */ || mode === 1 /* Values32 */) {
2726
+ let v;
2727
+ if (rawHi <= 2097151) {
2728
+ const r = rawHi * TWO32 + raw;
2729
+ v = r % 2 === 0 ? r / 2 : -(r + 1) / 2;
2730
+ } else {
2731
+ v = joinI64(lo, hi);
2732
+ }
2733
+ t.values[idx] = v;
2734
+ } else if (mode === 5 /* Longs */) {
2735
+ t.longs[idx] = new Long(lo, hi);
2736
+ } else {
2737
+ t.lo[idx] = lo;
2738
+ t.hi[idx] = hi;
2739
+ }
2740
+ idx++;
2741
+ }
2742
+ this.arrIndex = idx;
2743
+ }
2744
+ if (this.arrIndex === count) {
2745
+ this.endArray();
2746
+ return i;
2747
+ }
2748
+ if (i >= n) return i;
2749
+ i = this.varintStep(input, i);
2750
+ if (!this.vComplete) return i;
2751
+ this.bulkStoreS(this.arrIndex, this.vLo >>> 0, this.vHi >>> 0);
2752
+ if (++this.arrIndex === count) {
2753
+ this.endArray();
2754
+ return i;
2755
+ }
2756
+ }
2757
+ }
2758
+ /** The float twin of {@link uBulkArm}; a straddling element resumes through {@link fpStep}. */
2759
+ fpBulkArm(input, i, n, count, size, isFp32) {
2760
+ if (this.have === 0 && this.arrIndex < count && n - i >= size) {
2761
+ const t = this.bulk;
2762
+ const run = Math.min(count - this.arrIndex, (n - i) / size | 0);
2763
+ let idx = this.arrIndex;
2764
+ const bitsOut = this.bulkMode === 8 /* F32Bits */ ? t.bits : null;
2765
+ if (run >= (isFp32 ? FP32_HANDLE_MIN : FP64_HANDLE_MIN)) {
2766
+ const dv = this.dataView(input);
2767
+ if (bitsOut !== null) {
2768
+ for (let k = 0; k < run; k++) {
2769
+ bitsOut[idx++] = dv.getUint32(i, true);
2770
+ i += 4;
2771
+ }
2772
+ } else if (isFp32) {
2773
+ const out = t.f32;
2774
+ for (let k = 0; k < run; k++) {
2775
+ const v = dv.getFloat32(i, true);
2776
+ if (v === v) out[idx] = v;
2777
+ else this.f32StoreWord(out, idx, dv.getUint32(i, true));
2778
+ idx++;
2779
+ i += 4;
2780
+ }
2781
+ } else {
2782
+ const out = t.f64;
2783
+ for (let k = 0; k < run; k++) {
2784
+ out[idx++] = dv.getFloat64(i, true);
2785
+ i += 8;
2786
+ }
2787
+ }
2788
+ } else if (bitsOut !== null) {
2789
+ for (let k = 0; k < run; k++) {
2790
+ bitsOut[idx++] = u32le(input, i);
2791
+ i += 4;
2792
+ }
2793
+ } else if (isFp32) {
2794
+ const out = t.f32;
2795
+ for (let k = 0; k < run; k++) {
2796
+ const w = u32le(input, i);
2797
+ if ((w & 2147483647) > 2139095040) this.f32StoreWord(out, idx, w);
2798
+ else out[idx] = fp32FromBits(w);
2799
+ idx++;
2800
+ i += 4;
2801
+ }
2802
+ } else {
2803
+ const out = t.f64;
2804
+ for (let k = 0; k < run; k++) {
2805
+ out[idx++] = fp64FromBits(u32le(input, i), u32le(input, i + 4));
2806
+ i += 8;
2807
+ }
2808
+ }
2809
+ this.arrIndex = idx;
2810
+ }
2811
+ if (this.arrIndex === count) {
2812
+ this.endArray();
2813
+ return i;
2814
+ }
2815
+ if (i >= n) return i;
2816
+ i = this.fpStep(input, i, n);
2817
+ if (this.have < this.need) return i;
2818
+ const lo = this.fpLo;
2819
+ const hi = this.fpHi;
2820
+ this.fpBegin(size);
2821
+ this.bulkStoreFp(this.arrIndex, lo, hi, isFp32);
2822
+ if (++this.arrIndex === count) this.endArray();
2823
+ return i;
2824
+ }
2825
+ /**
2826
+ * Store an fp32 NaN into a `Float32Array` destination by its wire word (§4.6).
2827
+ * Widening a NaN to a double quiets a signaling one (and an engine may purify
2828
+ * the payload of any NaN it reads from a typed array), so a NaN never goes
2829
+ * through a value: it is written through a word view over the destination's own
2830
+ * storage. Every other fp32 survives the double exactly, which is why the view
2831
+ * is built lazily, on the array's first NaN, and never on the common path —
2832
+ * touching `.buffer` moves a small typed array's storage off the heap. It is
2833
+ * kept in {@link bulk64} for the rest of the array, so the count is one per
2834
+ * array however many NaNs the wire carries (§6.6.2).
2835
+ */
2836
+ f32StoreWord(out, idx, word) {
2837
+ let w = this.bulk64;
2838
+ if (w === null) w = this.bulk64 = new Uint32Array(out.buffer, out.byteOffset, out.length);
2839
+ w[idx] = word;
2840
+ }
2841
+ /** Store one float element that straddled a chunk boundary (see {@link bulkStoreU}). */
2842
+ bulkStoreFp(idx, lo, hi, isFp32) {
2843
+ const t = this.bulk;
2844
+ if (!isFp32) t.f64[idx] = fp64FromBits(lo, hi);
2845
+ else if (this.bulkMode === 8 /* F32Bits */) t.bits[idx] = lo >>> 0;
2846
+ else if ((lo & 2147483647) > 2139095040) this.f32StoreWord(t.f32, idx, lo >>> 0);
2847
+ else t.f32[idx] = fp32FromBits(lo);
2848
+ }
2849
+ /**
2850
+ * Store one unsigned element that straddled a chunk boundary — the tail a drain
2851
+ * loop cannot take, resumed from the varint accumulator. At most one per chunk,
2852
+ * so it re-decides the destination rather than duplicating three loops.
2853
+ */
2854
+ bulkStoreU(idx, lo, hi) {
2855
+ const t = this.bulk;
2856
+ if (hi < t.minHi || hi === t.minHi && lo < t.minLo || hi > t.maxHi || hi === t.maxHi && lo > t.maxLo) {
2857
+ this.outOfBound(idx);
2858
+ }
2859
+ if (this.bulkMode === 0 /* Values */ || this.bulkMode === 1 /* Values32 */) {
2860
+ t.values[idx] = this.vUnsigned();
2861
+ } else if (this.bulkMode === 2 /* Typed */) {
2862
+ t.typed[idx] = lo;
2863
+ } else if (this.bulkMode === 3 /* Typed64 */) {
2864
+ const o = this.bulk64;
2865
+ o[idx * 2 + LO] = lo;
2866
+ o[idx * 2 + HI] = hi;
2867
+ } else if (this.bulkMode === 4 /* Bool */) {
2868
+ this.bulk.bool[idx] = lo !== 0 || hi !== 0 ? 1 : 0;
2869
+ } else if (this.bulkMode === 5 /* Longs */) {
2870
+ t.longs[idx] = new Long(lo, hi);
2871
+ } else {
2872
+ t.lo[idx] = lo;
2873
+ t.hi[idx] = hi;
2874
+ }
2875
+ }
2876
+ /** The signed twin of {@link bulkStoreU}; `raw`/`rawHi` are the zig-zag halves. */
2877
+ bulkStoreS(idx, raw, rawHi) {
2878
+ const t = this.bulk;
2879
+ const mask = -(raw & 1) >>> 0;
2880
+ const lo = ((raw >>> 1 | rawHi << 31) >>> 0 ^ mask) >>> 0;
2881
+ const hi = (rawHi >>> 1 ^ mask) >>> 0;
2882
+ const shi = hi | 0;
2883
+ if (shi < (t.minHi | 0) || shi === (t.minHi | 0) && lo < t.minLo || shi > (t.maxHi | 0) || shi === (t.maxHi | 0) && lo > t.maxLo) {
2884
+ this.outOfBound(idx);
2885
+ }
2886
+ if (this.bulkMode === 0 /* Values */ || this.bulkMode === 1 /* Values32 */) {
2887
+ t.values[idx] = this.vSigned();
2888
+ } else if (this.bulkMode === 2 /* Typed */) t.typed[idx] = lo | 0;
2889
+ else if (this.bulkMode === 3 /* Typed64 */) {
2890
+ const o = this.bulk64;
2891
+ o[idx * 2 + LO] = lo;
2892
+ o[idx * 2 + HI] = hi;
2893
+ } else if (this.bulkMode === 5 /* Longs */) t.longs[idx] = new Long(lo, hi);
2894
+ else {
2895
+ t.lo[idx] = lo;
2896
+ t.hi[idx] = hi;
2897
+ }
2898
+ }
2899
+ /**
2900
+ * Refuse an element outside the bound its target declared (§7.3): the message
2901
+ * says a thing the schema does not allow, so it is `INVALID` and terminal, the
2902
+ * same verdict at the same point as a generated per-element guard raises today.
2903
+ * The destination keeps everything written before this element — see
2904
+ * {@link ArrayTarget}.
2905
+ */
2906
+ outOfBound(index) {
2907
+ const t = this.bulk;
2908
+ if (t !== null) this.trimPlain(t, index);
2909
+ this.fail(`array ${this.id}: element ${index} outside the schema bound`);
2910
+ }
2911
+ /**
2912
+ * Report one payload piece: the caller's own fed chunk plus the coordinates of
2913
+ * the piece inside it (§6.6.3). No view is created — this decoder allocates
2914
+ * nothing (§6.6) and exposes no borrowed slice of its own (§6.7); `src` is the
2915
+ * very array the caller passed to `feed`, so whoever wants the bytes copies
2916
+ * them out of memory it already owns, during the call.
2917
+ */
2918
+ emitBytes(src, start, end) {
2919
+ const v = this.cur;
2920
+ if (this.fixSub === FixlenSubtype.String) {
2921
+ v.string?.(this.id, this.fixLen, this.fixOff, src, start, end);
2922
+ } else {
2923
+ v.blob?.(this.id, this.fixLen, this.fixOff, src, start, end);
2924
+ }
2925
+ }
2926
+ /**
2927
+ * Consume varint bytes from `input` at `i` into the {@link vLo} / {@link vHi}
2928
+ * accumulator, resuming across chunk boundaries; sets {@link vComplete} when a
2929
+ * terminator byte arrives. Number-only — no per-byte `bigint`.
2930
+ */
2931
+ varintStep(input, i) {
2932
+ if (this.vBytes === 0) {
2933
+ const n0 = input.length;
2934
+ const b0 = input[i];
2935
+ if (b0 < 128) {
2936
+ this.vLo = b0;
2937
+ this.vHi = 0;
2938
+ this.vComplete = true;
2939
+ return i + 1;
2940
+ }
2941
+ if (i + 1 < n0) {
2942
+ const b1 = input[i + 1];
2943
+ if (b1 < 128) {
2944
+ this.vLo = b0 & 127 | b1 << 7;
2945
+ this.vHi = 0;
2946
+ this.vComplete = true;
2947
+ return i + 2;
2948
+ }
2949
+ if (i + 2 < n0) {
2950
+ const b2 = input[i + 2];
2951
+ if (b2 < 128) {
2952
+ this.vLo = b0 & 127 | (b1 & 127) << 7 | b2 << 14;
2953
+ this.vHi = 0;
2954
+ this.vComplete = true;
2955
+ return i + 3;
2956
+ }
2957
+ }
2958
+ }
2959
+ if (n0 - i >= VARINT_MAX_BYTES) return this.varintFull(input, i);
2960
+ }
2961
+ const k0 = this.vBytes;
2962
+ let lo = k0 === 0 ? 0 : this.vLo;
2963
+ let hi = k0 === 0 ? 0 : this.vHi;
2964
+ let k = k0;
2965
+ const n = input.length;
2966
+ while (i < n) {
2967
+ if (k >= VARINT_MAX_BYTES) this.fail("varint overflow");
2968
+ const b = input[i++];
2969
+ if (k < 4) lo |= (b & 127) << 7 * k;
2970
+ else if (k === 4) {
2971
+ lo |= (b & 15) << 28;
2972
+ hi |= b >> 4 & 7;
2973
+ } else {
2974
+ if (k === 9 && (b & 127) >> 1 !== 0) this.fail("varint overflow");
2975
+ hi |= (b & 127) << 7 * k - 32;
2976
+ }
2977
+ k++;
2978
+ if ((b & 128) === 0) {
2979
+ this.vLo = lo;
2980
+ this.vHi = hi;
2981
+ this.vBytes = 0;
2982
+ this.vComplete = true;
2983
+ return i;
2984
+ }
2985
+ }
2986
+ if (k >= VARINT_MAX_BYTES) this.fail("varint overflow");
2987
+ this.vLo = lo;
2988
+ this.vHi = hi;
2989
+ this.vBytes = k;
1477
2990
  this.vComplete = false;
2991
+ return i;
1478
2992
  }
1479
- /** The accumulated varint as a `bigint` (full 64-bit fidelity). */
1480
- vBig() {
1481
- return this.vHi === 0 ? BigInt(this.vLo >>> 0) : BigInt(this.vHi >>> 0) << 32n | BigInt(this.vLo >>> 0);
2993
+ /**
2994
+ * Decode the varint at `i` **if that needs no resume bookkeeping**, returning
2995
+ * the index past it, or `-1` when it does (leaving the accumulator untouched,
2996
+ * so the resumable ladder starts the word from scratch).
2997
+ *
2998
+ * Three cases, in the order they are worth testing:
2999
+ *
3000
+ * * ten bytes in hand — the unrolled {@link varintFull}, no bounds checks at
3001
+ * all;
3002
+ * * a one-byte varint — every small id, length, count and scalar;
3003
+ * * a two-byte one — every id past 15, and mid-sized lengths and counts.
3004
+ *
3005
+ * Past that the word may straddle the chunk, and only the ladder can carry the
3006
+ * state across `feed` calls.
3007
+ */
3008
+ varintQuick(input, i, n) {
3009
+ if (n - i >= VARINT_MAX_BYTES) return this.varintFull(input, i);
3010
+ if (i >= n) return -1;
3011
+ const b0 = input[i];
3012
+ if (b0 < 128) return this.setVarint(b0, 0, i + 1);
3013
+ if (i + 1 < n) {
3014
+ const b1 = input[i + 1];
3015
+ if (b1 < 128) return this.setVarint(b0 & 127 | b1 << 7, 0, i + 2);
3016
+ if (i + 2 < n) {
3017
+ const b2 = input[i + 2];
3018
+ if (b2 < 128) {
3019
+ return this.setVarint(b0 & 127 | (b1 & 127) << 7 | b2 << 14, 0, i + 3);
3020
+ }
3021
+ }
3022
+ }
3023
+ return -1;
1482
3024
  }
1483
3025
  /**
1484
- * The accumulated varint as an unsigned value, number-first: a `number` when
1485
- * it fits exactly (`≤ 2^53-1`, which covers all ids, u8..u32 and small u64s),
1486
- * a `bigint` only beyond that. Avoids a bigint allocation on the common path.
3026
+ * Decode one varint that is **guaranteed** to lie wholly within `input` — the
3027
+ * caller has checked that {@link VARINT_MAX_BYTES} bytes remain — into
3028
+ * {@link vLo} / {@link vHi}, returning the index past it.
3029
+ *
3030
+ * Unrolled and branch-per-byte: with the bytes known to be present there is no
3031
+ * bounds check, no resume counter and no `k`-dispatch per byte, which is the
3032
+ * whole per-byte cost of the resumable loop above. Reports the same `>64-bit`
3033
+ * overflow as that loop.
3034
+ */
3035
+ varintFull(input, i) {
3036
+ let b = input[i];
3037
+ let lo = b & 127;
3038
+ let hi = 0;
3039
+ if (b < 128) return this.setVarint(lo, 0, i + 1);
3040
+ b = input[i + 1];
3041
+ lo |= (b & 127) << 7;
3042
+ if (b < 128) return this.setVarint(lo, 0, i + 2);
3043
+ b = input[i + 2];
3044
+ lo |= (b & 127) << 14;
3045
+ if (b < 128) return this.setVarint(lo, 0, i + 3);
3046
+ b = input[i + 3];
3047
+ lo |= (b & 127) << 21;
3048
+ if (b < 128) return this.setVarint(lo, 0, i + 4);
3049
+ b = input[i + 4];
3050
+ lo |= (b & 15) << 28;
3051
+ hi = b >> 4 & 7;
3052
+ if (b < 128) return this.setVarint(lo, hi, i + 5);
3053
+ b = input[i + 5];
3054
+ hi |= (b & 127) << 3;
3055
+ if (b < 128) return this.setVarint(lo, hi, i + 6);
3056
+ b = input[i + 6];
3057
+ hi |= (b & 127) << 10;
3058
+ if (b < 128) return this.setVarint(lo, hi, i + 7);
3059
+ b = input[i + 7];
3060
+ hi |= (b & 127) << 17;
3061
+ if (b < 128) return this.setVarint(lo, hi, i + 8);
3062
+ b = input[i + 8];
3063
+ hi |= (b & 127) << 24;
3064
+ if (b < 128) return this.setVarint(lo, hi, i + 9);
3065
+ b = input[i + 9];
3066
+ if ((b & 127) >> 1 !== 0) this.fail("varint overflow");
3067
+ hi |= (b & 127) << 31;
3068
+ if (b < 128) return this.setVarint(lo, hi, i + 10);
3069
+ this.fail("varint overflow");
3070
+ }
3071
+ /** Publish a fully-decoded varint and the cursor past it (see {@link varintFull}). */
3072
+ setVarint(lo, hi, i) {
3073
+ this.vLo = lo;
3074
+ this.vHi = hi;
3075
+ this.vBytes = 0;
3076
+ this.vComplete = true;
3077
+ return i;
3078
+ }
3079
+ /**
3080
+ * The accumulated varint as an unsigned value, number-first: a `number` when it
3081
+ * fits exactly (`≤ 2^53-1`, which covers all ids, u8..u32 and small u64s), a
3082
+ * `bigint` only beyond that.
1487
3083
  */
1488
3084
  vUnsigned() {
1489
3085
  const hi = this.vHi >>> 0;
1490
- return hi <= 2097151 ? hi * TWO322 + (this.vLo >>> 0) : this.vBig();
3086
+ return hi <= 2097151 ? hi * TWO32 + (this.vLo >>> 0) : joinU64(this.vLo >>> 0, hi);
1491
3087
  }
1492
3088
  /** The accumulated zig-zag varint as a signed value, number-first (see {@link vUnsigned}). */
1493
3089
  vSigned() {
1494
3090
  const hi = this.vHi >>> 0;
1495
3091
  if (hi <= 2097151) {
1496
- const r = hi * TWO322 + (this.vLo >>> 0);
3092
+ const r = hi * TWO32 + (this.vLo >>> 0);
1497
3093
  return r % 2 === 0 ? r / 2 : -(r + 1) / 2;
1498
3094
  }
1499
- return zigzagDecode(this.vBig());
3095
+ const lo = this.vLo >>> 0;
3096
+ const mask = -(lo & 1) >>> 0;
3097
+ return joinI64(
3098
+ ((lo >>> 1 | hi << 31) >>> 0 ^ mask) >>> 0,
3099
+ (hi >>> 1 ^ mask) >>> 0
3100
+ );
1500
3101
  }
1501
- /** The accumulated varint as a JS number — exact for ids/lengths/counts. */
3102
+ /**
3103
+ * The accumulated varint as a JS number — exact for ids/lengths/counts.
3104
+ *
3105
+ * The `>>> 0` is load-bearing: `vHi` is accumulated with 32-bit bitwise ops, so
3106
+ * bit 63 of the varint lands on its sign bit and the value reads back negative,
3107
+ * sliding past the `count > ARRAY_MAX` guard.
3108
+ */
1502
3109
  vNum() {
1503
- return this.vHi * TWO322 + (this.vLo >>> 0);
1504
- }
1505
- /** The accumulated varint's low 3 tag bits (the wire type / fixlen subtype). */
1506
- vTag() {
1507
- return this.vLo & 7;
3110
+ return (this.vHi >>> 0) * TWO32 + (this.vLo >>> 0);
1508
3111
  }
1509
3112
  /** The accumulated varint with its low 3 tag bits stripped (`value >> 3`). */
1510
3113
  vUpper() {
1511
- return (this.vHi >>> 0) * (TWO322 / 8) + (this.vLo >>> 3);
3114
+ return (this.vHi >>> 0) * (TWO32 / 8) + (this.vLo >>> 3);
1512
3115
  }
1513
- /** Accumulate `need` raw bytes into {@link scratch}. */
1514
- fpStep(input, i) {
1515
- while (this.have < this.need && i < input.length) {
1516
- this.scratch[this.have++] = input[i++];
3116
+ /**
3117
+ * The handle over `input`, built on demand and reused while the same chunk is
3118
+ * being fed (see {@link view}).
3119
+ */
3120
+ dataView(input) {
3121
+ if (this.viewOf !== input) {
3122
+ this.view = new DataView(input.buffer, input.byteOffset, input.byteLength);
3123
+ this.viewOf = input;
1517
3124
  }
3125
+ return this.view;
3126
+ }
3127
+ /** Accumulate up to `need` raw float bytes into {@link fpLo} / {@link fpHi}. */
3128
+ fpStep(input, i, n) {
3129
+ let have = this.have;
3130
+ const need = this.need;
3131
+ while (have < need && i < n) {
3132
+ const b = input[i++];
3133
+ if (have < 4) this.fpLo |= b << (have << 3);
3134
+ else this.fpHi |= b << (have - 4 << 3);
3135
+ have++;
3136
+ }
3137
+ this.have = have;
1518
3138
  return i;
1519
3139
  }
3140
+ /** Start a fresh fp accumulation of `need` bytes. */
3141
+ fpBegin(need) {
3142
+ this.need = need;
3143
+ this.have = 0;
3144
+ this.fpLo = 0;
3145
+ this.fpHi = 0;
3146
+ }
1520
3147
  };
3148
+ function u32le(b, i) {
3149
+ return (b[i] | b[i + 1] << 8 | b[i + 2] << 16 | b[i + 3] << 24) >>> 0;
3150
+ }
1521
3151
 
1522
3152
  // src/decode/istream.ts
1523
3153
  var IStream = class {
1524
3154
  /**
1525
- * @param limits Optional opt-in decode caps ({@link DecodeLimits}). An
1526
- * over-limit array count or string / blob length throws {@link SofabError}
1527
- * (`LIMIT_EXCEEDED`) from {@link feed}, at the offending field's header and
1528
- * before any of its payload is streamed to the visitor. Omit for no caps.
1529
- */
1530
- constructor(limits) {
1531
- this.state = new DecoderState(limits);
1532
- }
1533
- /**
1534
- * Feed a chunk of bytes, dispatching decoded fields to `visitor`. Throws
1535
- * {@link SofabError} (`INVALID_MSG`) only if the bytes are *malformed*;
1536
- * running out of bytes mid-field is not an error — it simply suspends until
1537
- * the next chunk (see {@link end}).
3155
+ * @param visitor The field handler this stream drives, for its whole life — and
3156
+ * the layer that holds the receiver caps, if any (§6.2.1; see the class doc).
1538
3157
  */
1539
- feed(chunk, visitor) {
1540
- this.state.push(chunk, visitor);
3158
+ constructor(visitor) {
3159
+ this.state = new DecoderState(visitor);
1541
3160
  }
1542
3161
  /**
1543
- * Report whether the stream ended exactly at a field boundary. Call after the
1544
- * final {@link feed}: returns {@link DecodeStatus.Complete} at a clean field
1545
- * boundary, or {@link DecodeStatus.Incomplete} if the last chunk ended inside
1546
- * a field (a partial varint, an unfinished payload / array, or a still-open
1547
- * nested sequence).
3162
+ * Feed a chunk of bytes, dispatching decoded fields to the bound visitor, and
3163
+ * **return** where the decode stands after them (§5.2.1):
3164
+ * {@link DecodeStatus.Complete} when they end exactly at a field boundary,
3165
+ * {@link DecodeStatus.Incomplete} when they end *inside* a field (a partial
3166
+ * varint, an unfinished payload / array, or a still-open nested sequence).
3167
+ * Running out of bytes mid-field is not an error — the decode merely suspends
3168
+ * until the next chunk, and the caller owns end-of-input.
1548
3169
  *
1549
- * Per the finish-less spec (MESSAGE_SPEC §7) this is a pure accessor: it never
1550
- * throws and never promotes an incomplete decode to an error — the caller owns
1551
- * end-of-input and decides whether a trailing `Incomplete` is a truncation
1552
- * error. (A *malformed* message has already thrown from {@link feed}.)
3170
+ * **This call is the only place the answer is.** There is no finish / finalize
3171
+ * step (§5.2.4) and no status accessor: what this returns, or throws, is the
3172
+ * whole of what the stream has to say, so a caller is never one question short
3173
+ * after it and never has two answers to reconcile. Feeding an empty chunk
3174
+ * re-reads the same value without consuming anything, for a caller that wants
3175
+ * the outcome again without holding on to it.
3176
+ *
3177
+ * The chunk is borrowed **only for the duration of this call** (§6.0): once it
3178
+ * returns, the caller may reuse, overwrite or free that memory, and the decoded
3179
+ * message is unaffected — the decoder retains nothing that points into it.
3180
+ *
3181
+ * `INVALID` travels on the error channel — this port's idiomatic surfacing of
3182
+ * it: *malformed* bytes throw {@link SofabError} (`INVALID_MSG`) instead of
3183
+ * returning a status, which is why the return type names only the other two.
3184
+ * That verdict is **terminal** (§5.2.1): the stream latches it, so a caller that
3185
+ * catches the throw and feeds on gets the same error again from every later
3186
+ * call — no further byte is consumed and no visitor method is invoked. A caller
3187
+ * that caught it already holds the verdict, in the code on the error it caught.
3188
+ *
3189
+ * A receiver-limit rejection (`LIMIT_EXCEEDED`, §6.2.1) travels the same
3190
+ * channel — thrown out of the visitor callback that compared the cap — but it
3191
+ * is **not** the `INVALID` outcome and never becomes one: the bytes are
3192
+ * well-formed and the same message decodes under a looser cap, so it is a
3193
+ * policy rejection (§6.2.1, §6.3). The two stay distinguishable by their code,
3194
+ * which is what §6.3 requires; §6.3 leaves the surfacing open between "a fourth
3195
+ * decode outcome" and "a terminal failure carrying the `LimitExceeded` code on
3196
+ * the error channel", and this port takes the second. **Terminal** is the other
3197
+ * half of that sentence and holds exactly as it does for `INVALID`: the stream
3198
+ * latches the rejection, so every later call re-throws it under the same code,
3199
+ * consumes no byte and drives no visitor method. It is *only* on the error
3200
+ * channel — the three-valued outcome has no value for "valid, but more than I am
3201
+ * configured to accept", so there is nothing about it to read back as a status,
3202
+ * and nothing that has to be kept in step with the throw.
1553
3203
  */
1554
- end() {
1555
- return this.state.finish();
3204
+ feed(chunk) {
3205
+ this.state.push(chunk);
3206
+ return this.state.outcome();
1556
3207
  }
1557
3208
  };
1558
- function decode(bytes, visitor, limits) {
1559
- decodeContiguous(bytes, visitor, limits);
3209
+ function decode(bytes, visitor) {
3210
+ const state = pooled ?? new DecoderState();
3211
+ pooled = null;
3212
+ try {
3213
+ state.begin(visitor);
3214
+ state.push(bytes);
3215
+ if (state.outcome() !== DecodeStatus.Complete) {
3216
+ throw incompleteError("truncated message: input ends inside a field");
3217
+ }
3218
+ } finally {
3219
+ state.release();
3220
+ pooled = state;
3221
+ }
1560
3222
  }
3223
+ var pooled = null;
1561
3224
 
1562
- // src/decode/cursor.ts
1563
- var TWO323 = 4294967296;
3225
+ // src/decode/text.ts
1564
3226
  var _utf8 = new TextDecoder("utf-8", { fatal: true });
1565
- var Cursor = class {
1566
- constructor(buf, limits) {
1567
- /** Field id of the header last accepted by {@link readHeader}. */
1568
- this.id = 0;
1569
- /** Wire type of the header last accepted by {@link readHeader}. */
1570
- this.wire = 0;
1571
- /**
1572
- * Fixlen subtype of the header last accepted by {@link readHeader} — one of
1573
- * {@link FixlenSubtype} — when its {@link wire} is {@link WireType.Fixlen} or
1574
- * {@link WireType.ArrayFixlen}; `-1` otherwise (a non-fixlen field, or a
1575
- * fixlen field whose subtype word is truncated away).
1576
- *
1577
- * The four fixlen subtypes (`fp32`, `fp64`, `string`, `blob`) all share one
1578
- * {@link wire} type, so {@link wire} alone cannot separate them. This is the
1579
- * companion accessor that can: a generated guard reads it right after
1580
- * {@link readHeader} to skip a field whose delivered subtype contradicts the
1581
- * schema (MESSAGE_SPEC §7.3), exactly as it already does on {@link wire} for
1582
- * the other kinds:
1583
- *
1584
- * ```ts
1585
- * case 9: if (c.wire !== WireType.Fixlen || c.fixSub !== FixlenSubtype.Fp64) {
1586
- * c.skip(c.wire); break;
1587
- * } o.somefp64 = c.readFp64(); break;
1588
- * ```
1589
- *
1590
- * It is *peeked* — the subtype word is not consumed — so the matching typed
1591
- * reader (or {@link skip}) still reads and validates it, and a malformed or
1592
- * truncated word surfaces `INVALID` / `INCOMPLETE` there as before.
1593
- */
1594
- this.fixSub = -1;
1595
- this.p = 0;
1596
- // Last varint, as two unsigned 32-bit halves (see readVarint).
1597
- this.lo = 0;
1598
- this.hi = 0;
1599
- // Number of nested sequences currently open (0 = root). Incremented when
1600
- // readHeader accepts a SequenceStart, decremented when it consumes the matching
1601
- // SequenceEnd (or when skip() discards a whole nested sequence). Lets the pull
1602
- // parser tell a root-level dangling sequence-end (INVALID) and an unclosed
1603
- // sequence at end-of-buffer (INCOMPLETE) apart from a clean boundary.
1604
- this.depth = 0;
1605
- this.buf = buf;
1606
- this.n = buf.length;
1607
- this.view = new DataView(buf.buffer, buf.byteOffset, buf.length);
1608
- this.maxArrayCount = limits?.maxArrayCount ?? Infinity;
1609
- this.maxStringLen = limits?.maxStringLen ?? Infinity;
1610
- this.maxBlobLen = limits?.maxBlobLen ?? Infinity;
1611
- }
1612
- /**
1613
- * Advance to the next field header. Returns `true` and sets {@link id} /
1614
- * {@link wire} when a field follows; returns `false` — consuming the marker —
1615
- * at the end of the buffer *or* at the sequence-end that closes the sequence
1616
- * this decoder is reading. So a generated per-type decoder loops uniformly:
1617
- *
1618
- * ```ts
1619
- * while (c.readHeader()) {
1620
- * switch (c.id) {
1621
- * case 4: this.u32 = Number(c.readUnsigned()); break;
1622
- * case 10: this.child = Child.decodeFrom(c); break; // nested sequence
1623
- * default: c.skip(c.wire); break; // unknown field
1624
- * }
1625
- * }
1626
- * ```
1627
- *
1628
- * At the root the loop ends at end-of-buffer; inside a nested sequence it ends
1629
- * at the matching {@link WireType.SequenceEnd} (which is consumed). A field
1630
- * whose id is out of range throws {@link SofabError} (`INVALID_MSG`).
1631
- */
1632
- readHeader() {
1633
- if (this.p >= this.n) {
1634
- if (this.depth > 0) {
1635
- throw incompleteError("truncated message: unbalanced sequence");
3227
+ var FLAT_MAX = 16;
3228
+ function decodeUtf8(buf, start = 0, end = buf.length) {
3229
+ const n = end - start;
3230
+ if (n <= 0) return "";
3231
+ if (n <= FLAT_MAX) {
3232
+ let ascii = true;
3233
+ for (let k = start; k < end; k++) {
3234
+ if (buf[k] & 128) {
3235
+ ascii = false;
3236
+ break;
1636
3237
  }
1637
- return false;
1638
3238
  }
1639
- this.readVarint();
1640
- const wire = this.lo & 7;
1641
- if (wire === WireType.SequenceEnd) {
1642
- if (this.depth === 0) {
1643
- throw invalidMsgError("unbalanced sequence end");
1644
- }
1645
- this.depth--;
1646
- return false;
1647
- }
1648
- const id = this.upper();
1649
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
1650
- if (wire === WireType.SequenceStart) {
1651
- if (this.depth >= MAX_DEPTH) {
1652
- throw invalidMsgError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
3239
+ if (ascii) {
3240
+ switch (n) {
3241
+ case 1:
3242
+ return String.fromCharCode(buf[start]);
3243
+ case 2:
3244
+ return String.fromCharCode(buf[start], buf[start + 1]);
3245
+ case 3:
3246
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2]);
3247
+ case 4:
3248
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3]);
3249
+ case 5:
3250
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4]);
3251
+ case 6:
3252
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5]);
3253
+ case 7:
3254
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6]);
3255
+ case 8:
3256
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7]);
3257
+ case 9:
3258
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8]);
3259
+ case 10:
3260
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9]);
3261
+ case 11:
3262
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9], buf[start + 10]);
3263
+ case 12:
3264
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9], buf[start + 10], buf[start + 11]);
3265
+ case 13:
3266
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9], buf[start + 10], buf[start + 11], buf[start + 12]);
3267
+ case 14:
3268
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9], buf[start + 10], buf[start + 11], buf[start + 12], buf[start + 13]);
3269
+ case 15:
3270
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9], buf[start + 10], buf[start + 11], buf[start + 12], buf[start + 13], buf[start + 14]);
3271
+ case 16:
3272
+ return String.fromCharCode(buf[start], buf[start + 1], buf[start + 2], buf[start + 3], buf[start + 4], buf[start + 5], buf[start + 6], buf[start + 7], buf[start + 8], buf[start + 9], buf[start + 10], buf[start + 11], buf[start + 12], buf[start + 13], buf[start + 14], buf[start + 15]);
1653
3273
  }
1654
- this.depth++;
1655
- }
1656
- this.id = id;
1657
- this.wire = wire;
1658
- this.fixSub = this.peekFixSub(wire);
1659
- return true;
1660
- }
1661
- /** Read an unsigned scalar (wire {@link WireType.Unsigned}), number-first. */
1662
- readUnsigned() {
1663
- this.readVarint();
1664
- return this.unsignedValue();
1665
- }
1666
- /** Read a signed scalar (wire {@link WireType.Signed}), zig-zag, number-first. */
1667
- readSigned() {
1668
- this.readVarint();
1669
- return this.signedValue();
1670
- }
1671
- /** Read a 32-bit float scalar (wire {@link WireType.Fixlen}, subtype fp32). */
1672
- readFp32() {
1673
- this.fixlenHeader(FixlenSubtype.Fp32, 4);
1674
- return this.rawFp32();
1675
- }
1676
- /**
1677
- * Read a 32-bit float scalar as its raw 4 wire bytes (little-endian), zero-copy
1678
- * — the bit-preserving companion to {@link readFp32}.
1679
- *
1680
- * {@link readFp32} returns a JS `number` (a 64-bit double), and widening an
1681
- * fp32 *signaling* NaN into a double quiets it (0x7F800001 → 0x7FC00001), so a
1682
- * value consumer can never round-trip one bit-for-bit (§4.6). Generated
1683
- * bit-exact decode reads the bytes here instead and re-emits them verbatim with
1684
- * {@link OStream.writeFixlen} (subtype fp32) — mirroring the visitor `raw`
1685
- * channel on the push paths (fast.ts / state.ts), which the pull path was
1686
- * missing (corelib-ts#66).
1687
- *
1688
- * The header (subtype fp32, length 4) is validated exactly as in
1689
- * {@link readFp32}; the returned view aliases the source buffer, valid only
1690
- * until it is reused, like {@link readBlob}.
1691
- */
1692
- readFp32Raw() {
1693
- this.fixlenHeader(FixlenSubtype.Fp32, 4);
1694
- return this.take(4);
1695
- }
1696
- /** Read a 64-bit float scalar (wire {@link WireType.Fixlen}, subtype fp64). */
1697
- readFp64() {
1698
- this.fixlenHeader(FixlenSubtype.Fp64, 8);
1699
- return this.rawFp64();
1700
- }
1701
- /**
1702
- * Read a UTF-8 string scalar (wire {@link WireType.Fixlen}, subtype string).
1703
- * Pass the schema `maxlen` (byte length) for a bounded string so an
1704
- * over-length is rejected as `INVALID` at the header, before the payload is
1705
- * taken (see {@link fixlenLen}); the wire length is exactly the UTF-8 byte
1706
- * length, so the check is exact. Omit for an unbounded string.
1707
- */
1708
- readString(schemaMaxlen) {
1709
- const len = this.fixlenLen(FixlenSubtype.String, schemaMaxlen);
1710
- const bytes = this.take(len);
1711
- try {
1712
- return _utf8.decode(bytes);
1713
- } catch {
1714
- throw invalidMsgError("invalid UTF-8 in string");
1715
- }
1716
- }
1717
- /**
1718
- * Read a blob scalar (wire {@link WireType.Fixlen}, subtype blob) as a
1719
- * zero-copy {@link Uint8Array} view into the source buffer.
1720
- */
1721
- readBlob(schemaMaxlen) {
1722
- const len = this.fixlenLen(FixlenSubtype.Blob, schemaMaxlen);
1723
- return this.take(len);
1724
- }
1725
- /**
1726
- * Read an unsigned array (wire {@link WireType.ArrayUnsigned}), number-first
1727
- * per element. Pass the schema `count` for a bounded array so an over-count is
1728
- * rejected as `INVALID` at the header (see {@link arrayCount}); omit it for an
1729
- * unbounded array (today's behavior).
1730
- */
1731
- readUnsignedArray(schemaCount) {
1732
- const count = this.arrayCount(schemaCount);
1733
- const out = new Array(count);
1734
- for (let i = 0; i < count; i++) {
1735
- this.readVarint();
1736
- out[i] = this.unsignedValue();
1737
- }
1738
- return out;
1739
- }
1740
- /** Read a signed array (wire {@link WireType.ArraySigned}), zig-zag, number-first per element. */
1741
- readSignedArray(schemaCount) {
1742
- const count = this.arrayCount(schemaCount);
1743
- const out = new Array(count);
1744
- for (let i = 0; i < count; i++) {
1745
- this.readVarint();
1746
- out[i] = this.signedValue();
1747
- }
1748
- return out;
1749
- }
1750
- /**
1751
- * Read an unsigned 64-bit array into {@link Long}[] — the `bigint`-free path.
1752
- * Each element keeps the raw lo/hi halves; call {@link Long.toBigInt} to
1753
- * materialise only the values the caller actually needs.
1754
- */
1755
- readUnsignedArrayLong(schemaCount) {
1756
- const count = this.arrayCount(schemaCount);
1757
- const out = new Array(count);
1758
- for (let i = 0; i < count; i++) {
1759
- this.readVarint();
1760
- out[i] = new Long(this.lo, this.hi);
1761
- }
1762
- return out;
1763
- }
1764
- /** Read a signed 64-bit array (zig-zag) into {@link Long}[] — the `bigint`-free path. */
1765
- readSignedArrayLong(schemaCount) {
1766
- const count = this.arrayCount(schemaCount);
1767
- const out = new Array(count);
1768
- for (let i = 0; i < count; i++) {
1769
- this.readVarint();
1770
- const lo = this.lo >>> 0;
1771
- const hi = this.hi >>> 0;
1772
- const mask = -(lo & 1) >>> 0;
1773
- out[i] = new Long((lo >>> 1 | hi << 31) >>> 0 ^ mask, hi >>> 1 >>> 0 ^ mask);
1774
- }
1775
- return out;
1776
- }
1777
- /** Read an fp32 array (wire {@link WireType.ArrayFixlen}, element subtype fp32). */
1778
- readFp32Array(schemaCount) {
1779
- const count = this.arrayFixlenHeader(FixlenSubtype.Fp32, 4, schemaCount);
1780
- const out = new Array(count);
1781
- for (let i = 0; i < count; i++) out[i] = this.rawFp32();
1782
- return out;
1783
- }
1784
- /**
1785
- * Read an fp32 array as its raw little-endian element payload (`count * 4`
1786
- * bytes), zero-copy — the bit-preserving companion to {@link readFp32Array}.
1787
- * Widening each element to a JS `number` quiets an fp32 *signaling* NaN just as
1788
- * on the scalar path (§4.6; see {@link readFp32Raw}), so bit-exact decode reads
1789
- * the whole payload here and re-emits it with {@link OStream.writeFp32ArrayRaw}
1790
- * (corelib-ts#66). The header (element subtype fp32, size 4) is validated
1791
- * exactly as in {@link readFp32Array}; the returned view aliases the source
1792
- * buffer, like {@link readBlob}.
1793
- */
1794
- readFp32ArrayRaw(schemaCount) {
1795
- const count = this.arrayFixlenHeader(FixlenSubtype.Fp32, 4, schemaCount);
1796
- return this.take(count * 4);
1797
- }
1798
- /** Read an fp64 array (wire {@link WireType.ArrayFixlen}, element subtype fp64). */
1799
- readFp64Array(schemaCount) {
1800
- const count = this.arrayFixlenHeader(FixlenSubtype.Fp64, 8, schemaCount);
1801
- const out = new Array(count);
1802
- for (let i = 0; i < count; i++) out[i] = this.rawFp64();
1803
- return out;
1804
- }
1805
- /**
1806
- * Consume the value of the field whose header {@link readHeader} just accepted,
1807
- * discarding it — for a `default:` branch that keeps the cursor in sync on an
1808
- * unknown id. Pass {@link wire}. A {@link WireType.SequenceStart} skips the
1809
- * whole nested sequence.
1810
- */
1811
- skip(wire) {
1812
- if (wire === WireType.SequenceStart) {
1813
- this.skipSequence();
1814
- this.depth--;
1815
- return;
1816
3274
  }
1817
- this.skipValue(wire);
1818
3275
  }
1819
- // --- value skipping -----------------------------------------------------
1820
- skipValue(wire) {
1821
- switch (wire) {
1822
- case WireType.Unsigned:
1823
- case WireType.Signed:
1824
- this.readVarint();
1825
- return;
1826
- case WireType.Fixlen: {
1827
- this.readVarint();
1828
- const sub = this.lo & 7;
1829
- const len = this.upper();
1830
- if (sub > FixlenSubtype.Blob) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1831
- if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
1832
- if (len !== (sub === FixlenSubtype.Fp32 ? 4 : 8)) {
1833
- throw invalidMsgError("fixlen float length mismatch");
1834
- }
1835
- } else if (len > FIXLEN_MAX) {
1836
- throw invalidMsgError("fixlen length out of range");
1837
- }
1838
- this.take(len);
1839
- return;
1840
- }
1841
- case WireType.ArrayUnsigned:
1842
- case WireType.ArraySigned: {
1843
- const count = this.arrayCount();
1844
- for (let i = 0; i < count; i++) this.readVarint();
1845
- return;
1846
- }
1847
- case WireType.ArrayFixlen: {
1848
- this.readVarint();
1849
- const count = this.num();
1850
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1851
- if (count > this.maxArrayCount) {
1852
- throw limitExceededError(
1853
- `array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`
1854
- );
1855
- }
1856
- this.readVarint();
1857
- const sub = this.lo & 7;
1858
- const size = this.upper();
1859
- const ok = sub === FixlenSubtype.Fp32 && size === 4 || sub === FixlenSubtype.Fp64 && size === 8;
1860
- if (!ok) throw invalidMsgError("invalid fixlen array element type");
1861
- this.take(count * size);
1862
- return;
1863
- }
1864
- default:
1865
- throw invalidMsgError(`invalid wire type ${wire}`);
1866
- }
3276
+ try {
3277
+ return _utf8.decode(buf.subarray(start, end));
3278
+ } catch {
3279
+ throw invalidMsgError("invalid UTF-8 in string");
1867
3280
  }
1868
- skipSequence() {
1869
- let depth = 1;
1870
- while (depth > 0) {
1871
- if (this.p >= this.n) throw incompleteError("truncated message: unbalanced sequence");
1872
- this.readVarint();
1873
- const wire = this.lo & 7;
1874
- if (wire === WireType.SequenceEnd) {
1875
- depth--;
1876
- continue;
1877
- }
1878
- const id = this.upper();
1879
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
1880
- if (wire === WireType.SequenceStart) {
1881
- if (this.depth + depth - 1 >= MAX_DEPTH) {
1882
- throw invalidMsgError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
1883
- }
1884
- depth++;
1885
- } else {
1886
- this.skipValue(wire);
1887
- }
1888
- }
3281
+ }
3282
+
3283
+ // src/decode/acc.ts
3284
+ var PayloadAcc = class {
3285
+ constructor() {
3286
+ this.buf = null;
3287
+ this.len = 0;
1889
3288
  }
1890
- // --- field helpers ------------------------------------------------------
1891
3289
  /**
1892
- * Peek the delivered fixlen subtype of the field {@link readHeader} just
1893
- * accepted, **without advancing the cursor** — the readers / {@link skip}
1894
- * still re-read and validate the word. Returns one of {@link FixlenSubtype}
1895
- * (0..3), a reserved value (4..7), or `-1` when the wire is not a fixlen kind
1896
- * or the subtype word is truncated away.
3290
+ * Contribute one piece — the bytes `src[start..end)` at `offset` of a
3291
+ * `total`-byte payload — and return the **whole** payload once it is complete,
3292
+ * or `null` while bytes are still outstanding.
3293
+ *
3294
+ * `offset === 0` starts a payload — and *resets* the accumulator, so a decode
3295
+ * that was abandoned mid-payload (an `INVALID` field, a declined subtree) leaves
3296
+ * nothing behind to corrupt the next one.
1897
3297
  *
1898
- * The subtype is the low 3 bits of the fixlen sub-header word, and the low
1899
- * bits of a LEB128 word live entirely in its **first** byte — so this only
1900
- * reads one byte, it never decodes a varint.
3298
+ * A late piece with no payload in progress returns `null` rather than writing
3299
+ * anywhere: the accumulator has no buffer to append to, and inventing one would
3300
+ * fabricate a payload out of a fragment.
1901
3301
  */
1902
- peekFixSub(wire) {
1903
- if (wire === WireType.Fixlen) {
1904
- return this.p < this.n ? this.buf[this.p] & 7 : -1;
3302
+ take(total, offset, src, start, end) {
3303
+ if (offset === 0) {
3304
+ this.buf = new Uint8Array(total);
3305
+ this.len = 0;
1905
3306
  }
1906
- if (wire === WireType.ArrayFixlen) {
1907
- let p = this.p;
1908
- while (p < this.n && this.buf[p] >= 128) p++;
1909
- p++;
1910
- return p < this.n ? this.buf[p] & 7 : -1;
3307
+ const b = this.buf;
3308
+ if (b === null) return null;
3309
+ let n = end - start;
3310
+ const room = total - this.len;
3311
+ if (n > room) n = room;
3312
+ if (n > 0) {
3313
+ b.set(src.subarray(start, start + n), this.len);
3314
+ this.len += n;
1911
3315
  }
1912
- return -1;
3316
+ if (this.len < total) return null;
3317
+ this.buf = null;
3318
+ return b;
3319
+ }
3320
+ };
3321
+
3322
+ // src/decode/seq.ts
3323
+ var NO_BYTES = new Uint8Array(0);
3324
+ var UNBOUNDED = -1;
3325
+ function requireReceiverBound(schemaBound, receiver, what, name) {
3326
+ if (schemaBound >= 0) return;
3327
+ if (Number.isFinite(receiver) && receiver >= 0) return;
3328
+ throw argumentError(
3329
+ `${name}: ${what} is ${receiver}, which states no cap \u2014 the schema left this field unbounded, and \xA76.2.1 admits no unset state and no unlimited mode. The number is generated code's to supply.`
3330
+ );
3331
+ }
3332
+ function indexBound(cap, receiverCap) {
3333
+ return cap >= 0 ? cap : receiverCap;
3334
+ }
3335
+ function rejectIndex(id, cap, receiverCap, name) {
3336
+ if (cap >= 0) {
3337
+ throw invalidMsgError(`${name}: array index above schema capacity ${cap}`);
3338
+ }
3339
+ throw limitExceededError(`${name}: array index ${id} exceeds the receiver cap ${receiverCap}`);
3340
+ }
3341
+ var ElementSeq = class {
3342
+ constructor(out, def, cap, name, receiverCap) {
3343
+ this.out = out;
3344
+ this.def = def;
3345
+ this.cap = cap;
3346
+ this.name = name;
3347
+ this.receiverCap = receiverCap;
3348
+ if (cap < 0) requireReceiverBound(cap, receiverCap, "the receiver array-index cap", name);
3349
+ this.bound = indexBound(cap, receiverCap);
1913
3350
  }
1914
3351
  /**
1915
- * Read and validate an array count word (0..ARRAY_MAX; §4.7/§4.8). When a
1916
- * `schemaCount` is given, a count above it is a schema-bound violation and is
1917
- * rejected as `INVALID` — see the check below.
3352
+ * Bound-check `id` and grow `out` to `id + 1`, filling any gap — and the slot
3353
+ * itself — with the element default.
3354
+ *
3355
+ * The check runs **before** the growth, which is the whole of §7.2 item 8's
3356
+ * "after a rejected id the container is not left partially extended": a
3357
+ * rejection leaves `out` exactly as it was, so a lower id delivered afterwards
3358
+ * still lands at its own index.
1918
3359
  */
1919
- arrayCount(schemaCount) {
1920
- this.readVarint();
1921
- const count = this.num();
1922
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1923
- if (schemaCount !== void 0 && count > schemaCount) {
1924
- throw invalidMsgError("array count above schema capacity");
1925
- }
1926
- if (count > this.maxArrayCount) {
1927
- throw limitExceededError(
1928
- `array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`
1929
- );
1930
- }
1931
- if (count > this.n - this.p) throw incompleteError("truncated array");
1932
- return count;
1933
- }
1934
- /** Read a scalar fixlen sub-header, asserting subtype and exact byte length (floats). */
1935
- fixlenHeader(wantSub, wantLen) {
1936
- this.readVarint();
1937
- const sub = this.lo & 7;
1938
- const len = this.upper();
1939
- if (sub !== wantSub) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1940
- if (len !== wantLen) throw invalidMsgError("fixlen float length mismatch");
1941
- }
1942
- /**
1943
- * Read a scalar fixlen sub-header for a string/blob, asserting subtype;
1944
- * returns the byte length. When a `schemaMaxlen` is given, a length above it
1945
- * is a schema-bound violation and is rejected as `INVALID` — see below.
1946
- */
1947
- fixlenLen(wantSub, schemaMaxlen) {
1948
- this.readVarint();
1949
- const sub = this.lo & 7;
1950
- const len = this.upper();
1951
- if (sub !== wantSub) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1952
- if (len > FIXLEN_MAX) throw invalidMsgError("fixlen length out of range");
1953
- if (schemaMaxlen !== void 0 && len > schemaMaxlen) {
1954
- throw invalidMsgError("fixlen length above schema maxlen");
1955
- }
1956
- const limit = wantSub === FixlenSubtype.String ? this.maxStringLen : this.maxBlobLen;
1957
- if (len > limit) {
1958
- const what = wantSub === FixlenSubtype.String ? "string" : "blob";
1959
- const name = wantSub === FixlenSubtype.String ? "maxStringLen" : "maxBlobLen";
1960
- throw limitExceededError(
1961
- `${what} length ${len} exceeds ${name} ${limit}`
1962
- );
1963
- }
1964
- return len;
3360
+ reserve(id) {
3361
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
3362
+ while (this.out.length <= id) this.out.push(this.def);
1965
3363
  }
1966
3364
  /**
1967
- * Read an array fixlen element header (count + element type); returns the
1968
- * count. When a `schemaCount` is given, a count above it is a schema-bound
1969
- * violation and is rejected as `INVALID` — see below.
3365
+ * The two index bounds, without growing: the schema `count` as validity
3366
+ * (`INVALID`) or, where the schema left the array open, the receiver cap as
3367
+ * capacity (`LIMIT_EXCEEDED`). Never both — §6.2.1 keeps a cap off a field the
3368
+ * schema already bounds, which is why one `bound` can stand for both.
3369
+ *
3370
+ * Split out from {@link reserve} because a leaf element is bound-checked at its
3371
+ * length word, before its payload has arrived and so before there is anything to
3372
+ * place ({@link StringSeq.begin}).
1970
3373
  */
1971
- arrayFixlenHeader(wantSub, wantSize, schemaCount) {
1972
- this.readVarint();
1973
- const count = this.num();
1974
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1975
- if (schemaCount !== void 0 && count > schemaCount) {
1976
- throw invalidMsgError("array count above schema capacity");
1977
- }
1978
- if (count > this.maxArrayCount) {
1979
- throw limitExceededError(
1980
- `array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`
1981
- );
1982
- }
1983
- this.readVarint();
1984
- const sub = this.lo & 7;
1985
- const size = this.upper();
1986
- if (sub !== wantSub || size !== wantSize) {
1987
- throw invalidMsgError("invalid fixlen array element type");
1988
- }
1989
- if (count > (this.n - this.p) / wantSize) {
1990
- throw incompleteError("truncated fixlen array");
1991
- }
1992
- return count;
1993
- }
1994
- /** Hand back a zero-copy view of the next `len` bytes, advancing the cursor. */
1995
- take(len) {
1996
- const start = this.p;
1997
- const end = start + len;
1998
- if (end > this.n) throw incompleteError("truncated fixlen payload");
1999
- this.p = end;
2000
- return this.buf.subarray(start, end);
3374
+ checkIndex(id) {
3375
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
2001
3376
  }
2002
- rawFp32() {
2003
- const p = this.p;
2004
- if (p + 4 > this.n) throw incompleteError("truncated fp32");
2005
- this.p = p + 4;
2006
- return this.view.getFloat32(p, true);
3377
+ /**
3378
+ * What {@link reserve} does, then `value` written into the slot. A repeat
3379
+ * replaces (§7.4).
3380
+ *
3381
+ * Written out rather than delegating to {@link reserve}: on the baseline tier a
3382
+ * call is not free, and this is the per-element path. The check still precedes
3383
+ * the growth, which is the property §7.2 item 8 asks for.
3384
+ */
3385
+ place(id, value) {
3386
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
3387
+ while (this.out.length <= id) this.out.push(this.def);
3388
+ this.out[id] = value;
2007
3389
  }
2008
- rawFp64() {
2009
- const p = this.p;
2010
- if (p + 8 > this.n) throw incompleteError("truncated fp64");
2011
- this.p = p + 8;
2012
- return this.view.getFloat64(p, true);
3390
+ };
3391
+ var FramedSeq = class {
3392
+ constructor(out, make, cap, name, receiverCap) {
3393
+ this.out = out;
3394
+ this.make = make;
3395
+ this.cap = cap;
3396
+ this.name = name;
3397
+ this.receiverCap = receiverCap;
3398
+ if (cap < 0) requireReceiverBound(cap, receiverCap, "the receiver array-index cap", name);
3399
+ this.bound = indexBound(cap, receiverCap);
2013
3400
  }
2014
- // --- varint reading (shared verbatim with ./fast) -----------------------
2015
3401
  /**
2016
- * The last varint's full value as a `bigint` (64-bit fidelity). Only ever
2017
- * called from {@link unsignedValue} / {@link signedValue} on the `hi` overflow
2018
- * path (`this.hi >>> 0 > 0x1fffff`), so `hi` is always non-zero here.
3402
+ * The two index bounds, without growing — see {@link ElementSeq.checkIndex}.
3403
+ *
3404
+ * Split out for the same reason it is there: a caller may have a second bound
3405
+ * to take before anything is allocated. A native matrix row is that case in this
3406
+ * port — its element `count` is rejected at the array header, and §7.2 item 8
3407
+ * wants that rejection to leave the row container exactly as it was.
2019
3408
  */
2020
- big() {
2021
- return BigInt(this.hi >>> 0) << 32n | BigInt(this.lo >>> 0);
3409
+ checkIndex(id) {
3410
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
2022
3411
  }
2023
3412
  /**
2024
- * The last varint as an unsigned value, number-first: a `number` when it fits
2025
- * exactly (`≤ 2^53-1`), a `bigint` only beyond that.
3413
+ * Bound-check `id`, **then** grow `out` to `id + 1`, each new slot its own
3414
+ * `make()`.
3415
+ *
3416
+ * The order is §7.2 item 8's "after a rejected id the container is not left
3417
+ * partially extended": a rejection leaves `out` exactly as it was, so a lower id
3418
+ * delivered afterwards still lands at its own index. A slot already present is
3419
+ * left alone — a re-opened `struct` / `union` element merges into the object it
3420
+ * already built, which is what §7.4's last-occurrence-wins means for a scope
3421
+ * whose value *is* the scope.
2026
3422
  */
2027
- unsignedValue() {
2028
- const hi = this.hi >>> 0;
2029
- return hi <= 2097151 ? hi * TWO323 + (this.lo >>> 0) : this.big();
3423
+ reserve(id) {
3424
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
3425
+ while (this.out.length <= id) this.out.push(this.make());
2030
3426
  }
2031
- /** The last zig-zag varint as a signed value, number-first. */
2032
- signedValue() {
2033
- const hi = this.hi >>> 0;
2034
- if (hi <= 2097151) {
2035
- const r = hi * TWO323 + (this.lo >>> 0);
2036
- return r % 2 === 0 ? r / 2 : -(r + 1) / 2;
2037
- }
2038
- return zigzagDecode(this.big());
2039
- }
2040
- /** The last varint's value as a JS number — exact for ids/lengths/counts. */
2041
- num() {
2042
- return this.hi * TWO323 + (this.lo >>> 0);
3427
+ /**
3428
+ * Bound-check `id`, fill the gap below it, then write `value` into the slot —
3429
+ * what a nested **row** needs, an array wrapper *replacing* whatever an earlier
3430
+ * opening built at that index (§7.4) rather than merging into it.
3431
+ *
3432
+ * The gap fill stops one short of `id` on purpose: the slot is about to be
3433
+ * overwritten, so calling `make()` for it would allocate an element default
3434
+ * nobody ever reads. Assigning at `out.length` extends the array by exactly one,
3435
+ * which is the same array a {@link reserve} would have left.
3436
+ */
3437
+ place(id, value) {
3438
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
3439
+ while (this.out.length < id) this.out.push(this.make());
3440
+ this.out[id] = value;
2043
3441
  }
2044
- /** The last varint with its low 3 tag bits stripped (`value >> 3`). */
2045
- upper() {
2046
- return (this.hi >>> 0) * (TWO323 / 8) + (this.lo >>> 3);
3442
+ };
3443
+ var StringSeq = class {
3444
+ constructor(out, acc, cap, elemMax, name, receiverCap, receiverElemMax) {
3445
+ this.out = out;
3446
+ this.acc = acc;
3447
+ this.cap = cap;
3448
+ this.elemMax = elemMax;
3449
+ this.name = name;
3450
+ this.receiverCap = receiverCap;
3451
+ this.receiverElemMax = receiverElemMax;
3452
+ requireReceiverBound(elemMax, receiverElemMax, "the receiver element-length cap", name);
3453
+ this.slots = new ElementSeq(out, "", cap, name, receiverCap);
2047
3454
  }
2048
3455
  /**
2049
- * Decode one LEB128 varint at the cursor into {@link lo} / {@link hi} (each an
2050
- * unsigned 32-bit half), advancing {@link p}. Throws on truncation or a value
2051
- * spilling past 64 bits (>10 bytes). Unrolled, number-only — no `bigint`.
3456
+ * The element's fixlen length word ({@link Visitor.fixlenBegin}).
3457
+ *
3458
+ * The bounds are decided by this word, so they are checked here — before any
3459
+ * payload byte — and again in {@link element} below.
3460
+ *
3461
+ * That is not redundancy for its own sake: a message that ends *inside* an
3462
+ * over-long element must still be `INVALID`, and only this event runs early
3463
+ * enough to say so. Without it the verdict would degrade to `INCOMPLETE`, which
3464
+ * §5.2.3 forbids for input already known to be malformed and which §6.4 forbids
3465
+ * a chunk boundary from changing.
3466
+ *
3467
+ * An element of the wrong fixlen subtype is left alone: §7.3 requires it to be
3468
+ * *skipped*, not rejected, and it is skipped by this class simply ignoring it.
2052
3469
  */
2053
- readVarint() {
2054
- const buf = this.buf;
2055
- const n = this.n;
2056
- let p = this.p;
2057
- let b;
2058
- let lo;
2059
- let hi = 0;
2060
- if (p >= n) throw incompleteError("truncated varint");
2061
- b = buf[p++];
2062
- lo = b & 127;
2063
- if (b < 128) return this.set(lo, 0, p);
2064
- if (p >= n) throw incompleteError("truncated varint");
2065
- b = buf[p++];
2066
- lo |= (b & 127) << 7;
2067
- if (b < 128) return this.set(lo, 0, p);
2068
- if (p >= n) throw incompleteError("truncated varint");
2069
- b = buf[p++];
2070
- lo |= (b & 127) << 14;
2071
- if (b < 128) return this.set(lo, 0, p);
2072
- if (p >= n) throw incompleteError("truncated varint");
2073
- b = buf[p++];
2074
- lo |= (b & 127) << 21;
2075
- if (b < 128) return this.set(lo, 0, p);
2076
- if (p >= n) throw incompleteError("truncated varint");
2077
- b = buf[p++];
2078
- lo |= (b & 15) << 28;
2079
- hi = b >> 4 & 7;
2080
- if (b < 128) return this.set(lo, hi, p);
2081
- if (p >= n) throw incompleteError("truncated varint");
2082
- b = buf[p++];
2083
- hi |= (b & 127) << 3;
2084
- if (b < 128) return this.set(lo, hi, p);
2085
- if (p >= n) throw incompleteError("truncated varint");
2086
- b = buf[p++];
2087
- hi |= (b & 127) << 10;
2088
- if (b < 128) return this.set(lo, hi, p);
2089
- if (p >= n) throw incompleteError("truncated varint");
2090
- b = buf[p++];
2091
- hi |= (b & 127) << 17;
2092
- if (b < 128) return this.set(lo, hi, p);
2093
- if (p >= n) throw incompleteError("truncated varint");
2094
- b = buf[p++];
2095
- hi |= (b & 127) << 24;
2096
- if (b < 128) return this.set(lo, hi, p);
2097
- if (p >= n) throw incompleteError("truncated varint");
2098
- b = buf[p++];
2099
- if ((b & 127) >> 1 !== 0) throw invalidMsgError("varint overflow");
2100
- hi |= (b & 127) << 31;
2101
- if (b < 128) return this.set(lo, hi, p);
2102
- throw invalidMsgError("varint overflow");
2103
- }
2104
- set(lo, hi, p) {
2105
- this.lo = lo;
2106
- this.hi = hi;
2107
- this.p = p;
3470
+ begin(id, subtype, total) {
3471
+ if (subtype !== FixlenSubtype.String) return;
3472
+ this.check(id, total);
3473
+ }
3474
+ /** One payload piece of element `id` ({@link Visitor.string}). */
3475
+ element(id, total, offset, src, start, end) {
3476
+ this.check(id, total);
3477
+ const text = offset === 0 && end - start === total ? decodeUtf8(src, start, end) : decodeStringPiece(this.acc, total, offset, src, start, end);
3478
+ if (text === null) return;
3479
+ this.slots.place(id, text);
3480
+ }
3481
+ /** Every bound for one element. Rejects **before** the destination grows. */
3482
+ check(id, total) {
3483
+ this.slots.checkIndex(id);
3484
+ if (this.elemMax >= 0) {
3485
+ if (total > this.elemMax) {
3486
+ throw invalidMsgError(
3487
+ `${this.name} element: string byte length above schema maxlen ${this.elemMax}`
3488
+ );
3489
+ }
3490
+ } else if (total > this.receiverElemMax) {
3491
+ throw limitExceededError(
3492
+ `${this.name} element: string byte length ${total} exceeds the receiver cap ${this.receiverElemMax}`
3493
+ );
3494
+ }
2108
3495
  }
2109
3496
  };
2110
-
2111
- // src/backend/native.ts
2112
- var NATIVE_PACKAGE = "@sofa-buffers/corelib-native";
2113
- function isNode() {
2114
- return typeof process !== "undefined" && !!process.versions?.node;
2115
- }
2116
- async function loadNativeKernel() {
2117
- if (!isNode()) return false;
2118
- try {
2119
- const { createRequire } = await import('module');
2120
- const require2 = createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
2121
- const mod = require2(NATIVE_PACKAGE);
2122
- const kernel = mod.kernel ?? mod;
2123
- setKernel(kernel);
2124
- return true;
2125
- } catch {
2126
- return false;
3497
+ var BlobSeq = class {
3498
+ constructor(out, acc, cap, elemMax, name, receiverCap, receiverElemMax) {
3499
+ this.out = out;
3500
+ this.acc = acc;
3501
+ this.cap = cap;
3502
+ this.elemMax = elemMax;
3503
+ this.name = name;
3504
+ this.receiverCap = receiverCap;
3505
+ this.receiverElemMax = receiverElemMax;
3506
+ requireReceiverBound(elemMax, receiverElemMax, "the receiver element-length cap", name);
3507
+ this.slots = new ElementSeq(out, NO_BYTES, cap, name, receiverCap);
3508
+ }
3509
+ /** See {@link StringSeq.begin} — the early bound check, for subtype `blob`. */
3510
+ begin(id, subtype, total) {
3511
+ if (subtype !== FixlenSubtype.Blob) return;
3512
+ this.check(id, total);
3513
+ }
3514
+ /** One payload piece of element `id` ({@link Visitor.blob}). */
3515
+ element(id, total, offset, src, start, end) {
3516
+ this.check(id, total);
3517
+ const payload = this.acc.take(total, offset, src, start, end);
3518
+ if (payload === null) return;
3519
+ this.slots.place(id, payload);
3520
+ }
3521
+ /** Every bound for one element. Rejects **before** the destination grows. */
3522
+ check(id, total) {
3523
+ this.slots.checkIndex(id);
3524
+ if (this.elemMax >= 0) {
3525
+ if (total > this.elemMax) {
3526
+ throw invalidMsgError(
3527
+ `${this.name} element: blob byte length above schema maxlen ${this.elemMax}`
3528
+ );
3529
+ }
3530
+ } else if (total > this.receiverElemMax) {
3531
+ throw limitExceededError(
3532
+ `${this.name} element: blob byte length ${total} exceeds the receiver cap ${this.receiverElemMax}`
3533
+ );
3534
+ }
2127
3535
  }
3536
+ };
3537
+ function decodeStringPiece(acc, total, offset, src, start, end) {
3538
+ const payload = acc.take(total, offset, src, start, end);
3539
+ return payload === null ? null : decodeUtf8(payload);
2128
3540
  }
2129
3541
 
2130
- // src/backend/wasm.ts
2131
- async function loadWasmKernel(source, factory, imports = {}) {
2132
- let instance;
2133
- if (source instanceof WebAssembly.Module) {
2134
- instance = await WebAssembly.instantiate(source, imports);
2135
- } else if (typeof Response !== "undefined" && (source instanceof Response || isThenable(source))) {
2136
- const result = await WebAssembly.instantiateStreaming(
2137
- source,
2138
- imports
2139
- );
2140
- instance = result.instance;
2141
- } else {
2142
- const result = await WebAssembly.instantiate(source, imports);
2143
- instance = result.instance;
2144
- }
2145
- setKernel(factory(instance.exports));
3542
+ // src/encode/equal.ts
3543
+ function elementsEqual(a, b) {
3544
+ if (a.length !== b.length) return false;
3545
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2146
3546
  return true;
2147
3547
  }
2148
- function isThenable(x) {
2149
- return typeof x === "object" && x !== null && typeof x.then === "function";
3548
+ function longElementsEqual(a, b) {
3549
+ if (a.length !== b.length) return false;
3550
+ for (let i = 0; i < a.length; i++) {
3551
+ if (a[i].low !== b[i].low || a[i].high !== b[i].high) return false;
3552
+ }
3553
+ return true;
2150
3554
  }
2151
3555
 
2152
3556
  exports.API_VERSION = API_VERSION;
2153
3557
  exports.ARRAY_MAX = ARRAY_MAX;
2154
3558
  exports.ArrayKind = ArrayKind;
2155
- exports.Cursor = Cursor;
3559
+ exports.BlobSeq = BlobSeq;
2156
3560
  exports.DecodeStatus = DecodeStatus;
3561
+ exports.ElementSeq = ElementSeq;
2157
3562
  exports.FIXLEN_MAX = FIXLEN_MAX;
2158
3563
  exports.FixlenSubtype = FixlenSubtype;
3564
+ exports.FramedSeq = FramedSeq;
2159
3565
  exports.I64_MAX = I64_MAX;
2160
3566
  exports.I64_MIN = I64_MIN;
2161
3567
  exports.ID_MAX = ID_MAX;
2162
3568
  exports.IStream = IStream;
2163
3569
  exports.Long = Long;
2164
3570
  exports.MAX_DEPTH = MAX_DEPTH;
3571
+ exports.MIN_OUTPUT_BUFFER = MIN_OUTPUT_BUFFER;
2165
3572
  exports.OStream = OStream;
3573
+ exports.PayloadAcc = PayloadAcc;
2166
3574
  exports.SofabError = SofabError;
2167
3575
  exports.SofabErrorCode = SofabErrorCode;
3576
+ exports.StringSeq = StringSeq;
2168
3577
  exports.U64_MAX = U64_MAX;
3578
+ exports.UNBOUNDED = UNBOUNDED;
2169
3579
  exports.WireType = WireType;
2170
3580
  exports.decode = decode;
3581
+ exports.decodeUtf8 = decodeUtf8;
3582
+ exports.elementsEqual = elementsEqual;
3583
+ exports.fp32RawBytes = fp32RawBytes;
2171
3584
  exports.getKernel = getKernel;
3585
+ exports.growingOStream = growingOStream;
2172
3586
  exports.jsKernel = jsKernel;
2173
- exports.loadNativeKernel = loadNativeKernel;
2174
- exports.loadWasmKernel = loadWasmKernel;
3587
+ exports.longElementsEqual = longElementsEqual;
2175
3588
  exports.setKernel = setKernel;
2176
3589
  exports.sofab = public_exports;
2177
3590
  //# sourceMappingURL=index.cjs.map