@sofa-buffers/corelib 0.8.1 → 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. */
@@ -97,8 +108,6 @@ var DecodeStatus = {
97
108
  var SofabErrorCode = {
98
109
  /** A caller argument was invalid (e.g. id out of range, empty array). */
99
110
  Argument: "ARGUMENT",
100
- /** The API was used incorrectly (e.g. unbalanced sequence end). */
101
- Usage: "USAGE",
102
111
  /** The output buffer is full and no flush sink was provided. */
103
112
  BufferFull: "BUFFER_FULL",
104
113
  /** The input being decoded is malformed regardless of what follows (`INVALID`). */
@@ -113,7 +122,8 @@ var SofabErrorCode = {
113
122
  /**
114
123
  * A receiver-configured decode limit was exceeded — a dynamic array, string or
115
124
  * blob on the wire claims more elements / bytes than the caller's
116
- * {@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)
117
127
  * allows. Deliberately distinct from {@link SofabErrorCode.InvalidMsg}:
118
128
  * exceeding a limit is *policy*, not wire malformation — the identical bytes
119
129
  * decode fine under a looser limit — so differential fuzzing must not read it
@@ -133,9 +143,6 @@ var SofabError = class _SofabError extends Error {
133
143
  function argumentError(message) {
134
144
  return new SofabError(SofabErrorCode.Argument, message);
135
145
  }
136
- function usageError(message) {
137
- return new SofabError(SofabErrorCode.Usage, message);
138
- }
139
146
  function bufferFullError(message) {
140
147
  return new SofabError(SofabErrorCode.BufferFull, message);
141
148
  }
@@ -149,6 +156,34 @@ function limitExceededError(message) {
149
156
  return new SofabError(SofabErrorCode.LimitExceeded, message);
150
157
  }
151
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
+
152
187
  // src/long.ts
153
188
  var _Long = class _Long {
154
189
  constructor(low, high) {
@@ -159,9 +194,14 @@ var _Long = class _Long {
159
194
  static fromBits(low, high) {
160
195
  return new _Long(low, high);
161
196
  }
162
- /** 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
+ */
163
202
  static fromBigInt(value) {
164
- 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]);
165
205
  }
166
206
  /** From an integer `number` (`|n| < 2^53`); sign handled via `bigint` once. */
167
207
  static fromNumber(n) {
@@ -174,9 +214,7 @@ var _Long = class _Long {
174
214
  }
175
215
  /** Materialise as a `bigint`. `signed` reads the high bit as two's complement. */
176
216
  toBigInt(signed = false) {
177
- let r = BigInt(this.high >>> 0) << 32n | BigInt(this.low >>> 0);
178
- if (signed && (this.high & 2147483648) !== 0) r -= 0x10000000000000000n;
179
- return r;
217
+ return signed ? joinI64(this.low, this.high) : joinU64(this.low, this.high);
180
218
  }
181
219
  /** Decimal string (`signed` interprets the high bit as two's complement). */
182
220
  toString(signed = false) {
@@ -194,50 +232,40 @@ _Long.ZERO = new _Long(0, 0);
194
232
  var Long = _Long;
195
233
 
196
234
  // src/varint/leb128.ts
197
- function varintSize(value) {
198
- let lo = Number(value & 0xffffffffn) >>> 0;
199
- let hi = Number(value >> 32n & 0xffffffffn) >>> 0;
200
- let n = 0;
201
- while (hi !== 0) {
202
- n++;
203
- const next = (lo >>> 7 | hi << 25) >>> 0;
204
- hi >>>= 7;
205
- lo = next;
206
- }
207
- while (lo > 127) {
208
- n++;
209
- lo >>>= 7;
235
+ function varintSizeLoHi(lo, hi) {
236
+ if (hi === 0) {
237
+ return lo < 128 ? 1 : lo < 16384 ? 2 : lo < 2097152 ? 3 : lo < 268435456 ? 4 : 5;
210
238
  }
211
- return n + 1;
212
- }
213
- function encodeVarint(value, out, pos) {
214
- let lo = Number(value & 0xffffffffn) >>> 0;
215
- let hi = Number(value >> 32n & 0xffffffffn) >>> 0;
216
- while (hi !== 0) {
217
- out[pos++] = lo & 127 | 128;
218
- lo = (lo >>> 7 | hi << 25) >>> 0;
219
- hi >>>= 7;
220
- }
221
- while (lo > 127) {
222
- out[pos++] = lo & 127 | 128;
223
- lo >>>= 7;
224
- }
225
- out[pos++] = lo;
226
- 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);
227
241
  }
228
242
  function encodeVarintLoHi(lo, hi, out, pos) {
229
243
  lo >>>= 0;
230
244
  hi >>>= 0;
231
- while (hi !== 0) {
232
- out[pos++] = lo & 127 | 128;
233
- lo = (lo >>> 7 | hi << 25) >>> 0;
234
- 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;
235
262
  }
236
- while (lo > 127) {
237
- out[pos++] = lo & 127 | 128;
238
- lo >>>= 7;
263
+ out[pos++] = b4 | 128;
264
+ while (h > 127) {
265
+ out[pos++] = h & 127 | 128;
266
+ h >>>= 7;
239
267
  }
240
- out[pos++] = lo;
268
+ out[pos++] = h;
241
269
  return pos;
242
270
  }
243
271
  function varintSizeNum(value) {
@@ -267,51 +295,78 @@ function encodeVarintNum(value, out, pos) {
267
295
  }
268
296
 
269
297
  // src/varint/num64.ts
270
- 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);
271
304
  function toBigInt(value) {
272
305
  if (typeof value === "bigint") return value;
273
306
  if (!Number.isInteger(value)) {
274
- throw new RangeError(`expected an integer, got ${value}`);
307
+ throw argumentError(`expected an integer, got ${value}`);
275
308
  }
276
309
  return BigInt(value);
277
310
  }
278
- function inU64(value) {
279
- return value >= 0n && value <= U64_MAX;
280
- }
281
- function inI64(value) {
282
- return value >= I64_MIN && value <= I64_MAX;
283
- }
284
311
  function packFp32(out, pos, value) {
285
- SCRATCH.setFloat32(0, value, true);
286
- out[pos] = SCRATCH.getUint8(0);
287
- out[pos + 1] = SCRATCH.getUint8(1);
288
- out[pos + 2] = SCRATCH.getUint8(2);
289
- 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];
290
317
  return pos + 4;
291
318
  }
292
319
  function packFp64(out, pos, value) {
293
- SCRATCH.setFloat64(0, value, true);
294
- 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];
295
329
  return pos + 8;
296
330
  }
297
- function unpackFp32(buf, pos) {
298
- SCRATCH.setUint8(0, buf[pos]);
299
- SCRATCH.setUint8(1, buf[pos + 1]);
300
- SCRATCH.setUint8(2, buf[pos + 2]);
301
- SCRATCH.setUint8(3, buf[pos + 3]);
302
- 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);
303
338
  }
304
- function unpackFp64(buf, pos) {
305
- for (let i = 0; i < 8; i++) SCRATCH.setUint8(i, buf[pos + i]);
306
- return SCRATCH.getFloat64(0, true);
339
+ function fp64BitsHi(value) {
340
+ SCRATCH2.setFloat64(0, value, true);
341
+ return SCRATCH2.getUint32(4, true);
342
+ }
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];
307
359
  }
308
360
 
309
361
  // src/varint/zigzag.ts
310
- function zigzagEncode(value) {
311
- return (value << 1n ^ value >> 63n) & U64_MAX;
312
- }
313
- function zigzagDecode(value) {
314
- 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
+ );
315
370
  }
316
371
 
317
372
  // src/backend/js.ts
@@ -319,36 +374,161 @@ var SIGNED_FAST_MAX = 4503599627370496;
319
374
  var jsKernel = {
320
375
  name: "js",
321
376
  encodeUnsignedVarints(values, out, pos) {
322
- 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++) {
323
400
  const v = values[i];
324
401
  if (typeof v === "number" && v >= 0 && v <= Number.MAX_SAFE_INTEGER && Number.isInteger(v)) {
325
402
  pos = encodeVarintNum(v, out, pos);
326
- } else {
327
- 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;
328
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;
329
433
  }
330
434
  return pos;
331
435
  },
332
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
+ }
333
460
  for (let i = 0; i < values.length; i++) {
334
461
  const v = values[i];
335
462
  if (typeof v === "number" && v >= -SIGNED_FAST_MAX && v <= SIGNED_FAST_MAX && Number.isInteger(v)) {
336
463
  pos = encodeVarintNum(v >= 0 ? v * 2 : -v * 2 - 1, out, pos);
337
464
  } else {
338
- 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);
339
468
  }
340
469
  }
341
470
  return pos;
342
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.
343
482
  packFp32Array(values, out, pos) {
344
- for (let i = 0; i < values.length; i++) {
345
- 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;
346
519
  }
347
520
  return pos;
348
521
  },
349
522
  packFp64Array(values, out, pos) {
350
- for (let i = 0; i < values.length; i++) {
351
- 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;
352
532
  }
353
533
  return pos;
354
534
  }
@@ -378,19 +558,18 @@ function validateKernel(kernel) {
378
558
  }
379
559
 
380
560
  // src/encode/fixlen.ts
381
- var UTF8 = new TextEncoder();
382
561
  function unpairedSurrogate(index) {
383
562
  return argumentError(
384
563
  `unpaired surrogate at index ${index}: string value is not valid UTF-8`
385
564
  );
386
565
  }
387
- function encodeUtf8(text) {
388
- utf8Length(text);
389
- return UTF8.encode(text);
390
- }
391
566
  function utf8Length(text) {
392
- let len = 0;
393
- 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++) {
394
573
  const c = text.charCodeAt(i);
395
574
  if (c < 128) {
396
575
  len += 1;
@@ -413,7 +592,17 @@ function utf8Length(text) {
413
592
  return len;
414
593
  }
415
594
  function utf8Write(text, out, pos) {
416
- 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++) {
417
606
  let c = text.charCodeAt(i);
418
607
  if (c < 128) {
419
608
  out[pos++] = c;
@@ -442,48 +631,139 @@ function utf8Write(text, out, pos) {
442
631
  }
443
632
  return pos;
444
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
+ }
445
664
 
446
665
  // src/encode/ostream.ts
447
- var DEFAULT_CAPACITY = 256;
448
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
+ }
449
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
+ */
450
694
  constructor(buffer, offset = 0, flush) {
451
695
  this.depth = 0;
696
+ /** Valid entries in {@link OStream.pending}. */
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;
452
707
  this.kernel = getKernel();
453
- if (buffer === void 0) {
454
- this.buf = new Uint8Array(DEFAULT_CAPACITY);
455
- this.start = 0;
456
- this.pos = 0;
457
- this.flushSink = void 0;
458
- this.canGrow = true;
459
- } else {
460
- if (offset < 0 || offset > buffer.length) {
461
- throw argumentError(`offset ${offset} out of range`);
462
- }
463
- this.buf = buffer;
464
- this.start = offset;
465
- this.pos = offset;
466
- this.flushSink = flush;
467
- this.canGrow = false;
468
- }
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;
469
715
  }
470
- /** 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}). */
471
717
  get bytesUsed() {
472
- return this.pos - this.start;
718
+ return this.pos - this.origin;
473
719
  }
474
720
  /**
475
- * The encoded message so far, as a view into the working buffer.
476
- * Meaningful for the in-memory mode; in streaming mode it is only the
477
- * 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.
478
727
  */
479
728
  bytes() {
480
- return this.buf.subarray(this.start, this.pos);
729
+ return this.buf.subarray(this.origin, this.pos);
481
730
  }
482
- /** 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
+ */
483
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) {
484
759
  if (this.flushSink && this.pos > this.start) {
485
- this.flushSink(this.buf.subarray(this.start, this.pos));
486
- 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
+ }
487
767
  }
488
768
  }
489
769
  /**
@@ -493,14 +773,42 @@ var OStream = class {
493
773
  * without interruption. `offset` reserves space at the front of the new
494
774
  * buffer. Any not-yet-flushed bytes in the old buffer are dropped, so
495
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.
496
804
  */
497
- setBuffer(buffer, offset = 0) {
498
- if (offset < 0 || offset > buffer.length) {
499
- throw argumentError(`offset ${offset} out of range`);
500
- }
805
+ setBuffer(buffer, offset = 0, carried = 0) {
806
+ checkHandover(buffer, offset, this.flushSink !== void 0, carried);
501
807
  this.buf = buffer;
502
808
  this.start = offset;
809
+ this.origin = offset - carried;
503
810
  this.pos = offset;
811
+ this.installs++;
504
812
  }
505
813
  /**
506
814
  * Rewind the encoder to empty, reusing the existing buffer. Lets a caller pool
@@ -508,8 +816,10 @@ var OStream = class {
508
816
  * encode. Any view previously returned by {@link bytes} is invalidated.
509
817
  */
510
818
  reset() {
511
- this.pos = this.start;
819
+ this.pos = this.origin;
820
+ this.start = this.origin;
512
821
  this.depth = 0;
822
+ this.nPending = 0;
513
823
  }
514
824
  // --- scalars ------------------------------------------------------------
515
825
  /** Write an unsigned integer field. */
@@ -520,9 +830,11 @@ var OStream = class {
520
830
  return;
521
831
  }
522
832
  const v = toBigInt(value);
523
- 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];
524
836
  this.header(id, WireType.Unsigned);
525
- this.putVarint(v);
837
+ this.putVarintLoHi(lo, hi);
526
838
  }
527
839
  /** Write a signed integer field (zig-zag encoded). */
528
840
  writeSigned(id, value) {
@@ -532,9 +844,44 @@ var OStream = class {
532
844
  return;
533
845
  }
534
846
  const v = toBigInt(value);
535
- 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) {
536
883
  this.header(id, WireType.Signed);
537
- this.putVarint(zigzagEncode(v));
884
+ this.putZigzagVarintLoHi(value.low, value.high);
538
885
  }
539
886
  /** Write a boolean field (encoded as the unsigned value 0 or 1). */
540
887
  writeBoolean(id, value) {
@@ -544,69 +891,161 @@ var OStream = class {
544
891
  /** Write an IEEE-754 32-bit float field. */
545
892
  writeFp32(id, value) {
546
893
  this.fixlenHead(id, 4, FixlenSubtype.Fp32);
547
- this.ensure(4);
548
- 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);
549
911
  }
550
912
  /** Write an IEEE-754 64-bit double field. */
551
913
  writeFp64(id, value) {
552
914
  this.fixlenHead(id, 8, FixlenSubtype.Fp64);
553
- this.ensure(8);
554
- this.pos = packFp64(this.buf, this.pos, value);
915
+ this.putFp64(value);
555
916
  }
556
917
  /** Write a UTF-8 string field. */
557
918
  writeString(id, text) {
558
- if (this.canGrow) {
559
- const byteLen = utf8Length(text);
560
- if (byteLen > FIXLEN_MAX) {
561
- 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;
562
933
  }
563
- this.fixlenHead(id, byteLen, FixlenSubtype.String);
564
- 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)) {
565
943
  this.pos = utf8Write(text, this.buf, this.pos);
566
944
  return;
567
945
  }
568
- this.writeFixlen(id, encodeUtf8(text), FixlenSubtype.String);
946
+ utf8WriteSink(text, this);
569
947
  }
570
948
  /** Write a blob (arbitrary bytes) field. */
571
949
  writeBlob(id, data) {
572
950
  this.writeFixlen(id, data, FixlenSubtype.Blob);
573
951
  }
574
- /** 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
+ */
575
972
  writeFixlen(id, data, subtype) {
576
- 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) {
577
984
  throw argumentError(`fixlen length ${data.length} exceeds ${FIXLEN_MAX}`);
578
985
  }
579
986
  this.fixlenHead(id, data.length, subtype);
580
987
  this.writeRaw(data);
581
988
  }
582
989
  // --- arrays -------------------------------------------------------------
583
- /** 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
+ */
584
1015
  writeUnsignedArray(id, values) {
585
1016
  this.arrayHead(id, WireType.ArrayUnsigned, values.length);
586
- if (this.canGrow) {
587
- 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)) {
588
1023
  this.pos = this.kernel.encodeUnsignedVarints(values, this.buf, this.pos);
589
1024
  } else {
590
1025
  for (let i = 0; i < values.length; i++) {
591
1026
  const v = toBigInt(values[i]);
592
- if (!inU64(v)) throw argumentError(`unsigned value ${v} out of range`);
593
- this.ensure(VARINT_MAX_BYTES);
594
- 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);
595
1031
  }
596
1032
  }
597
1033
  }
598
- /** Write an array of signed integers (each zig-zag + varint). */
1034
+ /** Write an array of signed integers (each zig-zag + varint). See {@link writeUnsignedArray}. */
599
1035
  writeSignedArray(id, values) {
600
1036
  this.arrayHead(id, WireType.ArraySigned, values.length);
601
- if (this.canGrow) {
602
- 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)) {
603
1043
  this.pos = this.kernel.encodeSignedVarints(values, this.buf, this.pos);
604
1044
  } else {
605
1045
  for (let i = 0; i < values.length; i++) {
606
1046
  const v = toBigInt(values[i]);
607
- if (!inI64(v)) throw argumentError(`signed value ${v} out of range`);
608
- this.ensure(VARINT_MAX_BYTES);
609
- 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]);
610
1049
  }
611
1050
  }
612
1051
  }
@@ -617,14 +1056,20 @@ var OStream = class {
617
1056
  */
618
1057
  writeUnsignedArrayLong(id, values) {
619
1058
  this.arrayHead(id, WireType.ArrayUnsigned, values.length);
620
- this.ensure(values.length * VARINT_MAX_BYTES);
621
- let pos = this.pos;
622
- const buf = this.buf;
623
- for (let i = 0; i < values.length; i++) {
624
- const v = values[i];
625
- 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
+ }
626
1072
  }
627
- this.pos = pos;
628
1073
  }
629
1074
  /**
630
1075
  * Write a signed 64-bit array (zig-zag) from {@link Long}[] — the `bigint`-free
@@ -632,411 +1077,745 @@ var OStream = class {
632
1077
  */
633
1078
  writeSignedArrayLong(id, values) {
634
1079
  this.arrayHead(id, WireType.ArraySigned, values.length);
635
- this.ensure(values.length * VARINT_MAX_BYTES);
636
- let pos = this.pos;
637
- const buf = this.buf;
638
- for (let i = 0; i < values.length; i++) {
639
- const v = values[i];
640
- const lo = v.low;
641
- const hi = v.high;
642
- const sgn = -(hi >>> 31) >>> 0;
643
- const zLo = (lo << 1 >>> 0 ^ sgn) >>> 0;
644
- const zHi = ((hi << 1 | lo >>> 31) >>> 0 ^ sgn) >>> 0;
645
- 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
+ }
646
1093
  }
647
- this.pos = pos;
648
1094
  }
649
1095
  /** Write an array of IEEE-754 32-bit floats. */
650
1096
  writeFp32Array(id, values) {
1097
+ if (values instanceof Float32Array) {
1098
+ this.writeFp32Words(id, values);
1099
+ return;
1100
+ }
651
1101
  this.arrayHead(id, WireType.ArrayFixlen, values.length);
652
1102
  this.putVarintNum(4 * 8 + FixlenSubtype.Fp32);
653
- if (this.canGrow) {
654
- this.ensure(values.length * 4);
1103
+ if (this.reserveBulk(values.length * 4)) {
655
1104
  this.pos = this.kernel.packFp32Array(values, this.buf, this.pos);
656
1105
  } else {
657
- for (let i = 0; i < values.length; i++) {
658
- this.ensure(4);
659
- this.pos = packFp32(this.buf, this.pos, values[i]);
660
- }
1106
+ for (let i = 0; i < values.length; i++) this.putFp32(values[i]);
661
1107
  }
662
1108
  }
1109
+ /**
1110
+ * Write an fp32 array from its raw little-endian element payload. The bytes
1111
+ * are emitted verbatim — no per-element `setFloat32` — so a signaling NaN
1112
+ * survives bit-for-bit (§4.6), which {@link writeFp32Array} cannot guarantee
1113
+ * because it re-quantizes each JS `number`. `payload.length` must be a
1114
+ * multiple of 4; the element count is `payload.length / 4`.
1115
+ */
1116
+ writeFp32ArrayRaw(id, payload) {
1117
+ if ((payload.length & 3) !== 0) {
1118
+ throw argumentError(
1119
+ `fp32 array payload length ${payload.length} is not a multiple of 4`
1120
+ );
1121
+ }
1122
+ this.arrayHead(id, WireType.ArrayFixlen, payload.length >> 2);
1123
+ this.putVarintNum(4 * 8 + FixlenSubtype.Fp32);
1124
+ this.writeRaw(payload);
1125
+ }
663
1126
  /** Write an array of IEEE-754 64-bit doubles. */
664
1127
  writeFp64Array(id, values) {
665
1128
  this.arrayHead(id, WireType.ArrayFixlen, values.length);
666
1129
  this.putVarintNum(8 * 8 + FixlenSubtype.Fp64);
667
- if (this.canGrow) {
668
- this.ensure(values.length * 8);
1130
+ if (this.reserveBulk(values.length * 8)) {
669
1131
  this.pos = this.kernel.packFp64Array(values, this.buf, this.pos);
670
1132
  } else {
671
- for (let i = 0; i < values.length; i++) {
672
- this.ensure(8);
673
- this.pos = packFp64(this.buf, this.pos, values[i]);
674
- }
1133
+ for (let i = 0; i < values.length; i++) this.putFp64(values[i]);
675
1134
  }
676
1135
  }
677
1136
  // --- sequences ----------------------------------------------------------
678
- /** Open a nested sequence (a fresh id scope). */
679
- writeSequenceBegin(id) {
1137
+ /**
1138
+ * Open a nested sequence (a fresh id scope) whose header is **held back**
1139
+ * until the sequence turns out to have content.
1140
+ *
1141
+ * MESSAGE_SPEC §2 omits a sequence-typed field whose value equals its declared
1142
+ * default, and "not one child was written" is exactly that condition —
1143
+ * evaluated per child field, recursively, for free, because the message layer
1144
+ * already omits every child equal to its default. A sequence closed with
1145
+ * nothing in it therefore emits **nothing** instead of a two-byte empty frame,
1146
+ * and an all-default message becomes the empty byte string. No byte image is
1147
+ * ever compared, so in-memory layout never enters the decision.
1148
+ *
1149
+ * This is the only way to open a sequence. How it closes decides whether a
1150
+ * contentless one survives: {@link OStream.writeSequenceEnd} drops it,
1151
+ * {@link OStream.writeSequenceEndKeep} forces the frame out.
1152
+ */
1153
+ writeSequenceBeginLazy(id) {
680
1154
  if (this.depth >= MAX_DEPTH) {
681
- throw usageError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
1155
+ throw argumentError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
682
1156
  }
683
- this.header(id, WireType.SequenceStart);
1157
+ if (id >>> 0 !== id || id > ID_MAX) {
1158
+ throw argumentError(`field id ${id} out of range 0..${ID_MAX}`);
1159
+ }
1160
+ this.pending[this.nPending++] = id;
684
1161
  this.depth++;
685
1162
  }
686
- /** Close the current sequence. */
1163
+ /**
1164
+ * Close the current sequence, letting it **vanish** if it received no content.
1165
+ *
1166
+ * Use it wherever absence encodes the same value as an empty frame: a
1167
+ * `struct`/`union` field, and an array field whose declared `default` is the
1168
+ * empty collection (MESSAGE_SPEC §2). Where the frame must be visible, close
1169
+ * with {@link OStream.writeSequenceEndKeep} instead.
1170
+ *
1171
+ * An end with no matching begin is not rejected: the encoder writes what it is
1172
+ * told, and the resulting bytes are then malformed, which is the decoder's
1173
+ * verdict to make. No other port refuses it. The depth counter stops at zero
1174
+ * so the MAX_DEPTH check on begin cannot be fooled by an underflow.
1175
+ */
687
1176
  writeSequenceEnd() {
688
- if (this.depth <= 0) throw usageError("sequence end without matching begin");
1177
+ if (this.nPending !== 0) {
1178
+ this.nPending--;
1179
+ if (this.depth > 0) this.depth--;
1180
+ return;
1181
+ }
689
1182
  this.ensure(1);
690
1183
  this.buf[this.pos++] = WireType.SequenceEnd;
691
- this.depth--;
1184
+ if (this.depth > 0) this.depth--;
692
1185
  }
693
- // --- internals ----------------------------------------------------------
694
- /** Ensure exactly `value`'s varint size, then write it (bigint path). */
695
- putVarint(value) {
696
- this.ensure(varintSize(value));
697
- this.pos = encodeVarint(value, this.buf, this.pos);
1186
+ /**
1187
+ * Close the current sequence, **keeping** its frame even when it received no
1188
+ * content.
1189
+ *
1190
+ * Behaves like a write: it first emits any held-back headers — this frame's
1191
+ * and every enclosing one's — and then the end marker, so an empty sequence
1192
+ * reaches the wire as `begin` + `end`.
1193
+ *
1194
+ * Required wherever the frame carries information beyond its contents:
1195
+ * - a **wrapper-array element** (`struct`/`union`/nested row): element
1196
+ * presence is what carries a dynamic array's length — *highest present id +
1197
+ * 1* (MESSAGE_SPEC §5.1) — so dropping an all-default element would change
1198
+ * the decoded length, not just the bytes;
1199
+ * - an array field already known to **differ from a non-empty declared
1200
+ * `default`**: absence would reconstruct that default, so the empty frame is
1201
+ * the only encoding of "explicitly empty" (§2, §3).
1202
+ *
1203
+ * The two failure directions are not symmetric, which is why this is the safe
1204
+ * choice when in doubt: using it where {@link OStream.writeSequenceEnd} would
1205
+ * do costs one non-canonical empty frame that a decoder normalizes away, while
1206
+ * the reverse silently changes an array's length.
1207
+ */
1208
+ writeSequenceEndKeep() {
1209
+ if (this.nPending !== 0) this.commitPending();
1210
+ this.ensure(1);
1211
+ this.buf[this.pos++] = WireType.SequenceEnd;
1212
+ if (this.depth > 0) this.depth--;
698
1213
  }
1214
+ // --- internals ----------------------------------------------------------
699
1215
  /** Ensure exactly `value`'s varint size, then write it (number fast path). */
700
1216
  putVarintNum(value) {
701
- this.ensure(varintSizeNum(value));
702
- this.pos = encodeVarintNum(value, this.buf, this.pos);
703
- }
704
- header(id, type) {
705
- if (id < 0 || id > ID_MAX || !Number.isInteger(id)) {
706
- throw argumentError(`field id ${id} out of range 0..${ID_MAX}`);
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;
707
1222
  }
708
- this.putVarintNum(id * 8 + type);
1223
+ this.putVarintNumSlow(value);
709
1224
  }
710
- fixlenHead(id, length, subtype) {
711
- this.header(id, WireType.Fixlen);
712
- this.putVarintNum(length * 8 + subtype);
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);
713
1240
  }
714
- arrayHead(id, type, count) {
715
- if (count < 0 || count > ARRAY_MAX) {
716
- throw argumentError(`array count ${count} out of range 0..${ARRAY_MAX}`);
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;
717
1254
  }
718
- this.header(id, type);
719
- this.putVarintNum(count);
1255
+ this.putVarintLoHiSlow(lo, hi);
720
1256
  }
721
- /** Copy `data` out, flushing/growing as needed (large payloads stay chunked). */
722
- writeRaw(data) {
723
- let off = 0;
724
- while (off < data.length) {
725
- const room = this.ensureSome(data.length - off);
726
- this.buf.set(data.subarray(off, off + room), this.pos);
727
- this.pos += room;
728
- off += room;
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
+ }
729
1272
  }
1273
+ this.putVarintLoHiTight(lo, hi);
730
1274
  }
731
- /** Ensure `n` contiguous bytes are free at `pos`; returns `pos` for chaining. */
732
- ensure(n) {
733
- if (this.buf.length - this.pos >= n) return this.pos;
734
- this.flush();
735
- if (this.buf.length - this.pos >= n) return this.pos;
736
- if (this.canGrow) {
737
- this.growTo(this.pos + n);
738
- return this.pos;
739
- }
740
- throw bufferFullError(
741
- `output buffer full: need ${n} more bytes, have ${this.buf.length - this.pos}`
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
742
1290
  );
743
1291
  }
744
- /** Ensure *some* room (up to `want`); returns how many bytes are available. */
745
- ensureSome(want) {
746
- let room = this.buf.length - this.pos;
747
- if (room === 0) {
748
- this.flush();
749
- room = this.buf.length - this.pos;
750
- if (room === 0) {
751
- if (this.canGrow) {
752
- this.growTo(this.pos + want);
753
- room = this.buf.length - this.pos;
754
- } else {
755
- throw bufferFullError("output buffer full");
756
- }
757
- }
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;
758
1311
  }
759
- return Math.min(room, want);
760
1312
  }
761
- growTo(needed) {
762
- let cap = this.buf.length * 2;
763
- if (cap < needed) cap = needed;
764
- const next = new Uint8Array(cap);
765
- next.set(this.buf.subarray(0, this.pos));
766
- this.buf = next;
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);
767
1327
  }
768
- };
769
-
770
- // src/decode/fast.ts
771
- var TWO32 = 4294967296;
772
- function decodeContiguous(buf, root, limits) {
773
- new FastDecoder(buf, limits).run(root);
774
- }
775
- var FastDecoder = class {
776
- constructor(buf, limits) {
777
- this.p = 0;
778
- // Last varint, as two unsigned 32-bit halves (see readVarint).
779
- this.lo = 0;
780
- this.hi = 0;
781
- this.buf = buf;
782
- this.n = buf.length;
783
- this.view = new DataView(buf.buffer, buf.byteOffset, buf.length);
784
- this.maxArrayCount = limits?.maxArrayCount ?? Infinity;
785
- this.maxStringLen = limits?.maxStringLen ?? Infinity;
786
- this.maxBlobLen = limits?.maxBlobLen ?? Infinity;
787
- }
788
- run(root) {
789
- const stack = [root];
790
- let top = root;
791
- while (this.p < this.n) {
792
- this.readVarint();
793
- const type = this.lo & 7;
794
- if (type === WireType.SequenceEnd) {
795
- if (stack.length <= 1) throw invalidMsgError("unbalanced sequence end");
796
- top.sequenceEnd?.();
797
- stack.pop();
798
- top = stack[stack.length - 1];
799
- continue;
800
- }
801
- const id = this.upper();
802
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
803
- switch (type) {
804
- case WireType.Unsigned: {
805
- this.readVarint();
806
- top.unsigned?.(id, this.unsignedValue());
807
- break;
808
- }
809
- case WireType.Signed: {
810
- this.readVarint();
811
- top.signed?.(id, this.signedValue());
812
- break;
813
- }
814
- case WireType.Fixlen: {
815
- this.readVarint();
816
- const sub = this.lo & 7;
817
- const len = this.upper();
818
- if (sub > FixlenSubtype.Blob) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
819
- if (len > FIXLEN_MAX) throw invalidMsgError("fixlen length out of range");
820
- if (sub === FixlenSubtype.String && len > this.maxStringLen) {
821
- throw limitExceededError(`string length ${len} exceeds maxStringLen ${this.maxStringLen}`);
822
- }
823
- if (sub === FixlenSubtype.Blob && len > this.maxBlobLen) {
824
- throw limitExceededError(`blob length ${len} exceeds maxBlobLen ${this.maxBlobLen}`);
825
- }
826
- if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
827
- const want = sub === FixlenSubtype.Fp32 ? 4 : 8;
828
- if (len !== want) throw invalidMsgError("fixlen float length mismatch");
829
- const value = sub === FixlenSubtype.Fp32 ? this.readFp32() : this.readFp64();
830
- if (sub === FixlenSubtype.Fp32) top.fp32?.(id, value);
831
- else top.fp64?.(id, value);
832
- } else {
833
- const chunk = this.take(len);
834
- if (sub === FixlenSubtype.String) top.string?.(id, len, 0, chunk);
835
- else top.blob?.(id, len, 0, chunk);
836
- }
837
- break;
838
- }
839
- case WireType.ArrayUnsigned: {
840
- const count = this.arrayCount();
841
- top.arrayBegin?.(id, ArrayKind.Unsigned, count);
842
- for (let i = 0; i < count; i++) {
843
- this.readVarint();
844
- top.arrayUnsigned?.(id, i, this.unsignedValue());
845
- }
846
- top.arrayEnd?.(id);
847
- break;
848
- }
849
- case WireType.ArraySigned: {
850
- const count = this.arrayCount();
851
- top.arrayBegin?.(id, ArrayKind.Signed, count);
852
- for (let i = 0; i < count; i++) {
853
- this.readVarint();
854
- top.arraySigned?.(id, i, this.signedValue());
855
- }
856
- top.arrayEnd?.(id);
857
- break;
858
- }
859
- case WireType.ArrayFixlen: {
860
- const count = this.arrayCount();
861
- this.readVarint();
862
- const sub = this.lo & 7;
863
- const size = this.upper();
864
- let kind;
865
- if (sub === FixlenSubtype.Fp32 && size === 4) kind = ArrayKind.Fp32;
866
- else if (sub === FixlenSubtype.Fp64 && size === 8) kind = ArrayKind.Fp64;
867
- else throw invalidMsgError("invalid fixlen array element type");
868
- top.arrayBegin?.(id, kind, count);
869
- if (kind === ArrayKind.Fp32) {
870
- for (let i = 0; i < count; i++) {
871
- const value = this.readFp32();
872
- top.arrayFp32?.(id, i, value);
873
- }
874
- } else {
875
- for (let i = 0; i < count; i++) {
876
- const value = this.readFp64();
877
- top.arrayFp64?.(id, i, value);
878
- }
879
- }
880
- top.arrayEnd?.(id);
881
- break;
882
- }
883
- case WireType.SequenceStart: {
884
- if (stack.length - 1 >= MAX_DEPTH) {
885
- throw invalidMsgError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
886
- }
887
- const child = top.sequenceBegin?.(id);
888
- top = child ?? top;
889
- stack.push(top);
890
- break;
891
- }
892
- default:
893
- throw invalidMsgError(`invalid wire type ${type}`);
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;
894
1402
  }
1403
+ this.pos = p;
895
1404
  }
896
- if (stack.length > 1) throw incompleteError("truncated message: unbalanced sequence");
897
- }
898
- // --- field helpers ------------------------------------------------------
899
- /** Read and validate an array count word (0..ARRAY_MAX; §4.7/§4.8). */
900
- arrayCount() {
901
- this.readVarint();
902
- const count = this.num();
903
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
904
- if (count > this.maxArrayCount) {
905
- throw limitExceededError(`array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`);
906
- }
907
- return count;
908
- }
909
- /** Hand back a zero-copy view of the next `len` bytes, advancing the cursor. */
910
- take(len) {
911
- const start = this.p;
912
- const end = start + len;
913
- if (end > this.n) throw incompleteError("truncated fixlen payload");
914
- this.p = end;
915
- return this.buf.subarray(start, end);
916
- }
917
- readFp32() {
918
- const p = this.p;
919
- if (p + 4 > this.n) throw incompleteError("truncated fp32");
920
- this.p = p + 4;
921
- return this.view.getFloat32(p, true);
922
- }
923
- readFp64() {
924
- const p = this.p;
925
- if (p + 8 > this.n) throw incompleteError("truncated fp64");
926
- this.p = p + 8;
927
- return this.view.getFloat64(p, true);
928
- }
929
- // --- varint reading -----------------------------------------------------
930
- /** The last varint's full value as a `bigint` (64-bit fidelity). */
931
- big() {
932
- return this.hi === 0 ? BigInt(this.lo >>> 0) : BigInt(this.hi >>> 0) << 32n | BigInt(this.lo >>> 0);
933
- }
934
- /**
935
- * The last varint as an unsigned value, number-first: a `number` when it fits
936
- * exactly (`≤ 2^53-1` — all ids, u8..u32 and small u64s), a `bigint` only
937
- * beyond that. Skips the per-value bigint allocation on the common path.
938
- */
939
- unsignedValue() {
940
- const hi = this.hi >>> 0;
941
- return hi <= 2097151 ? hi * TWO32 + (this.lo >>> 0) : this.big();
942
- }
943
- /** The last zig-zag varint as a signed value, number-first (see {@link unsignedValue}). */
944
- signedValue() {
945
- const hi = this.hi >>> 0;
946
- if (hi <= 2097151) {
947
- const r = hi * TWO32 + (this.lo >>> 0);
948
- return r % 2 === 0 ? r / 2 : -(r + 1) / 2;
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;
949
1411
  }
950
- return zigzagDecode(this.big());
1412
+ this.putFp64Slow(value);
951
1413
  }
952
- /** The last varint's value as a JS number — exact for ids/lengths/counts. */
953
- num() {
954
- return this.hi * TWO32 + (this.lo >>> 0);
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);
955
1429
  }
956
- /** The last varint with its low 3 tag bits stripped (`value >> 3`). */
957
- upper() {
958
- return (this.hi >>> 0) * (TWO32 / 8) + (this.lo >>> 3);
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;
959
1439
  }
960
1440
  /**
961
- * Decode one LEB128 varint at the cursor into {@link lo} / {@link hi} (each an
962
- * unsigned 32-bit half), advancing {@link p}. Throws on truncation or a value
963
- * spilling past 64 bits (>10 bytes). Unrolled, number-only — no `bigint`.
1441
+ * Write a field header, the `(id << 3) | wireType` tag, as a varint.
1442
+ *
1443
+ * This is the single choke point every field write passes through — the
1444
+ * scalar, fixlen, float, string, blob and both array writers all reach the
1445
+ * wire through `header` / `fixlenHead` / `arrayHead`, and `fixlenHead` and
1446
+ * `arrayHead` are themselves nothing but `header` plus a follow-up varint. So
1447
+ * this is also where a held-back sequence run is committed: the field about to
1448
+ * be written is content, which means every enclosing sequence is non-default
1449
+ * and must be framed after all (MESSAGE_SPEC §2).
1450
+ *
1451
+ * The only writers that do *not* pass through here are the two sequence
1452
+ * closers, which must not commit ({@link OStream.writeSequenceEnd}) or commit
1453
+ * explicitly ({@link OStream.writeSequenceEndKeep}), and
1454
+ * {@link OStream.writeSequenceBeginLazy}, which writes no byte at all.
964
1455
  */
965
- readVarint() {
966
- const buf = this.buf;
967
- const n = this.n;
968
- let p = this.p;
969
- let b;
970
- let lo;
971
- let hi = 0;
972
- if (p >= n) throw incompleteError("truncated varint");
973
- b = buf[p++];
974
- lo = b & 127;
975
- if (b < 128) return this.set(lo, 0, p);
976
- if (p >= n) throw incompleteError("truncated varint");
977
- b = buf[p++];
978
- lo |= (b & 127) << 7;
979
- if (b < 128) return this.set(lo, 0, p);
980
- if (p >= n) throw incompleteError("truncated varint");
981
- b = buf[p++];
982
- lo |= (b & 127) << 14;
983
- if (b < 128) return this.set(lo, 0, p);
984
- if (p >= n) throw incompleteError("truncated varint");
985
- b = buf[p++];
986
- lo |= (b & 127) << 21;
987
- if (b < 128) return this.set(lo, 0, p);
988
- if (p >= n) throw incompleteError("truncated varint");
989
- b = buf[p++];
990
- lo |= (b & 15) << 28;
991
- hi = b >> 4 & 7;
992
- if (b < 128) return this.set(lo, hi, p);
993
- if (p >= n) throw incompleteError("truncated varint");
994
- b = buf[p++];
995
- hi |= (b & 127) << 3;
996
- if (b < 128) return this.set(lo, hi, p);
997
- if (p >= n) throw incompleteError("truncated varint");
998
- b = buf[p++];
999
- hi |= (b & 127) << 10;
1000
- if (b < 128) return this.set(lo, hi, p);
1001
- if (p >= n) throw incompleteError("truncated varint");
1002
- b = buf[p++];
1003
- hi |= (b & 127) << 17;
1004
- if (b < 128) return this.set(lo, hi, p);
1005
- if (p >= n) throw incompleteError("truncated varint");
1006
- b = buf[p++];
1007
- hi |= (b & 127) << 24;
1008
- if (b < 128) return this.set(lo, hi, p);
1009
- if (p >= n) throw incompleteError("truncated varint");
1010
- b = buf[p++];
1011
- if ((b & 127) >> 1 !== 0) throw invalidMsgError("varint overflow");
1012
- hi |= (b & 127) << 31;
1013
- if (b < 128) return this.set(lo, hi, p);
1014
- throw invalidMsgError("varint overflow");
1456
+ header(id, type) {
1457
+ if (id >>> 0 !== id || id > ID_MAX) {
1458
+ throw argumentError(`field id ${id} out of range 0..${ID_MAX}`);
1459
+ }
1460
+ if (this.nPending !== 0) this.commitPending();
1461
+ this.putVarintNum(id * 8 + type);
1462
+ }
1463
+ /**
1464
+ * Write out the held-back sequence headers, **outermost first**, and clear the
1465
+ * run. Runs at most once per non-default sequence, never per field — the cost
1466
+ * on the hot path is the single `nPending` test in {@link header}.
1467
+ *
1468
+ * The count is zeroed before the first byte goes out, so a write re-entered
1469
+ * from a flush sink cannot emit the same run twice.
1470
+ */
1471
+ commitPending() {
1472
+ const n = this.nPending;
1473
+ this.nPending = 0;
1474
+ const pending = this.pending;
1475
+ for (let i = 0; i < n; i++) {
1476
+ this.putVarintNum(pending[i] * 8 + WireType.SequenceStart);
1477
+ }
1478
+ }
1479
+ fixlenHead(id, length, subtype) {
1480
+ this.header(id, WireType.Fixlen);
1481
+ this.putVarintNum(length * 8 + subtype);
1482
+ }
1483
+ arrayHead(id, type, count) {
1484
+ if (count < 0 || count > ARRAY_MAX) {
1485
+ throw argumentError(`array count ${count} out of range 0..${ARRAY_MAX}`);
1486
+ }
1487
+ this.header(id, type);
1488
+ this.putVarintNum(count);
1489
+ }
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
+ */
1514
+ writeRaw(data) {
1515
+ const total = data.length;
1516
+ let off = 0;
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
+ }
1524
+ this.pos += room;
1525
+ off += room;
1526
+ }
1527
+ }
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;
1015
1549
  }
1016
- set(lo, hi, p) {
1017
- this.lo = lo;
1018
- this.hi = hi;
1019
- this.p = p;
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;
1579
+ }
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
+ );
1601
+ }
1602
+ return pos;
1603
+ }
1604
+ /**
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`.
1610
+ */
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;
1618
+ }
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);
1020
1628
  }
1021
1629
  };
1022
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
+
1023
1673
  // src/decode/state.ts
1024
- 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
+ }
1025
1706
  var DecoderState = class {
1026
- 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;
1027
1756
  this.state = 0 /* Header */;
1028
- this.stack = [];
1029
- // 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. */
1030
1803
  this.id = 0;
1031
- // Resumable varint accumulator, as two unsigned 32-bit halves (vLo / vHi)
1032
- // plus the byte count so far. Number-only: a `bigint` is built once, at the
1033
- // 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).
1034
1807
  this.vLo = 0;
1035
1808
  this.vHi = 0;
1036
1809
  this.vBytes = 0;
1037
1810
  this.vComplete = false;
1038
- // fixlen / fp scratch
1039
- 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;
1040
1819
  this.need = 0;
1041
1820
  this.have = 0;
1042
1821
  // fixlen string/blob streaming
@@ -1048,96 +1827,249 @@ var DecoderState = class {
1048
1827
  this.arrIsFixlen = false;
1049
1828
  this.arrCount = 0;
1050
1829
  this.arrIndex = 0;
1051
- this.maxArrayCount = limits?.maxArrayCount ?? Infinity;
1052
- this.maxStringLen = limits?.maxStringLen ?? Infinity;
1053
- 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);
1054
1855
  }
1055
- /** Feed `input` to the machine, dispatching to `root` and its sub-visitors. */
1056
- push(input, root) {
1057
- if (this.stack.length === 0) this.stack.push(root);
1058
- 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) {
1059
1933
  const n = input.length;
1934
+ let i = 0;
1060
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
+ }
1061
2015
  switch (this.state) {
1062
2016
  case 0 /* Header */: {
1063
2017
  i = this.varintStep(input, i);
1064
2018
  if (!this.vComplete) return;
1065
- 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`);
1066
2022
  if (type === WireType.SequenceEnd) {
1067
- this.resetVarint();
1068
2023
  this.endSequence();
1069
2024
  break;
1070
2025
  }
1071
- const id = this.vUpper();
1072
- this.resetVarint();
1073
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
1074
2026
  this.id = id;
2027
+ this.cur.fieldBegin?.(id, type);
1075
2028
  this.dispatch(type);
1076
2029
  break;
1077
2030
  }
1078
2031
  case 1 /* ScalarU */: {
1079
2032
  i = this.varintStep(input, i);
1080
2033
  if (!this.vComplete) return;
1081
- const value = this.vUnsigned();
1082
- this.resetVarint();
1083
- this.top().unsigned?.(this.id, value);
1084
2034
  this.state = 0 /* Header */;
2035
+ this.cur.unsigned?.(this.id, this.vUnsigned(), this.vLo >>> 0, this.vHi >>> 0);
1085
2036
  break;
1086
2037
  }
1087
2038
  case 2 /* ScalarS */: {
1088
2039
  i = this.varintStep(input, i);
1089
2040
  if (!this.vComplete) return;
1090
- const value = this.vSigned();
1091
- this.resetVarint();
1092
- this.top().signed?.(this.id, value);
1093
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
+ );
1094
2051
  break;
1095
2052
  }
1096
- case 3 /* FixlenLen */: {
2053
+ case 3 /* FixlenWord */: {
1097
2054
  i = this.varintStep(input, i);
1098
2055
  if (!this.vComplete) return;
1099
- const sub = this.vTag();
1100
- const len = this.vUpper();
1101
- this.resetVarint();
1102
- if (sub > FixlenSubtype.Blob) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1103
- if (len > FIXLEN_MAX) throw invalidMsgError("fixlen length out of range");
1104
- if (sub === FixlenSubtype.String && len > this.maxStringLen) {
1105
- throw limitExceededError(`string length ${len} exceeds maxStringLen ${this.maxStringLen}`);
1106
- }
1107
- if (sub === FixlenSubtype.Blob && len > this.maxBlobLen) {
1108
- throw limitExceededError(`blob length ${len} exceeds maxBlobLen ${this.maxBlobLen}`);
1109
- }
1110
- this.fixSub = sub;
1111
- this.fixLen = len;
1112
- this.fixOff = 0;
1113
- if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
1114
- const want = sub === FixlenSubtype.Fp32 ? 4 : 8;
1115
- if (this.fixLen !== want) throw invalidMsgError("fixlen float length mismatch");
1116
- this.need = want;
1117
- this.have = 0;
1118
- this.state = 4 /* FixlenFp */;
1119
- } else {
1120
- if (this.fixLen === 0) {
1121
- this.emitBytes(input.subarray(0, 0));
1122
- this.state = 0 /* Header */;
1123
- } else {
1124
- this.state = 5 /* FixlenBytes */;
1125
- }
1126
- }
2056
+ i = this.fixlenWord(input, i, n);
1127
2057
  break;
1128
2058
  }
1129
2059
  case 4 /* FixlenFp */: {
1130
- i = this.fpStep(input, i);
2060
+ i = this.fpStep(input, i, n);
1131
2061
  if (this.have < this.need) return;
1132
- const value = this.fixSub === FixlenSubtype.Fp32 ? unpackFp32(this.scratch, 0) : unpackFp64(this.scratch, 0);
1133
- if (this.fixSub === FixlenSubtype.Fp32) this.top().fp32?.(this.id, value);
1134
- else this.top().fp64?.(this.id, value);
1135
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
+ }
1136
2068
  break;
1137
2069
  }
1138
2070
  case 5 /* FixlenBytes */: {
1139
2071
  const take = Math.min(n - i, this.fixLen - this.fixOff);
1140
- this.emitBytes(input.subarray(i, i + take));
2072
+ this.emitBytes(input, i, i + take);
1141
2073
  i += take;
1142
2074
  this.fixOff += take;
1143
2075
  if (this.fixOff === this.fixLen) this.state = 0 /* Header */;
@@ -1147,75 +2079,95 @@ var DecoderState = class {
1147
2079
  i = this.varintStep(input, i);
1148
2080
  if (!this.vComplete) return;
1149
2081
  const count = this.vNum();
1150
- this.resetVarint();
1151
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1152
- if (count > this.maxArrayCount) {
1153
- throw limitExceededError(`array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`);
1154
- }
2082
+ if (count > ARRAY_MAX) this.fail("array count out of range");
1155
2083
  this.arrCount = count;
1156
2084
  this.arrIndex = 0;
1157
2085
  if (this.arrIsFixlen) {
1158
- this.state = 9 /* ArrayElemLen */;
2086
+ this.state = 8 /* ArrayElemWord */;
1159
2087
  } else if (count === 0) {
1160
- this.top().arrayBegin?.(this.id, this.arrKind, 0);
1161
- this.top().arrayEnd?.(this.id);
1162
- this.state = 0 /* Header */;
2088
+ this.cur.arrayBegin?.(this.id, this.arrKind, 0);
2089
+ this.askBulk(this.arrKind, 0);
2090
+ this.endArray();
1163
2091
  } else {
1164
- this.top().arrayBegin?.(this.id, this.arrKind, this.arrCount);
1165
- 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);
1166
2095
  }
1167
2096
  break;
1168
2097
  }
1169
- case 7 /* ArrayUElem */: {
1170
- i = this.varintStep(input, i);
1171
- if (!this.vComplete) return;
1172
- const value = this.vUnsigned();
1173
- this.resetVarint();
1174
- this.top().arrayUnsigned?.(this.id, this.arrIndex, value);
1175
- this.advanceArray();
1176
- break;
1177
- }
1178
- 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;
1179
2119
  i = this.varintStep(input, i);
1180
2120
  if (!this.vComplete) return;
1181
- const value = this.vSigned();
1182
- this.resetVarint();
1183
- this.top().arraySigned?.(this.id, this.arrIndex, value);
1184
2121
  this.advanceArray();
1185
2122
  break;
1186
2123
  }
1187
- case 9 /* ArrayElemLen */: {
2124
+ case 8 /* ArrayElemWord */: {
1188
2125
  i = this.varintStep(input, i);
1189
2126
  if (!this.vComplete) return;
1190
- const sub = this.vTag();
2127
+ const sub = this.vLo & 7;
1191
2128
  const size = this.vUpper();
1192
- this.resetVarint();
1193
2129
  if (sub === FixlenSubtype.Fp32 && size === 4) {
1194
2130
  this.arrKind = ArrayKind.Fp32;
1195
- this.need = 4;
2131
+ this.fpBegin(4);
1196
2132
  } else if (sub === FixlenSubtype.Fp64 && size === 8) {
1197
2133
  this.arrKind = ArrayKind.Fp64;
1198
- this.need = 8;
2134
+ this.fpBegin(8);
1199
2135
  } else {
1200
- throw invalidMsgError("invalid fixlen array element type");
2136
+ this.fail("invalid fixlen array element type");
1201
2137
  }
1202
- this.top().arrayBegin?.(this.id, this.arrKind, this.arrCount);
1203
2138
  if (this.arrCount === 0) {
1204
- this.top().arrayEnd?.(this.id);
1205
- this.state = 0 /* Header */;
2139
+ this.cur.arrayBegin?.(this.id, this.arrKind, 0);
2140
+ this.askBulk(this.arrKind, 0);
2141
+ this.endArray();
1206
2142
  } else {
1207
- this.have = 0;
1208
- 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);
1209
2146
  }
1210
2147
  break;
1211
2148
  }
1212
- case 10 /* ArrayFp */: {
1213
- 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);
1214
2169
  if (this.have < this.need) return;
1215
- const value = this.arrKind === ArrayKind.Fp32 ? unpackFp32(this.scratch, 0) : unpackFp64(this.scratch, 0);
1216
- if (this.arrKind === ArrayKind.Fp32) this.top().arrayFp32?.(this.id, this.arrIndex, value);
1217
- else this.top().arrayFp64?.(this.id, this.arrIndex, value);
1218
- this.have = 0;
2170
+ this.fpBegin(size);
1219
2171
  this.advanceArray();
1220
2172
  break;
1221
2173
  }
@@ -1223,20 +2175,104 @@ var DecoderState = class {
1223
2175
  }
1224
2176
  }
1225
2177
  /**
1226
- * Report the terminal decode outcome (MESSAGE_SPEC §7) *without* promoting it
1227
- * to an error. Returns {@link DecodeStatus.Complete} when the stream ended
1228
- * exactly at a field boundary, or {@link DecodeStatus.Incomplete} when it
1229
- * ended inside a field (a partial varint, an unfinished payload / array, or a
1230
- * still-open nested sequence). This is a pure accessor — the finish-less spec
1231
- * has no finalize step, and a trailing `Incomplete` is a truncation the caller
1232
- * decides how to treat, not an error this machine raises. A genuinely
1233
- * 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.
1234
2199
  */
1235
- finish() {
1236
- 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;
1237
2202
  return atBoundary ? DecodeStatus.Complete : DecodeStatus.Incomplete;
1238
2203
  }
1239
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
+ }
1240
2276
  dispatch(type) {
1241
2277
  switch (type) {
1242
2278
  case WireType.Unsigned:
@@ -1246,7 +2282,7 @@ var DecoderState = class {
1246
2282
  this.state = 2 /* ScalarS */;
1247
2283
  break;
1248
2284
  case WireType.Fixlen:
1249
- this.state = 3 /* FixlenLen */;
2285
+ this.state = 3 /* FixlenWord */;
1250
2286
  break;
1251
2287
  case WireType.ArrayUnsigned:
1252
2288
  this.arrKind = ArrayKind.Unsigned;
@@ -1262,39 +2298,630 @@ var DecoderState = class {
1262
2298
  this.arrIsFixlen = true;
1263
2299
  this.state = 6 /* ArrayCount */;
1264
2300
  break;
1265
- case WireType.SequenceStart: {
1266
- if (this.stack.length - 1 >= MAX_DEPTH) {
1267
- throw invalidMsgError(`nesting exceeds MAX_DEPTH (${MAX_DEPTH})`);
1268
- }
1269
- const child = this.top().sequenceBegin?.(this.id);
1270
- this.stack.push(child ?? this.top());
1271
- this.state = 0 /* Header */;
2301
+ case WireType.SequenceStart:
2302
+ this.beginSequence();
1272
2303
  break;
1273
- }
1274
2304
  default:
1275
- throw invalidMsgError(`invalid wire type ${type}`);
2305
+ this.fail(`invalid wire type ${type}`);
1276
2306
  }
1277
2307
  }
1278
- endSequence() {
1279
- if (this.stack.length <= 1) throw invalidMsgError("unbalanced sequence end");
1280
- this.top().sequenceEnd?.();
1281
- this.stack.pop();
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;
2323
+ }
2324
+ this.seqIds[d] = this.id;
2325
+ this.depth = d + 1;
1282
2326
  this.state = 0 /* Header */;
1283
2327
  }
1284
- advanceArray() {
1285
- this.arrIndex++;
1286
- if (this.arrIndex === this.arrCount) {
1287
- this.top().arrayEnd?.(this.id);
2328
+ endSequence() {
2329
+ const d = this.depth;
2330
+ if (d === 0) this.fail("unbalanced sequence end");
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);
2342
+ }
2343
+ advanceArray() {
2344
+ if (++this.arrIndex === this.arrCount) {
1288
2345
  this.state = 0 /* Header */;
2346
+ this.cur.arrayEnd?.(this.id);
2347
+ }
2348
+ }
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;
2388
+ }
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;
2415
+ }
2416
+ /**
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.
2425
+ */
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
+ );
2437
+ }
2438
+ if (dest.length < count) {
2439
+ throw argumentError(
2440
+ `array ${this.id}: ${is32 ? "fp32" : "fp64"} destination holds ${dest.length} of ${count} elements`
2441
+ );
2442
+ }
2443
+ if (!is32) return 9 /* F64 */;
2444
+ return f.bits !== void 0 ? 8 /* F32Bits */ : 7 /* F32 */;
2445
+ }
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`);
1289
2508
  }
2509
+ return it.minHi === 0 && it.maxHi === 0 ? 1 /* Values32 */ : 0 /* Values */;
1290
2510
  }
1291
- emitBytes(chunk) {
1292
- const v = this.top();
1293
- if (this.fixSub === FixlenSubtype.String) v.string?.(this.id, this.fixLen, this.fixOff, chunk);
1294
- else v.blob?.(this.id, this.fixLen, this.fixOff, chunk);
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 */;
1295
2540
  }
1296
- top() {
1297
- return this.stack[this.stack.length - 1];
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
+ }
1298
2925
  }
1299
2926
  /**
1300
2927
  * Consume varint bytes from `input` at `i` into the {@link vLo} / {@link vHi}
@@ -1302,661 +2929,662 @@ var DecoderState = class {
1302
2929
  * terminator byte arrives. Number-only — no per-byte `bigint`.
1303
2930
  */
1304
2931
  varintStep(input, i) {
1305
- let lo = this.vLo;
1306
- let hi = this.vHi;
1307
- let k = this.vBytes;
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;
1308
2965
  const n = input.length;
1309
2966
  while (i < n) {
1310
- if (k >= VARINT_MAX_BYTES) throw invalidMsgError("varint overflow");
2967
+ if (k >= VARINT_MAX_BYTES) this.fail("varint overflow");
1311
2968
  const b = input[i++];
1312
2969
  if (k < 4) lo |= (b & 127) << 7 * k;
1313
2970
  else if (k === 4) {
1314
2971
  lo |= (b & 15) << 28;
1315
2972
  hi |= b >> 4 & 7;
1316
2973
  } else {
1317
- if (k === 9 && (b & 127) >> 1 !== 0) throw invalidMsgError("varint overflow");
2974
+ if (k === 9 && (b & 127) >> 1 !== 0) this.fail("varint overflow");
1318
2975
  hi |= (b & 127) << 7 * k - 32;
1319
2976
  }
1320
2977
  k++;
1321
2978
  if ((b & 128) === 0) {
1322
2979
  this.vLo = lo;
1323
2980
  this.vHi = hi;
1324
- this.vBytes = k;
2981
+ this.vBytes = 0;
1325
2982
  this.vComplete = true;
1326
2983
  return i;
1327
2984
  }
1328
2985
  }
2986
+ if (k >= VARINT_MAX_BYTES) this.fail("varint overflow");
1329
2987
  this.vLo = lo;
1330
2988
  this.vHi = hi;
1331
2989
  this.vBytes = k;
1332
2990
  this.vComplete = false;
1333
2991
  return i;
1334
2992
  }
1335
- resetVarint() {
1336
- this.vLo = 0;
1337
- this.vHi = 0;
1338
- this.vBytes = 0;
1339
- this.vComplete = false;
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;
1340
3024
  }
1341
- /** The accumulated varint as a `bigint` (full 64-bit fidelity). */
1342
- vBig() {
1343
- return this.vHi === 0 ? BigInt(this.vLo >>> 0) : BigInt(this.vHi >>> 0) << 32n | BigInt(this.vLo >>> 0);
3025
+ /**
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;
1344
3078
  }
1345
3079
  /**
1346
- * The accumulated varint as an unsigned value, number-first: a `number` when
1347
- * it fits exactly (`≤ 2^53-1`, which covers all ids, u8..u32 and small u64s),
1348
- * a `bigint` only beyond that. Avoids a bigint allocation on the common path.
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.
1349
3083
  */
1350
3084
  vUnsigned() {
1351
3085
  const hi = this.vHi >>> 0;
1352
- return hi <= 2097151 ? hi * TWO322 + (this.vLo >>> 0) : this.vBig();
3086
+ return hi <= 2097151 ? hi * TWO32 + (this.vLo >>> 0) : joinU64(this.vLo >>> 0, hi);
1353
3087
  }
1354
3088
  /** The accumulated zig-zag varint as a signed value, number-first (see {@link vUnsigned}). */
1355
3089
  vSigned() {
1356
3090
  const hi = this.vHi >>> 0;
1357
3091
  if (hi <= 2097151) {
1358
- const r = hi * TWO322 + (this.vLo >>> 0);
3092
+ const r = hi * TWO32 + (this.vLo >>> 0);
1359
3093
  return r % 2 === 0 ? r / 2 : -(r + 1) / 2;
1360
3094
  }
1361
- 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
+ );
1362
3101
  }
1363
- /** 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
+ */
1364
3109
  vNum() {
1365
- return this.vHi * TWO322 + (this.vLo >>> 0);
1366
- }
1367
- /** The accumulated varint's low 3 tag bits (the wire type / fixlen subtype). */
1368
- vTag() {
1369
- return this.vLo & 7;
3110
+ return (this.vHi >>> 0) * TWO32 + (this.vLo >>> 0);
1370
3111
  }
1371
3112
  /** The accumulated varint with its low 3 tag bits stripped (`value >> 3`). */
1372
3113
  vUpper() {
1373
- return (this.vHi >>> 0) * (TWO322 / 8) + (this.vLo >>> 3);
3114
+ return (this.vHi >>> 0) * (TWO32 / 8) + (this.vLo >>> 3);
1374
3115
  }
1375
- /** Accumulate `need` raw bytes into {@link scratch}. */
1376
- fpStep(input, i) {
1377
- while (this.have < this.need && i < input.length) {
1378
- 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;
1379
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;
1380
3138
  return i;
1381
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
+ }
1382
3147
  };
3148
+ function u32le(b, i) {
3149
+ return (b[i] | b[i + 1] << 8 | b[i + 2] << 16 | b[i + 3] << 24) >>> 0;
3150
+ }
1383
3151
 
1384
3152
  // src/decode/istream.ts
1385
3153
  var IStream = class {
1386
3154
  /**
1387
- * @param limits Optional opt-in decode caps ({@link DecodeLimits}). An
1388
- * over-limit array count or string / blob length throws {@link SofabError}
1389
- * (`LIMIT_EXCEEDED`) from {@link feed}, at the offending field's header and
1390
- * before any of its payload is streamed to the visitor. Omit for no caps.
1391
- */
1392
- constructor(limits) {
1393
- this.state = new DecoderState(limits);
1394
- }
1395
- /**
1396
- * Feed a chunk of bytes, dispatching decoded fields to `visitor`. Throws
1397
- * {@link SofabError} (`INVALID_MSG`) only if the bytes are *malformed*;
1398
- * running out of bytes mid-field is not an error — it simply suspends until
1399
- * 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).
1400
3157
  */
1401
- feed(chunk, visitor) {
1402
- this.state.push(chunk, visitor);
3158
+ constructor(visitor) {
3159
+ this.state = new DecoderState(visitor);
1403
3160
  }
1404
3161
  /**
1405
- * Report whether the stream ended exactly at a field boundary. Call after the
1406
- * final {@link feed}: returns {@link DecodeStatus.Complete} at a clean field
1407
- * boundary, or {@link DecodeStatus.Incomplete} if the last chunk ended inside
1408
- * a field (a partial varint, an unfinished payload / array, or a still-open
1409
- * 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.
1410
3169
  *
1411
- * Per the finish-less spec (MESSAGE_SPEC §7) this is a pure accessor: it never
1412
- * throws and never promotes an incomplete decode to an error — the caller owns
1413
- * end-of-input and decides whether a trailing `Incomplete` is a truncation
1414
- * 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.
1415
3203
  */
1416
- end() {
1417
- return this.state.finish();
3204
+ feed(chunk) {
3205
+ this.state.push(chunk);
3206
+ return this.state.outcome();
1418
3207
  }
1419
3208
  };
1420
- function decode(bytes, visitor, limits) {
1421
- 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
+ }
1422
3222
  }
3223
+ var pooled = null;
1423
3224
 
1424
- // src/decode/cursor.ts
1425
- var TWO323 = 4294967296;
3225
+ // src/decode/text.ts
1426
3226
  var _utf8 = new TextDecoder("utf-8", { fatal: true });
1427
- var Cursor = class {
1428
- constructor(buf, limits) {
1429
- /** Field id of the header last accepted by {@link readHeader}. */
1430
- this.id = 0;
1431
- /** Wire type of the header last accepted by {@link readHeader}. */
1432
- this.wire = 0;
1433
- /**
1434
- * Fixlen subtype of the header last accepted by {@link readHeader} — one of
1435
- * {@link FixlenSubtype} — when its {@link wire} is {@link WireType.Fixlen} or
1436
- * {@link WireType.ArrayFixlen}; `-1` otherwise (a non-fixlen field, or a
1437
- * fixlen field whose subtype word is truncated away).
1438
- *
1439
- * The four fixlen subtypes (`fp32`, `fp64`, `string`, `blob`) all share one
1440
- * {@link wire} type, so {@link wire} alone cannot separate them. This is the
1441
- * companion accessor that can: a generated guard reads it right after
1442
- * {@link readHeader} to skip a field whose delivered subtype contradicts the
1443
- * schema (MESSAGE_SPEC §7.3), exactly as it already does on {@link wire} for
1444
- * the other kinds:
1445
- *
1446
- * ```ts
1447
- * case 9: if (c.wire !== WireType.Fixlen || c.fixSub !== FixlenSubtype.Fp64) {
1448
- * c.skip(c.wire); break;
1449
- * } o.somefp64 = c.readFp64(); break;
1450
- * ```
1451
- *
1452
- * It is *peeked* — the subtype word is not consumed — so the matching typed
1453
- * reader (or {@link skip}) still reads and validates it, and a malformed or
1454
- * truncated word surfaces `INVALID` / `INCOMPLETE` there as before.
1455
- */
1456
- this.fixSub = -1;
1457
- this.p = 0;
1458
- // Last varint, as two unsigned 32-bit halves (see readVarint).
1459
- this.lo = 0;
1460
- this.hi = 0;
1461
- // Number of nested sequences currently open (0 = root). Incremented when
1462
- // readHeader accepts a SequenceStart, decremented when it consumes the matching
1463
- // SequenceEnd (or when skip() discards a whole nested sequence). Lets the pull
1464
- // parser tell a root-level dangling sequence-end (INVALID) and an unclosed
1465
- // sequence at end-of-buffer (INCOMPLETE) apart from a clean boundary.
1466
- this.depth = 0;
1467
- this.buf = buf;
1468
- this.n = buf.length;
1469
- this.view = new DataView(buf.buffer, buf.byteOffset, buf.length);
1470
- this.maxArrayCount = limits?.maxArrayCount ?? Infinity;
1471
- this.maxStringLen = limits?.maxStringLen ?? Infinity;
1472
- this.maxBlobLen = limits?.maxBlobLen ?? Infinity;
1473
- }
1474
- /**
1475
- * Advance to the next field header. Returns `true` and sets {@link id} /
1476
- * {@link wire} when a field follows; returns `false` — consuming the marker —
1477
- * at the end of the buffer *or* at the sequence-end that closes the sequence
1478
- * this decoder is reading. So a generated per-type decoder loops uniformly:
1479
- *
1480
- * ```ts
1481
- * while (c.readHeader()) {
1482
- * switch (c.id) {
1483
- * case 4: this.u32 = Number(c.readUnsigned()); break;
1484
- * case 10: this.child = Child.decodeFrom(c); break; // nested sequence
1485
- * default: c.skip(c.wire); break; // unknown field
1486
- * }
1487
- * }
1488
- * ```
1489
- *
1490
- * At the root the loop ends at end-of-buffer; inside a nested sequence it ends
1491
- * at the matching {@link WireType.SequenceEnd} (which is consumed). A field
1492
- * whose id is out of range throws {@link SofabError} (`INVALID_MSG`).
1493
- */
1494
- readHeader() {
1495
- if (this.p >= this.n) {
1496
- if (this.depth > 0) {
1497
- 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;
1498
3237
  }
1499
- return false;
1500
3238
  }
1501
- this.readVarint();
1502
- const wire = this.lo & 7;
1503
- if (wire === WireType.SequenceEnd) {
1504
- if (this.depth === 0) {
1505
- throw invalidMsgError("unbalanced sequence end");
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]);
1506
3273
  }
1507
- this.depth--;
1508
- return false;
1509
- }
1510
- const id = this.upper();
1511
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
1512
- if (wire === WireType.SequenceStart) this.depth++;
1513
- this.id = id;
1514
- this.wire = wire;
1515
- this.fixSub = this.peekFixSub(wire);
1516
- return true;
1517
- }
1518
- /** Read an unsigned scalar (wire {@link WireType.Unsigned}), number-first. */
1519
- readUnsigned() {
1520
- this.readVarint();
1521
- return this.unsignedValue();
1522
- }
1523
- /** Read a signed scalar (wire {@link WireType.Signed}), zig-zag, number-first. */
1524
- readSigned() {
1525
- this.readVarint();
1526
- return this.signedValue();
1527
- }
1528
- /** Read a 32-bit float scalar (wire {@link WireType.Fixlen}, subtype fp32). */
1529
- readFp32() {
1530
- this.fixlenHeader(FixlenSubtype.Fp32, 4);
1531
- return this.rawFp32();
1532
- }
1533
- /** Read a 64-bit float scalar (wire {@link WireType.Fixlen}, subtype fp64). */
1534
- readFp64() {
1535
- this.fixlenHeader(FixlenSubtype.Fp64, 8);
1536
- return this.rawFp64();
1537
- }
1538
- /** Read a UTF-8 string scalar (wire {@link WireType.Fixlen}, subtype string). */
1539
- readString() {
1540
- const len = this.fixlenLen(FixlenSubtype.String);
1541
- const bytes = this.take(len);
1542
- try {
1543
- return _utf8.decode(bytes);
1544
- } catch {
1545
- throw invalidMsgError("invalid UTF-8 in string");
1546
- }
1547
- }
1548
- /**
1549
- * Read a blob scalar (wire {@link WireType.Fixlen}, subtype blob) as a
1550
- * zero-copy {@link Uint8Array} view into the source buffer.
1551
- */
1552
- readBlob() {
1553
- const len = this.fixlenLen(FixlenSubtype.Blob);
1554
- return this.take(len);
1555
- }
1556
- /** Read an unsigned array (wire {@link WireType.ArrayUnsigned}), number-first per element. */
1557
- readUnsignedArray() {
1558
- const count = this.arrayCount();
1559
- const out = new Array(count);
1560
- for (let i = 0; i < count; i++) {
1561
- this.readVarint();
1562
- out[i] = this.unsignedValue();
1563
- }
1564
- return out;
1565
- }
1566
- /** Read a signed array (wire {@link WireType.ArraySigned}), zig-zag, number-first per element. */
1567
- readSignedArray() {
1568
- const count = this.arrayCount();
1569
- const out = new Array(count);
1570
- for (let i = 0; i < count; i++) {
1571
- this.readVarint();
1572
- out[i] = this.signedValue();
1573
- }
1574
- return out;
1575
- }
1576
- /**
1577
- * Read an unsigned 64-bit array into {@link Long}[] — the `bigint`-free path.
1578
- * Each element keeps the raw lo/hi halves; call {@link Long.toBigInt} to
1579
- * materialise only the values the caller actually needs.
1580
- */
1581
- readUnsignedArrayLong() {
1582
- const count = this.arrayCount();
1583
- const out = new Array(count);
1584
- for (let i = 0; i < count; i++) {
1585
- this.readVarint();
1586
- out[i] = new Long(this.lo, this.hi);
1587
- }
1588
- return out;
1589
- }
1590
- /** Read a signed 64-bit array (zig-zag) into {@link Long}[] — the `bigint`-free path. */
1591
- readSignedArrayLong() {
1592
- const count = this.arrayCount();
1593
- const out = new Array(count);
1594
- for (let i = 0; i < count; i++) {
1595
- this.readVarint();
1596
- const lo = this.lo >>> 0;
1597
- const hi = this.hi >>> 0;
1598
- const mask = -(lo & 1) >>> 0;
1599
- out[i] = new Long((lo >>> 1 | hi << 31) >>> 0 ^ mask, hi >>> 1 >>> 0 ^ mask);
1600
- }
1601
- return out;
1602
- }
1603
- /** Read an fp32 array (wire {@link WireType.ArrayFixlen}, element subtype fp32). */
1604
- readFp32Array() {
1605
- const count = this.arrayFixlenHeader(FixlenSubtype.Fp32, 4);
1606
- const out = new Array(count);
1607
- for (let i = 0; i < count; i++) out[i] = this.rawFp32();
1608
- return out;
1609
- }
1610
- /** Read an fp64 array (wire {@link WireType.ArrayFixlen}, element subtype fp64). */
1611
- readFp64Array() {
1612
- const count = this.arrayFixlenHeader(FixlenSubtype.Fp64, 8);
1613
- const out = new Array(count);
1614
- for (let i = 0; i < count; i++) out[i] = this.rawFp64();
1615
- return out;
1616
- }
1617
- /**
1618
- * Consume the value of the field whose header {@link readHeader} just accepted,
1619
- * discarding it — for a `default:` branch that keeps the cursor in sync on an
1620
- * unknown id. Pass {@link wire}. A {@link WireType.SequenceStart} skips the
1621
- * whole nested sequence.
1622
- */
1623
- skip(wire) {
1624
- if (wire === WireType.SequenceStart) {
1625
- this.skipSequence();
1626
- this.depth--;
1627
- return;
1628
3274
  }
1629
- this.skipValue(wire);
1630
3275
  }
1631
- // --- value skipping -----------------------------------------------------
1632
- skipValue(wire) {
1633
- switch (wire) {
1634
- case WireType.Unsigned:
1635
- case WireType.Signed:
1636
- this.readVarint();
1637
- return;
1638
- case WireType.Fixlen: {
1639
- this.readVarint();
1640
- const sub = this.lo & 7;
1641
- const len = this.upper();
1642
- if (sub > FixlenSubtype.Blob) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1643
- if (sub === FixlenSubtype.Fp32 || sub === FixlenSubtype.Fp64) {
1644
- if (len !== (sub === FixlenSubtype.Fp32 ? 4 : 8)) {
1645
- throw invalidMsgError("fixlen float length mismatch");
1646
- }
1647
- } else if (len > FIXLEN_MAX) {
1648
- throw invalidMsgError("fixlen length out of range");
1649
- }
1650
- this.take(len);
1651
- return;
1652
- }
1653
- case WireType.ArrayUnsigned:
1654
- case WireType.ArraySigned: {
1655
- const count = this.arrayCount();
1656
- for (let i = 0; i < count; i++) this.readVarint();
1657
- return;
1658
- }
1659
- case WireType.ArrayFixlen: {
1660
- this.readVarint();
1661
- const count = this.num();
1662
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1663
- if (count > this.maxArrayCount) {
1664
- throw limitExceededError(
1665
- `array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`
1666
- );
1667
- }
1668
- this.readVarint();
1669
- const sub = this.lo & 7;
1670
- const size = this.upper();
1671
- const ok = sub === FixlenSubtype.Fp32 && size === 4 || sub === FixlenSubtype.Fp64 && size === 8;
1672
- if (!ok) throw invalidMsgError("invalid fixlen array element type");
1673
- this.take(count * size);
1674
- return;
1675
- }
1676
- default:
1677
- throw invalidMsgError(`invalid wire type ${wire}`);
1678
- }
3276
+ try {
3277
+ return _utf8.decode(buf.subarray(start, end));
3278
+ } catch {
3279
+ throw invalidMsgError("invalid UTF-8 in string");
1679
3280
  }
1680
- skipSequence() {
1681
- let depth = 1;
1682
- while (depth > 0) {
1683
- if (this.p >= this.n) throw incompleteError("truncated message: unbalanced sequence");
1684
- this.readVarint();
1685
- const wire = this.lo & 7;
1686
- if (wire === WireType.SequenceEnd) {
1687
- depth--;
1688
- continue;
1689
- }
1690
- const id = this.upper();
1691
- if (id > ID_MAX) throw invalidMsgError(`field id ${id} out of range`);
1692
- if (wire === WireType.SequenceStart) depth++;
1693
- else this.skipValue(wire);
1694
- }
3281
+ }
3282
+
3283
+ // src/decode/acc.ts
3284
+ var PayloadAcc = class {
3285
+ constructor() {
3286
+ this.buf = null;
3287
+ this.len = 0;
1695
3288
  }
1696
- // --- field helpers ------------------------------------------------------
1697
3289
  /**
1698
- * Peek the delivered fixlen subtype of the field {@link readHeader} just
1699
- * accepted, **without advancing the cursor** — the readers / {@link skip}
1700
- * still re-read and validate the word. Returns one of {@link FixlenSubtype}
1701
- * (0..3), a reserved value (4..7), or `-1` when the wire is not a fixlen kind
1702
- * 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.
1703
3297
  *
1704
- * The subtype is the low 3 bits of the fixlen sub-header word, and the low
1705
- * bits of a LEB128 word live entirely in its **first** byte — so this only
1706
- * 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.
1707
3301
  */
1708
- peekFixSub(wire) {
1709
- if (wire === WireType.Fixlen) {
1710
- 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;
1711
3306
  }
1712
- if (wire === WireType.ArrayFixlen) {
1713
- let p = this.p;
1714
- while (p < this.n && this.buf[p] >= 128) p++;
1715
- p++;
1716
- 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;
1717
3315
  }
1718
- return -1;
3316
+ if (this.len < total) return null;
3317
+ this.buf = null;
3318
+ return b;
1719
3319
  }
1720
- /** Read and validate an array count word (0..ARRAY_MAX; §4.7/§4.8). */
1721
- arrayCount() {
1722
- this.readVarint();
1723
- const count = this.num();
1724
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1725
- if (count > this.maxArrayCount) {
1726
- throw limitExceededError(
1727
- `array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`
1728
- );
1729
- }
1730
- if (count > this.n - this.p) throw incompleteError("truncated array");
1731
- return count;
1732
- }
1733
- /** Read a scalar fixlen sub-header, asserting subtype and exact byte length (floats). */
1734
- fixlenHeader(wantSub, wantLen) {
1735
- this.readVarint();
1736
- const sub = this.lo & 7;
1737
- const len = this.upper();
1738
- if (sub !== wantSub) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1739
- if (len !== wantLen) throw invalidMsgError("fixlen float length mismatch");
1740
- }
1741
- /** Read a scalar fixlen sub-header for a string/blob, asserting subtype; returns byte length. */
1742
- fixlenLen(wantSub) {
1743
- this.readVarint();
1744
- const sub = this.lo & 7;
1745
- const len = this.upper();
1746
- if (sub !== wantSub) throw invalidMsgError(`invalid fixlen subtype ${sub}`);
1747
- if (len > FIXLEN_MAX) throw invalidMsgError("fixlen length out of range");
1748
- const limit = wantSub === FixlenSubtype.String ? this.maxStringLen : this.maxBlobLen;
1749
- if (len > limit) {
1750
- const what = wantSub === FixlenSubtype.String ? "string" : "blob";
1751
- const name = wantSub === FixlenSubtype.String ? "maxStringLen" : "maxBlobLen";
1752
- throw limitExceededError(
1753
- `${what} length ${len} exceeds ${name} ${limit}`
1754
- );
1755
- }
1756
- return len;
1757
- }
1758
- /** Read an array fixlen element header (count + element type); returns the count. */
1759
- arrayFixlenHeader(wantSub, wantSize) {
1760
- this.readVarint();
1761
- const count = this.num();
1762
- if (count > ARRAY_MAX) throw invalidMsgError("array count out of range");
1763
- if (count > this.maxArrayCount) {
1764
- throw limitExceededError(
1765
- `array count ${count} exceeds maxArrayCount ${this.maxArrayCount}`
1766
- );
1767
- }
1768
- this.readVarint();
1769
- const sub = this.lo & 7;
1770
- const size = this.upper();
1771
- if (sub !== wantSub || size !== wantSize) {
1772
- throw invalidMsgError("invalid fixlen array element type");
1773
- }
1774
- if (count > (this.n - this.p) / wantSize) {
1775
- throw incompleteError("truncated fixlen array");
1776
- }
1777
- return count;
1778
- }
1779
- /** Hand back a zero-copy view of the next `len` bytes, advancing the cursor. */
1780
- take(len) {
1781
- const start = this.p;
1782
- const end = start + len;
1783
- if (end > this.n) throw incompleteError("truncated fixlen payload");
1784
- this.p = end;
1785
- return this.buf.subarray(start, end);
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}`);
1786
3338
  }
1787
- rawFp32() {
1788
- const p = this.p;
1789
- if (p + 4 > this.n) throw incompleteError("truncated fp32");
1790
- this.p = p + 4;
1791
- return this.view.getFloat32(p, true);
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);
1792
3350
  }
1793
- rawFp64() {
1794
- const p = this.p;
1795
- if (p + 8 > this.n) throw incompleteError("truncated fp64");
1796
- this.p = p + 8;
1797
- return this.view.getFloat64(p, true);
3351
+ /**
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.
3359
+ */
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);
1798
3363
  }
1799
- // --- varint reading (shared verbatim with ./fast) -----------------------
1800
3364
  /**
1801
- * The last varint's full value as a `bigint` (64-bit fidelity). Only ever
1802
- * called from {@link unsignedValue} / {@link signedValue} on the `hi` overflow
1803
- * path (`this.hi >>> 0 > 0x1fffff`), so `hi` is always non-zero here.
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}).
1804
3373
  */
1805
- big() {
1806
- return BigInt(this.hi >>> 0) << 32n | BigInt(this.lo >>> 0);
3374
+ checkIndex(id) {
3375
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
1807
3376
  }
1808
3377
  /**
1809
- * The last varint as an unsigned value, number-first: a `number` when it fits
1810
- * exactly (`≤ 2^53-1`), a `bigint` only beyond that.
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.
1811
3384
  */
1812
- unsignedValue() {
1813
- const hi = this.hi >>> 0;
1814
- return hi <= 2097151 ? hi * TWO323 + (this.lo >>> 0) : this.big();
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;
1815
3389
  }
1816
- /** The last zig-zag varint as a signed value, number-first. */
1817
- signedValue() {
1818
- const hi = this.hi >>> 0;
1819
- if (hi <= 2097151) {
1820
- const r = hi * TWO323 + (this.lo >>> 0);
1821
- return r % 2 === 0 ? r / 2 : -(r + 1) / 2;
1822
- }
1823
- return zigzagDecode(this.big());
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);
1824
3400
  }
1825
- /** The last varint's value as a JS number — exact for ids/lengths/counts. */
1826
- num() {
1827
- return this.hi * TWO323 + (this.lo >>> 0);
3401
+ /**
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.
3408
+ */
3409
+ checkIndex(id) {
3410
+ if (id >= this.bound) rejectIndex(id, this.cap, this.receiverCap, this.name);
1828
3411
  }
1829
- /** The last varint with its low 3 tag bits stripped (`value >> 3`). */
1830
- upper() {
1831
- return (this.hi >>> 0) * (TWO323 / 8) + (this.lo >>> 3);
3412
+ /**
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.
3422
+ */
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());
1832
3426
  }
1833
3427
  /**
1834
- * Decode one LEB128 varint at the cursor into {@link lo} / {@link hi} (each an
1835
- * unsigned 32-bit half), advancing {@link p}. Throws on truncation or a value
1836
- * spilling past 64 bits (>10 bytes). Unrolled, number-only — no `bigint`.
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.
1837
3436
  */
1838
- readVarint() {
1839
- const buf = this.buf;
1840
- const n = this.n;
1841
- let p = this.p;
1842
- let b;
1843
- let lo;
1844
- let hi = 0;
1845
- if (p >= n) throw incompleteError("truncated varint");
1846
- b = buf[p++];
1847
- lo = b & 127;
1848
- if (b < 128) return this.set(lo, 0, p);
1849
- if (p >= n) throw incompleteError("truncated varint");
1850
- b = buf[p++];
1851
- lo |= (b & 127) << 7;
1852
- if (b < 128) return this.set(lo, 0, p);
1853
- if (p >= n) throw incompleteError("truncated varint");
1854
- b = buf[p++];
1855
- lo |= (b & 127) << 14;
1856
- if (b < 128) return this.set(lo, 0, p);
1857
- if (p >= n) throw incompleteError("truncated varint");
1858
- b = buf[p++];
1859
- lo |= (b & 127) << 21;
1860
- if (b < 128) return this.set(lo, 0, p);
1861
- if (p >= n) throw incompleteError("truncated varint");
1862
- b = buf[p++];
1863
- lo |= (b & 15) << 28;
1864
- hi = b >> 4 & 7;
1865
- if (b < 128) return this.set(lo, hi, p);
1866
- if (p >= n) throw incompleteError("truncated varint");
1867
- b = buf[p++];
1868
- hi |= (b & 127) << 3;
1869
- if (b < 128) return this.set(lo, hi, p);
1870
- if (p >= n) throw incompleteError("truncated varint");
1871
- b = buf[p++];
1872
- hi |= (b & 127) << 10;
1873
- if (b < 128) return this.set(lo, hi, p);
1874
- if (p >= n) throw incompleteError("truncated varint");
1875
- b = buf[p++];
1876
- hi |= (b & 127) << 17;
1877
- if (b < 128) return this.set(lo, hi, p);
1878
- if (p >= n) throw incompleteError("truncated varint");
1879
- b = buf[p++];
1880
- hi |= (b & 127) << 24;
1881
- if (b < 128) return this.set(lo, hi, p);
1882
- if (p >= n) throw incompleteError("truncated varint");
1883
- b = buf[p++];
1884
- if ((b & 127) >> 1 !== 0) throw invalidMsgError("varint overflow");
1885
- hi |= (b & 127) << 31;
1886
- if (b < 128) return this.set(lo, hi, p);
1887
- throw invalidMsgError("varint overflow");
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;
1888
3441
  }
1889
- set(lo, hi, p) {
1890
- this.lo = lo;
1891
- this.hi = hi;
1892
- this.p = p;
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);
3454
+ }
3455
+ /**
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.
3469
+ */
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
+ }
1893
3495
  }
1894
3496
  };
1895
-
1896
- // src/backend/native.ts
1897
- var NATIVE_PACKAGE = "@sofa-buffers/corelib-native";
1898
- function isNode() {
1899
- return typeof process !== "undefined" && !!process.versions?.node;
1900
- }
1901
- async function loadNativeKernel() {
1902
- if (!isNode()) return false;
1903
- try {
1904
- const { createRequire } = await import('module');
1905
- 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)));
1906
- const mod = require2(NATIVE_PACKAGE);
1907
- const kernel = mod.kernel ?? mod;
1908
- setKernel(kernel);
1909
- return true;
1910
- } catch {
1911
- 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
+ }
1912
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);
1913
3540
  }
1914
3541
 
1915
- // src/backend/wasm.ts
1916
- async function loadWasmKernel(source, factory, imports = {}) {
1917
- let instance;
1918
- if (source instanceof WebAssembly.Module) {
1919
- instance = await WebAssembly.instantiate(source, imports);
1920
- } else if (typeof Response !== "undefined" && (source instanceof Response || isThenable(source))) {
1921
- const result = await WebAssembly.instantiateStreaming(
1922
- source,
1923
- imports
1924
- );
1925
- instance = result.instance;
1926
- } else {
1927
- const result = await WebAssembly.instantiate(source, imports);
1928
- instance = result.instance;
1929
- }
1930
- 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;
1931
3546
  return true;
1932
3547
  }
1933
- function isThenable(x) {
1934
- 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;
1935
3554
  }
1936
3555
 
1937
3556
  exports.API_VERSION = API_VERSION;
1938
3557
  exports.ARRAY_MAX = ARRAY_MAX;
1939
3558
  exports.ArrayKind = ArrayKind;
1940
- exports.Cursor = Cursor;
3559
+ exports.BlobSeq = BlobSeq;
1941
3560
  exports.DecodeStatus = DecodeStatus;
3561
+ exports.ElementSeq = ElementSeq;
1942
3562
  exports.FIXLEN_MAX = FIXLEN_MAX;
1943
3563
  exports.FixlenSubtype = FixlenSubtype;
3564
+ exports.FramedSeq = FramedSeq;
1944
3565
  exports.I64_MAX = I64_MAX;
1945
3566
  exports.I64_MIN = I64_MIN;
1946
3567
  exports.ID_MAX = ID_MAX;
1947
3568
  exports.IStream = IStream;
1948
3569
  exports.Long = Long;
1949
3570
  exports.MAX_DEPTH = MAX_DEPTH;
3571
+ exports.MIN_OUTPUT_BUFFER = MIN_OUTPUT_BUFFER;
1950
3572
  exports.OStream = OStream;
3573
+ exports.PayloadAcc = PayloadAcc;
1951
3574
  exports.SofabError = SofabError;
1952
3575
  exports.SofabErrorCode = SofabErrorCode;
3576
+ exports.StringSeq = StringSeq;
1953
3577
  exports.U64_MAX = U64_MAX;
3578
+ exports.UNBOUNDED = UNBOUNDED;
1954
3579
  exports.WireType = WireType;
1955
3580
  exports.decode = decode;
3581
+ exports.decodeUtf8 = decodeUtf8;
3582
+ exports.elementsEqual = elementsEqual;
3583
+ exports.fp32RawBytes = fp32RawBytes;
1956
3584
  exports.getKernel = getKernel;
3585
+ exports.growingOStream = growingOStream;
1957
3586
  exports.jsKernel = jsKernel;
1958
- exports.loadNativeKernel = loadNativeKernel;
1959
- exports.loadWasmKernel = loadWasmKernel;
3587
+ exports.longElementsEqual = longElementsEqual;
1960
3588
  exports.setKernel = setKernel;
1961
3589
  exports.sofab = public_exports;
1962
3590
  //# sourceMappingURL=index.cjs.map