nish 0.44.0 → 0.45.1

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.
Files changed (111) hide show
  1. package/README.md +1 -1
  2. package/docs/AI.md +18 -16
  3. package/package.json +5 -5
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +8 -0
  7. package/runtime/core.mjs +16 -0
  8. package/runtime/nish.d.ts +47 -5
  9. package/runtime/nish.mjs +4 -0
  10. package/std/README.md +3 -3
  11. package/std/array.ts +10 -2
  12. package/std/bytes.ts +239 -26
  13. package/std/cli-args.ts +1072 -606
  14. package/std/cli-flags.ts +180 -98
  15. package/std/cli.ts +21 -13
  16. package/std/collections.ts +245 -127
  17. package/std/compress/checksum.ts +32 -37
  18. package/std/compress/deflate.ts +1102 -542
  19. package/std/compress/gzip.ts +290 -145
  20. package/std/compress/zlib.ts +57 -21
  21. package/std/crypto/aes.ts +153 -75
  22. package/std/crypto/base64url.ts +84 -61
  23. package/std/crypto/bcrypt-batch.ts +164 -90
  24. package/std/crypto/bcrypt.ts +185 -107
  25. package/std/crypto/chacha20poly1305.ts +84 -68
  26. package/std/crypto/ct.ts +9 -7
  27. package/std/crypto/ed25519.ts +64 -27
  28. package/std/crypto/hkdf.ts +105 -63
  29. package/std/crypto/hmac.ts +95 -89
  30. package/std/crypto/jwt.ts +248 -126
  31. package/std/crypto/p256.ts +758 -444
  32. package/std/crypto/p384.ts +20 -13
  33. package/std/crypto/pki-roots.ts +95 -38
  34. package/std/crypto/pki.ts +164 -60
  35. package/std/crypto/rsa.ts +266 -223
  36. package/std/crypto/scram.ts +3 -4
  37. package/std/crypto/sha1.ts +107 -65
  38. package/std/crypto/sha256.ts +502 -422
  39. package/std/crypto/sha512.ts +204 -135
  40. package/std/crypto/x509-random.ts +9 -3
  41. package/std/crypto/x509.ts +331 -171
  42. package/std/json-equal.ts +35 -19
  43. package/std/json-format.ts +215 -108
  44. package/std/json-number.ts +126 -72
  45. package/std/json-pointer.ts +42 -13
  46. package/std/json-tokenizer.ts +498 -307
  47. package/std/json-typed.ts +115 -36
  48. package/std/json-value.ts +341 -152
  49. package/std/json.ts +300 -158
  50. package/std/net/buffer-pool.ts +17 -7
  51. package/std/net/dns-config.ts +427 -236
  52. package/std/net/dns-message.ts +114 -47
  53. package/std/net/dns-resolver.ts +736 -237
  54. package/std/net/dns.ts +205 -52
  55. package/std/net/fetch.ts +320 -184
  56. package/std/net/grpc.ts +948 -0
  57. package/std/net/handler.ts +1275 -217
  58. package/std/net/hpack.ts +395 -180
  59. package/std/net/http-compress.ts +502 -65
  60. package/std/net/http-fields.ts +85 -49
  61. package/std/net/http-server.ts +1764 -602
  62. package/std/net/http1-client-codec.ts +372 -161
  63. package/std/net/http1-codec.ts +665 -331
  64. package/std/net/http1-server.ts +660 -278
  65. package/std/net/http2-cleartext.ts +165 -95
  66. package/std/net/http2-frame.ts +232 -89
  67. package/std/net/http2-tls.ts +42 -12
  68. package/std/net/http2.ts +327 -101
  69. package/std/net/http3-frame.ts +68 -33
  70. package/std/net/http3-server.ts +647 -192
  71. package/std/net/http3.ts +667 -189
  72. package/std/net/oidc.ts +63 -24
  73. package/std/net/outbound.ts +207 -142
  74. package/std/net/postgres-async.ts +1165 -443
  75. package/std/net/postgres-carrier.ts +575 -372
  76. package/std/net/postgres.ts +1459 -559
  77. package/std/net/prefork.ts +254 -98
  78. package/std/net/protobuf.ts +1017 -0
  79. package/std/net/qpack.ts +143 -92
  80. package/std/net/quic-conn-ack.ts +50 -18
  81. package/std/net/quic-conn-cid.ts +66 -26
  82. package/std/net/quic-conn-params.ts +13 -7
  83. package/std/net/quic-datagram.ts +90 -27
  84. package/std/net/quic-frame.ts +225 -124
  85. package/std/net/quic-listener.ts +197 -89
  86. package/std/net/quic-packet.ts +289 -163
  87. package/std/net/quic-recovery.ts +279 -128
  88. package/std/net/quic-stream.ts +466 -167
  89. package/std/net/quic.ts +568 -257
  90. package/std/net/router.ts +450 -99
  91. package/std/net/serve.ts +651 -232
  92. package/std/net/static.ts +1458 -0
  93. package/std/net/tls/client.ts +140 -45
  94. package/std/net/tls/codec.ts +510 -260
  95. package/std/net/tls/record-client.ts +268 -76
  96. package/std/net/tls/record-server.ts +236 -79
  97. package/std/net/tls/record.ts +173 -47
  98. package/std/net/tls/schedule.ts +58 -39
  99. package/std/net/tls/ticket.ts +295 -103
  100. package/std/net/tls/verify.ts +1 -1
  101. package/std/net/tls-tcp.ts +218 -75
  102. package/std/net/tls.ts +260 -152
  103. package/std/net/upstream.ts +283 -86
  104. package/std/net/url.ts +277 -102
  105. package/std/net/websocket.ts +370 -186
  106. package/std/net/webtransport.ts +755 -436
  107. package/std/regex.ts +1659 -829
  108. package/std/sync/ring.ts +320 -156
  109. package/std/sync/shm.ts +53 -6
  110. package/std/text.ts +205 -124
  111. package/std/threads.ts +22 -2
@@ -53,7 +53,7 @@
53
53
  * ported from another implementation.
54
54
  */
55
55
  import { uncheckedGet, uncheckedSet, wrappingAdd, wrappingSub } from "nish:unsafe"
56
- import { copyBytes } from "nish/bytes"
56
+ import { copyBytes, tryCopyBytes } from "nish/bytes"
57
57
 
58
58
  /** Level 0: stored blocks only, the input copied with five bytes of framing per 65,535. */
59
59
  export const DEFLATE_STORE: i32 = 0
@@ -133,6 +133,8 @@ const FIXED_WINDOW: i32 = 16384
133
133
 
134
134
  /** `FixedDeflater`'s largest hash table, 2^14 entries; a call clears only as much as its input needs. */
135
135
  const FIXED_HASH_BITS: i32 = 14
136
+ /** `FixedDeflater`'s hash table size, `1 << FIXED_HASH_BITS`. */
137
+ const FIXED_HASH_SIZE: i32 = 16384
136
138
 
137
139
  /** Decoder table entry kinds, in bits 8 to 10 of an entry. */
138
140
  const INF_LITERAL: i32 = 0
@@ -172,17 +174,21 @@ const INF_S_DONE: i32 = 3
172
174
  /**
173
175
  * The most bytes `Deflater.compress` writes for `n` bytes of input, at any
174
176
  * level: the input stored, five bytes of framing for every 65,535 and for
175
- * every block, and slack for the last partial byte. `n` is at most
176
- * 2^31 - 1 less the framing; a negative `n` answers 0.
177
+ * every block, and slack for the last partial byte. A negative `n`
178
+ * answers 0, and an `n` past 2,146,664,744, the largest whose bound fits,
179
+ * answers -1: its bound would pass 2^31 - 1.
177
180
  *
178
181
  * @param n The length of the input, in bytes.
179
182
  * @returns A size in bytes, not a position: an `out` with this many bytes
180
- * from `at` always holds the stream.
183
+ * from `at` always holds the stream; or -1 for an `n` past 2,146,664,744.
181
184
  */
182
185
  export const deflateBound = (n: i32): i32 => {
183
186
  if (n < 0) {
184
187
  return 0
185
188
  }
189
+ if (n > 2146664744) {
190
+ return -1
191
+ }
186
192
  return n + ((n >> 16) + (n >> 14) + 2) * 5 + 8
187
193
  }
188
194
 
@@ -193,9 +199,16 @@ export const deflateBound = (n: i32): i32 => {
193
199
  *
194
200
  * @param n The length of the input, in bytes.
195
201
  * @returns A size in bytes, not a position: an `out` with this many bytes
196
- * from `at` always holds the raw, zlib or gzip stream.
202
+ * from `at` always holds the raw, zlib or gzip stream; or -1 for an `n`
203
+ * past 2,146,664,726, the largest whose bound with the 18 bytes fits.
197
204
  */
198
- export const compressBound = (n: i32): i32 => deflateBound(n) + 18
205
+ export const compressBound = (n: i32): i32 => {
206
+ const b: i32 = deflateBound(n)
207
+ if (b < 0 || b > 2147483629) {
208
+ return -1
209
+ }
210
+ return b + 18
211
+ }
199
212
 
200
213
  /**
201
214
  * Copies `b[from .. from + 16)` to `b[to .. to + 16)` eight bytes at a time,
@@ -203,14 +216,17 @@ export const compressBound = (n: i32): i32 => deflateBound(n) + 18
203
216
  * meaning when `to - from` is at least 8. The caller has checked the range.
204
217
  */
205
218
  const inflateCopy16 = (b: u8[], to: integer<0, 2147483631>, from: integer<0, 2147483631>): void => {
219
+ const to8: i32 = to + 8
220
+ const from8: i32 = from + 8
206
221
  deflateStore64(b, to, deflateLoad64(b, from))
207
- deflateStore64(b, to + 8, deflateLoad64(b, from + 8))
222
+ deflateStore64(b, to8, deflateLoad64(b, from8))
208
223
  }
209
224
 
210
225
  /** Stores `w` twice into `b[to .. to + 16)`; the caller has checked the range. */
211
226
  const inflateFill16 = (b: u8[], to: integer<0, 2147483631>, w: u64): void => {
227
+ const to8: i32 = to + 8
212
228
  deflateStore64(b, to, w)
213
- deflateStore64(b, to + 8, w)
229
+ deflateStore64(b, to8, w)
214
230
  }
215
231
 
216
232
  /** Panics unless `buf[off .. off + len)` lies inside `buf`. */
@@ -220,17 +236,6 @@ const deflateWindow = (what: string, buf: u8[], off: i32, len: i32): void => {
220
236
  }
221
237
  }
222
238
 
223
- /**
224
- * Panics unless `out[p .. p + n)` lies inside `out`: the check every store of
225
- * the bit writer makes before its unchecked stores. A block's exact size was
226
- * checked against the room before it was written, so this never fires.
227
- */
228
- const deflateRoom = (out: u8[], p: i32, n: i32): void => {
229
- if (p < 0 || p > toI32(out.length) - n) {
230
- panic("Deflater: a write past the room its block was sized for")
231
- }
232
- }
233
-
234
239
  /**
235
240
  * The little-endian 32-bit word at `b[p .. p + 4)`; the caller has checked the
236
241
  * range. `p`'s range is what lets `p + 3` be an `add nsw`, which is what lets
@@ -281,28 +286,34 @@ const deflateCtz64 = (x: u64): i32 => {
281
286
  }
282
287
 
283
288
  /**
284
- * How many bytes from `a` and from `b` agree, at most `max`; `a < b` and
285
- * `b + max` lie inside `src`, which the caller has checked.
289
+ * How many bytes from `a` and from `b` agree, at most `max` and at most
290
+ * `DEFLATE_MAX_MATCH`; `a < b` and `b + max` lie inside `src`, which the
291
+ * caller has checked.
286
292
  */
287
293
  const deflateMatchLength = (src: u8[], a: i32, b: i32, max: i32): i32 => {
288
- if (a < 0 || b > 2147483639 - max) {
289
- panic("deflateMatchLength: a match outside its input")
290
- }
294
+ // `k`'s caps are no-ops for a caller, whose `max` is at most 258; they let
295
+ // the prover bound the answer. Each sum adds two non-negative i32s, so it
296
+ // cannot wrap a u32, and a sum past what `src` can hold ends the match
297
+ // where the caller's checks would have stopped it.
291
298
  let k: i32 = 0
292
- while (k + 8 <= max) {
293
- const pa: i32 = a + k
294
- const pb: i32 = b + k
295
- if (pa >= 0 && pa <= 2147483639 && pb >= 0 && pb <= 2147483639) {
296
- const x: u64 = deflateLoad64(src, pa) ^ deflateLoad64(src, pb)
297
- if (x !== toU64(0)) {
298
- return k + (deflateCtz64(x) >> 3)
299
- }
300
- } else {
299
+ while (k >= 0 && k <= 250 && k + 8 <= max && a >= 0 && b >= 0) {
300
+ const pa: i32 = toI32(toU32(a) + toU32(k))
301
+ const pb: i32 = toI32(toU32(b) + toU32(k))
302
+ if (pa < 0 || pa > 2147483639 || pb < 0 || pb > 2147483639) {
301
303
  return k
302
304
  }
305
+ const x: u64 = deflateLoad64(src, pa) ^ deflateLoad64(src, pb)
306
+ if (x !== toU64(0)) {
307
+ return k + (deflateCtz64(x) >> 3)
308
+ }
303
309
  k += 8
304
310
  }
305
- while (k < max && uncheckedGet(src, a + k) === uncheckedGet(src, b + k)) {
311
+ while (k >= 0 && k < 258 && k < max && a >= 0 && b >= 0) {
312
+ const pa: i32 = toI32(toU32(a) + toU32(k))
313
+ const pb: i32 = toI32(toU32(b) + toU32(k))
314
+ if (pa < 0 || pb < 0 || uncheckedGet(src, pa) !== uncheckedGet(src, pb)) {
315
+ return k
316
+ }
306
317
  k += 1
307
318
  }
308
319
  return k
@@ -319,27 +330,41 @@ const deflateReverse = (code: i32, len: i32): i32 => {
319
330
  return r
320
331
  }
321
332
 
322
- /** The base length of each length symbol 257 + s (§3.2.5). */
333
+ /**
334
+ * The base length of each length symbol 257 + s (§3.2.5); every `s` past 27
335
+ * answers symbol 28's, 258.
336
+ */
323
337
  const deflateLengthBase = (s: i32): i32 => {
324
338
  if (s < 8) {
325
339
  return 3 + s
326
340
  }
327
- if (s === 28) {
341
+ if (s >= 28) {
328
342
  return 258
329
343
  }
330
- return ((toI32(4) + (s & 3)) << ((s >> 2) - 1)) + 3
344
+ // At most 7 << 5, so the mask keeps every bit; it bounds the sum.
345
+ return (((toI32(4) + (s & 3)) << ((s >> 2) - 1)) & 255) + 3
331
346
  }
332
347
 
333
- /** The extra bits of each length symbol 257 + s (§3.2.5). */
334
- const deflateLengthExtra = (s: i32): i32 => (s < 8 || s === 28 ? 0 : (s >> 2) - 1)
348
+ /**
349
+ * The extra bits of each length symbol 257 + s (§3.2.5); every `s` past 27
350
+ * answers symbol 28's, 0.
351
+ */
352
+ const deflateLengthExtra = (s: i32): i32 => (s < 8 || s >= 28 ? 0 : (s >> 2) - 1)
335
353
 
336
- /** The base distance of each distance symbol (§3.2.5). */
354
+ /**
355
+ * The base distance of each distance symbol (§3.2.5); every `d` past 29
356
+ * answers symbol 29's, 24577.
357
+ */
337
358
  const deflateDistBase = (d: i32): i32 => {
338
359
  if (d < 4) {
339
360
  return 1 + d
340
361
  }
362
+ if (d >= 29) {
363
+ return 24577
364
+ }
341
365
  const extra: i32 = (d >> 1) - 1
342
- return ((toI32(2) + (d & 1)) << extra) + 1
366
+ // At most 3 << 13, so the mask keeps every bit; it bounds the sum.
367
+ return (((toI32(2) + (d & 1)) << extra) & 32767) + 1
343
368
  }
344
369
 
345
370
  /** The extra bits of each distance symbol (§3.2.5). */
@@ -403,20 +428,41 @@ const deflateFixedLitLength = (s: i32): i32 => {
403
428
  return 8
404
429
  }
405
430
 
431
+ /**
432
+ * The fixed code (§3.2.6) of literal/length symbol `s`, bit-reversed for the
433
+ * LSB-first stream: what `deflateCanonical` gives the fixed lengths, written
434
+ * out by its four runs: from 0x30, 0x190, 0 and 0xc0.
435
+ */
436
+ const deflateFixedLitCode = (s: i32): i32 => {
437
+ if (s < 144) {
438
+ return deflateReverse(0x30 + s, 8)
439
+ }
440
+ if (s < 256) {
441
+ return deflateReverse(s + 256, 9)
442
+ }
443
+ if (s < 280) {
444
+ return deflateReverse(s - 256, 7)
445
+ }
446
+ return deflateReverse(s - 88, 8)
447
+ }
448
+
406
449
  /**
407
450
  * Fills `codes[0 .. n)` with the canonical code (§3.2.2) of the lengths
408
451
  * `lens[0 .. n)`, each already bit-reversed for the LSB-first stream. `count`
409
452
  * and `next` are scratch of at least 16 entries. A length of 0 gets code 0.
453
+ * Answers false, filling nothing, when a table is smaller than that or `n`
454
+ * is past 288, the largest alphabet, which every caller's tables rule out.
410
455
  */
411
- const deflateCanonical = (lens: i32[], n: i32, codes: i32[], count: i32[], next: i32[]): void => {
456
+ const deflateCanonical = (lens: i32[], n: i32, codes: i32[], count: i32[], next: i32[]): boolean => {
412
457
  if (
413
458
  n < 0 ||
459
+ n > 288 ||
414
460
  n > toI32(lens.length) ||
415
461
  n > toI32(codes.length) ||
416
462
  toI32(count.length) < 16 ||
417
463
  toI32(next.length) < 16
418
464
  ) {
419
- panic("deflateCanonical: a table smaller than its symbols")
465
+ return false
420
466
  }
421
467
  for (let i: i32 = 0; i < 16; i += 1) {
422
468
  count[i] = 0
@@ -424,13 +470,17 @@ const deflateCanonical = (lens: i32[], n: i32, codes: i32[], count: i32[], next:
424
470
  for (let s: i32 = 0; s < n; s += 1) {
425
471
  const l: i32 = lens[s]
426
472
  if (l >= 0 && l < 16) {
427
- count[l] += 1
473
+ // A count is at most n <= 288: the mask keeps every bit, and tells
474
+ // the bounds prover so.
475
+ count[l] = (count[l] & 511) + 1
428
476
  }
429
477
  }
430
478
  count[0] = 0
431
479
  let code: i32 = 0
432
480
  for (let l: i32 = 1; l < 16; l += 1) {
433
- code = (code + count[l - 1]) << 1
481
+ // Only a code's low `l` bits are written, and they depend only on the
482
+ // low bits of the sum: the mask keeps 16 of them.
483
+ code = ((code + (count[l - 1] & 511)) << 1) & 0xffff
434
484
  next[l] = code
435
485
  }
436
486
  // Each length's next code is kept bit-reversed, as it is written, and
@@ -443,15 +493,18 @@ const deflateCanonical = (lens: i32[], n: i32, codes: i32[], count: i32[], next:
443
493
  if (l > 0 && l < 16) {
444
494
  const r: i32 = next[l]
445
495
  codes[s] = r
446
- const top: i32 = (toI32(1) << l) - 1
496
+ // `l` is below 16, so `r` and `top` are below 2^16 and the masks keep
497
+ // every bit.
498
+ const top: i32 = ((toI32(1) << l) & 0xffff) - 1
447
499
  if (r !== top) {
448
- const bit: i32 = toI32(1) << (31 - toI32(Math.clz32(toU32(r ^ top))))
500
+ const bit: i32 = (toI32(1) << (31 - toI32(Math.clz32(toU32(r ^ top))))) & 0xffff
449
501
  next[l] = (r & (bit - 1)) | bit
450
502
  }
451
503
  } else {
452
504
  codes[s] = 0
453
505
  }
454
506
  }
507
+ return true
455
508
  }
456
509
 
457
510
  /**
@@ -490,9 +543,13 @@ export class DeflateHuffmanScratch {
490
543
  * then, if a length passed `limit`, the counts per length repaired until the
491
544
  * Kraft sum is exactly 1 again. A symbol of frequency 0 gets length 0. With
492
545
  * fewer than two used symbols, symbols are given length 1 until two have
493
- * one, so the code is always complete. Frequencies are below 2^16.
546
+ * one, so the code is always complete. Answers false, setting nothing, when
547
+ * the alphabet or `limit` is outside the scratch's sizes or a frequency is
548
+ * 2^16 or more, which every caller's tables and blocks rule out. Those
549
+ * bounds keep every weight below 2^25 and every count below 2^9, which the
550
+ * masks below keep whole and tell the bounds prover.
494
551
  */
495
- const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: DeflateHuffmanScratch): void => {
552
+ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: DeflateHuffmanScratch): boolean => {
496
553
  const syms: i32[] = w.syms
497
554
  const keys: i32[] = w.keys
498
555
  const tsyms: i32[] = w.tmpSyms
@@ -513,19 +570,24 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
513
570
  limit < 1 ||
514
571
  limit > 15
515
572
  ) {
516
- panic("deflateLengths: an alphabet outside its scratch")
573
+ return false
517
574
  }
518
575
  // The used symbols, by a two-pass radix sort on the 16-bit frequency.
519
576
  let used: i32 = 0
520
577
  for (let s: i32 = 0; s < n; s += 1) {
521
- lens[s] = 0
522
578
  const f: i32 = freq[s]
579
+ if (f > 65535) {
580
+ return false
581
+ }
523
582
  if (f > 0) {
524
583
  uncheckedSet(tsyms, used, s)
525
584
  uncheckedSet(tkeys, used, f)
526
585
  used += 1
527
586
  }
528
587
  }
588
+ for (let s: i32 = 0; s < n; s += 1) {
589
+ lens[s] = 0
590
+ }
529
591
  if (used < 2) {
530
592
  // One code or none: every decoder wants a complete code, so give two
531
593
  // symbols one bit each.
@@ -542,7 +604,7 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
542
604
  given += 1
543
605
  }
544
606
  }
545
- return
607
+ return true
546
608
  }
547
609
  for (let pass: i32 = 0; pass < 2; pass += 1) {
548
610
  const shift: i32 = pass * 8
@@ -555,18 +617,18 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
555
617
  const toKeys: i32[] = pass === 0 ? keys : tkeys
556
618
  for (let i: i32 = 0; i < used; i += 1) {
557
619
  const b: i32 = (uncheckedGet(fromKeys, i) >> shift) & 255
558
- uncheckedSet(buckets, b, uncheckedGet(buckets, b) + 1)
620
+ uncheckedSet(buckets, b, (uncheckedGet(buckets, b) & 511) + 1)
559
621
  }
560
622
  let sum: i32 = 0
561
623
  for (let b: i32 = 0; b < 256; b += 1) {
562
- const c: i32 = uncheckedGet(buckets, b)
624
+ const c: i32 = uncheckedGet(buckets, b) & 511
563
625
  uncheckedSet(buckets, b, sum)
564
- sum += c
626
+ sum = (sum + c) & 511
565
627
  }
566
628
  for (let i: i32 = 0; i < used; i += 1) {
567
629
  const k: i32 = uncheckedGet(fromKeys, i)
568
630
  const b: i32 = (k >> shift) & 255
569
- const at: i32 = uncheckedGet(buckets, b)
631
+ const at: i32 = uncheckedGet(buckets, b) & 511
570
632
  uncheckedSet(buckets, b, at + 1)
571
633
  uncheckedSet(toSyms, at, uncheckedGet(fromSyms, i))
572
634
  uncheckedSet(toKeys, at, k)
@@ -579,31 +641,39 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
579
641
  }
580
642
  // Moffat and Katajainen, phase 1: each internal node's weight, and each
581
643
  // node's parent, in place over the ascending weights.
582
- uncheckedSet(keys, 0, uncheckedGet(keys, 0) + uncheckedGet(keys, 1))
644
+ uncheckedSet(keys, 0, (uncheckedGet(keys, 0) & 0x1ffffff) + (uncheckedGet(keys, 1) & 0x1ffffff))
583
645
  let root: i32 = 0
584
646
  let leaf: i32 = 2
585
647
  for (let next: i32 = 1; next < used - 1; next += 1) {
586
648
  if (leaf >= used || uncheckedGet(keys, root) < uncheckedGet(keys, leaf)) {
587
649
  uncheckedSet(keys, next, uncheckedGet(keys, root))
588
650
  uncheckedSet(keys, root, next)
589
- root += 1
651
+ root = (root + 1) & 511
590
652
  } else {
591
653
  uncheckedSet(keys, next, uncheckedGet(keys, leaf))
592
654
  leaf += 1
593
655
  }
594
656
  if (leaf >= used || (root < next && uncheckedGet(keys, root) < uncheckedGet(keys, leaf))) {
595
- uncheckedSet(keys, next, uncheckedGet(keys, next) + uncheckedGet(keys, root))
657
+ uncheckedSet(
658
+ keys,
659
+ next,
660
+ (uncheckedGet(keys, next) & 0x1ffffff) + (uncheckedGet(keys, root) & 0x1ffffff)
661
+ )
596
662
  uncheckedSet(keys, root, next)
597
- root += 1
663
+ root = (root + 1) & 511
598
664
  } else {
599
- uncheckedSet(keys, next, uncheckedGet(keys, next) + uncheckedGet(keys, leaf))
665
+ uncheckedSet(
666
+ keys,
667
+ next,
668
+ (uncheckedGet(keys, next) & 0x1ffffff) + (uncheckedGet(keys, leaf) & 0x1ffffff)
669
+ )
600
670
  leaf += 1
601
671
  }
602
672
  }
603
673
  // Phase 2: each internal node's depth.
604
674
  uncheckedSet(keys, used - 2, 0)
605
675
  for (let next: i32 = used - 3; next >= 0; next -= 1) {
606
- uncheckedSet(keys, next, uncheckedGet(keys, uncheckedGet(keys, next)) + 1)
676
+ uncheckedSet(keys, next, (uncheckedGet(keys, uncheckedGet(keys, next)) & 511) + 1)
607
677
  }
608
678
  // Phase 3: how many leaves sit at each depth.
609
679
  for (let l: i32 = 0; l < 33; l += 1) {
@@ -613,18 +683,21 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
613
683
  let usedHere: i32 = 0
614
684
  let depth: i32 = 0
615
685
  root = used - 2
616
- while (avail > 0) {
617
- while (root >= 0 && uncheckedGet(keys, root) === depth) {
686
+ // A tree of at most 288 leaves is under 288 deep and has under 288
687
+ // internal nodes, so the bounds on `depth` and `usedHere` never stop a loop.
688
+ while (avail > 0 && depth < 288) {
689
+ while (root >= 0 && usedHere < 288 && uncheckedGet(keys, root) === depth) {
618
690
  usedHere += 1
619
691
  root -= 1
620
692
  }
621
- while (avail > usedHere) {
693
+ // `usedHere` is never negative, so `avail > 0` only restates the first test.
694
+ while (avail > usedHere && avail > 0) {
622
695
  if (depth < 33) {
623
- per[depth] += 1
696
+ per[depth] = (per[depth] & 511) + 1
624
697
  }
625
698
  avail -= 1
626
699
  }
627
- avail = 2 * usedHere
700
+ avail = usedHere << 1
628
701
  depth += 1
629
702
  usedHere = 0
630
703
  }
@@ -632,19 +705,22 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
632
705
  // shorter codes until the Kraft sum is exactly 2^limit again.
633
706
  if (per[limit + 1] > 0 || depth > limit + 1) {
634
707
  for (let l: i32 = limit + 1; l < 33; l += 1) {
635
- per[limit] += per[l]
708
+ per[limit] = (per[limit] & 511) + (per[l] & 511)
636
709
  per[l] = 0
637
710
  }
711
+ // At most 288 codes of at most 15 bits: the Kraft sum is below 2^23.
638
712
  let total: i32 = 0
639
713
  for (let l: i32 = limit; l > 0; l -= 1) {
640
- total += per[l] << (limit - l)
714
+ total = (total + (((per[l] & 511) << (limit - l)) & 0x7fffff)) & 0x7fffff
641
715
  }
642
- while (total !== 1 << limit) {
643
- per[limit] -= 1
716
+ // Each pass takes one off a sum above 2^limit, so it stays positive.
717
+ while (total !== 1 << limit && total > 0) {
718
+ per[limit] = (per[limit] & 511) - 1
644
719
  for (let l: i32 = limit - 1; l > 0; l -= 1) {
645
- if (per[l] !== 0) {
646
- per[l] -= 1
647
- per[l + 1] += 2
720
+ const c: i32 = per[l] & 511
721
+ if (c !== 0) {
722
+ per[l] = c - 1
723
+ per[l + 1] = (per[l + 1] & 511) + 2
648
724
  break
649
725
  }
650
726
  }
@@ -654,16 +730,15 @@ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: Deflate
654
730
  // The most frequent symbols take the shortest lengths.
655
731
  let j: i32 = used
656
732
  for (let l: i32 = 1; l <= limit; l += 1) {
657
- for (let c: i32 = per[l]; c > 0; c -= 1) {
733
+ for (let c: i32 = per[l]; c > 0 && j > 0; c -= 1) {
658
734
  j -= 1
659
- if (j >= 0) {
660
- const s: i32 = uncheckedGet(syms, j)
661
- if (s >= 0 && s < n) {
662
- lens[s] = l
663
- }
735
+ const s: i32 = uncheckedGet(syms, j)
736
+ if (s >= 0 && s < n) {
737
+ lens[s] = l
664
738
  }
665
739
  }
666
740
  }
741
+ return true
667
742
  }
668
743
 
669
744
  /**
@@ -710,7 +785,9 @@ export class Deflater {
710
785
  private readonly scratch: DeflateHuffmanScratch
711
786
  /** Bits written but not yet stored, low bit first, and how many. */
712
787
  private bitBuf: u64
713
- private bitCount: i32
788
+ private bitCount: u32
789
+ /** Set when a store would have run past `out`: the call answers `DEFLATE_NO_ROOM`. */
790
+ private overrun: boolean
714
791
  /** @internal Used by `GzipCompressor`, `GzipWriter` (std/compress/gzip.ts) and `ZlibCompressor` (std/compress/zlib.ts). The level, 0 to 9. */
715
792
  readonly level: i32
716
793
  /** Candidates tried per position. */
@@ -827,16 +904,18 @@ export class Deflater {
827
904
  this.scratch = new DeflateHuffmanScratch()
828
905
  this.bitBuf = 0
829
906
  this.bitCount = 0
907
+ this.overrun = false
830
908
  for (let s: i32 = 0; s < 29; s += 1) {
831
909
  this.lengthBase[s] = deflateLengthBase(s)
832
910
  this.lengthExtra[s] = deflateLengthExtra(s)
833
911
  }
834
912
  for (let s: i32 = 0; s < 29; s += 1) {
835
- const lo: i32 = this.lengthBase[s] - 3
913
+ const lo: i32 = deflateLengthBase(s) - 3
836
914
  // Symbol 27 stops short of 258, which has symbol 28 to itself.
837
915
  let hi: i32 = 256
838
916
  if (s < 27) {
839
- hi = this.lengthBase[s + 1] - 3
917
+ const next: i32 = s + 1
918
+ hi = deflateLengthBase(next) - 3
840
919
  } else if (s === 27) {
841
920
  hi = 255
842
921
  }
@@ -850,9 +929,13 @@ export class Deflater {
850
929
  }
851
930
  // Distances 1 to 256 directly; above, by (distance - 1) >> 7 from 256 on.
852
931
  for (let d: i32 = 0; d < 30; d += 1) {
853
- const lo: i32 = this.distBase[d]
854
- const hi: i32 = d === 29 ? 32769 : this.distBase[d + 1]
855
- for (let dist: i32 = lo; dist < hi; dist += 1) {
932
+ const lo: i32 = deflateDistBase(d)
933
+ let hi: i32 = 32769
934
+ if (d < 29) {
935
+ const next: i32 = d + 1
936
+ hi = deflateDistBase(next)
937
+ }
938
+ for (let dist: i32 = lo; dist < hi && dist >= 1 && dist <= 32768; dist += 1) {
856
939
  if (dist <= 256) {
857
940
  this.distSymbol[dist - 1] = d
858
941
  } else {
@@ -869,8 +952,12 @@ export class Deflater {
869
952
  for (let d: i32 = 0; d < 32; d += 1) {
870
953
  this.fixedDistLens[d] = 5
871
954
  }
872
- deflateCanonical(this.fixedLitLens, 288, this.fixedLitCodes, this.countScratch, this.nextScratch)
873
- deflateCanonical(this.fixedDistLens, 32, this.fixedDistCodes, this.countScratch, this.nextScratch)
955
+ for (let s: i32 = 0; s < 288; s += 1) {
956
+ this.fixedLitCodes[s] = deflateFixedLitCode(s)
957
+ }
958
+ for (let d: i32 = 0; d < 32; d += 1) {
959
+ this.fixedDistCodes[d] = deflateReverse(d, 5)
960
+ }
874
961
  }
875
962
 
876
963
  /**
@@ -881,6 +968,7 @@ export class Deflater {
881
968
  reset(): void {
882
969
  this.bitBuf = 0
883
970
  this.bitCount = 0
971
+ this.overrun = false
884
972
  }
885
973
 
886
974
  /**
@@ -904,10 +992,18 @@ export class Deflater {
904
992
  deflateWindow("Deflater.compress", out, at, 0)
905
993
  this.bitBuf = 0
906
994
  this.bitCount = 0
995
+ this.overrun = false
996
+ // Cannot wrap: deflateWindow checked off + len <= src.length.
997
+ const srcEnd: i32 = toI32(toU32(off) + toU32(len))
907
998
  this.begin(off)
908
- const end: i32 = this.compressRange(src, off, off + len, off, true, out, at, toI32(out.length))
909
- this.finish(off + len)
999
+ const end: i32 = this.compressRange(src, off, srcEnd, off, true, out, at, toI32(out.length))
1000
+ this.finish(srcEnd)
910
1001
  if (end < 0) {
1002
+ // Every other -1 under `compressRange` (a table not its size, a code
1003
+ // that does not build, a position past i32) cannot happen: the
1004
+ // constructor sizes the tables, the codes are built from frequencies
1005
+ // this class counted, and `begin` and `rebase` keep positions low. So
1006
+ // this is a lack of room, which a larger `out` cures.
911
1007
  return DEFLATE_NO_ROOM
912
1008
  }
913
1009
  return this.flushBits(out, end, toI32(out.length))
@@ -919,12 +1015,18 @@ export class Deflater {
919
1015
  * every position the tables hold is pushed a window behind it.
920
1016
  */
921
1017
  begin(start: i32): void {
922
- if (this.base > DEFLATE_REBASE) {
923
- this.head.fill(0)
924
- this.prev.fill(0)
925
- this.base = DEFLATE_WINDOW + 1
1018
+ let base: i32 = this.base
1019
+ // 32769 is DEFLATE_WINDOW + 1, spelled out for the bounds prover.
1020
+ if (base > DEFLATE_REBASE || base < 32769) {
1021
+ this.forget()
1022
+ base = DEFLATE_WINDOW + 1
1023
+ }
1024
+ if (start < 0) {
1025
+ // No stream starts before its input; the next write answers -1.
1026
+ this.overrun = true
1027
+ return
926
1028
  }
927
- this.delta = this.base - start
1029
+ this.delta = base - start
928
1030
  }
929
1031
 
930
1032
  /**
@@ -933,7 +1035,10 @@ export class Deflater {
933
1035
  * positions start a window past every position the tables now hold.
934
1036
  */
935
1037
  finish(end: i32): void {
936
- this.base = end + this.delta + DEFLATE_WINDOW + 1
1038
+ const v: i32 = this.position(end)
1039
+ // Past the rebase floor (DEFLATE_REBASE, spelled out for the bounds
1040
+ // prover), the next `begin` clears the tables.
1041
+ this.base = v < 0 || v > 1073741824 ? DEFLATE_REBASE + 1 : v + DEFLATE_WINDOW + 1
937
1042
  }
938
1043
 
939
1044
  /**
@@ -943,23 +1048,71 @@ export class Deflater {
943
1048
  * The streaming writer calls it when it slides its window.
944
1049
  */
945
1050
  slide(shift: i32): void {
946
- this.delta = this.delta + shift
1051
+ const delta: i32 = this.delta
1052
+ // DEFLATE_REBASE - 1 and DEFLATE_REBASE, spelled out for the bounds prover.
1053
+ if (shift < 0 || shift > 1073741823 || delta > 1073741824) {
1054
+ // A slide no rebase can follow: drop the history instead. The output
1055
+ // stays valid DEFLATE; only matches into the dropped history are lost.
1056
+ // `GzipWriter` never gets here: it shifts by 1 to 65,536 right after a
1057
+ // `compressRange`, which rebased any position past DEFLATE_REBASE, so
1058
+ // `delta` is at most DEFLATE_REBASE.
1059
+ this.forget()
1060
+ this.delta = DEFLATE_WINDOW + 1
1061
+ return
1062
+ }
1063
+ this.delta = delta + shift
1064
+ }
1065
+
1066
+ /** Empties the tables, so that no position is a candidate. */
1067
+ private forget(): void {
1068
+ this.head.fill(0)
1069
+ this.prev.fill(0)
1070
+ this.base = DEFLATE_WINDOW + 1
1071
+ }
1072
+
1073
+ /**
1074
+ * The table position of input index `p`, `p + delta`, or -1 when that is
1075
+ * negative or past the i32 range.
1076
+ */
1077
+ private position(p: i32): i32 {
1078
+ const delta: i32 = this.delta
1079
+ if (p < 0) {
1080
+ return -1
1081
+ }
1082
+ if (delta <= 0) {
1083
+ const v: i32 = p + delta
1084
+ return v < 0 ? -1 : v
1085
+ }
1086
+ if (p > 2147483647 - delta) {
1087
+ return -1
1088
+ }
1089
+ // Cannot wrap: p <= 2147483647 - delta was checked above.
1090
+ return toI32(toU32(p) + toU32(delta))
947
1091
  }
948
1092
 
949
1093
  /**
950
1094
  * @internal Called by `GzipWriter` (std/compress/gzip.ts).
951
1095
  * Writes the whole bytes of the bit buffer, and the last partial byte
952
1096
  * padded with zeros, into `out` at `op`; answers the end, or
953
- * `DEFLATE_NO_ROOM`.
1097
+ * `DEFLATE_NO_ROOM`, which a pending `begin` refusal also answers.
954
1098
  */
955
1099
  flushBits(out: u8[], op: i32, oe: i32): i32 {
956
- const bytes: i32 = (this.bitCount + 7) >> 3
957
- if (op < 0 || oe > toI32(out.length) || bytes > oe - op) {
1100
+ return this.settle(this.writeBits(out, op, oe))
1101
+ }
1102
+
1103
+ /** `flushBits` without settling `overrun`: a step inside a write. */
1104
+ private writeBits(out: u8[], op: i32, oe: i32): i32 {
1105
+ // The buffer holds at most 64 bits: the mask keeps every bit of the
1106
+ // count, and tells the prover so.
1107
+ const bytes: i32 = toI32(((this.bitCount + 7) >> 3) & 15)
1108
+ if (op < 0 || oe < 0 || oe > toI32(out.length) || bytes > oe - op) {
958
1109
  return DEFLATE_NO_ROOM
959
1110
  }
1111
+ // Cannot wrap: op + bytes <= oe was checked above.
1112
+ const end: i32 = toI32(toU32(op) + toU32(bytes))
960
1113
  let p: i32 = op
961
1114
  let bb: u64 = this.bitBuf
962
- for (let i: i32 = 0; i < bytes; i += 1) {
1115
+ while (p < end) {
963
1116
  uncheckedSet(out, p, toU8(bb & toU64(255)))
964
1117
  bb = bb >> toU64(8)
965
1118
  p += 1
@@ -976,17 +1129,20 @@ export class Deflater {
976
1129
  */
977
1130
  private putBits(out: u8[], op: i32, v: i32, n: i32): i32 {
978
1131
  let bb: u64 = this.bitBuf | (toU64(toU32(v)) << toU64(this.bitCount))
979
- let bc: i32 = this.bitCount + n
1132
+ let bc: u32 = this.bitCount + toU32(n)
980
1133
  let p: i32 = op
981
- if (bc >= 32) {
982
- deflateRoom(out, p, 4)
983
- uncheckedSet(out, p, toU8(bb & toU64(255)))
984
- uncheckedSet(out, p + 1, toU8((bb >> toU64(8)) & toU64(255)))
985
- uncheckedSet(out, p + 2, toU8((bb >> toU64(16)) & toU64(255)))
986
- uncheckedSet(out, p + 3, toU8((bb >> toU64(24)) & toU64(255)))
1134
+ if (bc >= toU32(32)) {
1135
+ if (p >= 0 && p <= toI32(out.length) - 4) {
1136
+ uncheckedSet(out, p, toU8(bb & toU64(255)))
1137
+ uncheckedSet(out, p + 1, toU8((bb >> toU64(8)) & toU64(255)))
1138
+ uncheckedSet(out, p + 2, toU8((bb >> toU64(16)) & toU64(255)))
1139
+ uncheckedSet(out, p + 3, toU8((bb >> toU64(24)) & toU64(255)))
1140
+ p += 4
1141
+ } else {
1142
+ this.overrun = true
1143
+ }
987
1144
  bb = bb >> toU64(32)
988
- bc -= 32
989
- p += 4
1145
+ bc -= toU32(32)
990
1146
  }
991
1147
  this.bitBuf = bb
992
1148
  this.bitCount = bc
@@ -999,18 +1155,11 @@ export class Deflater {
999
1155
  * starts at. Answers the new `op`; the caller has checked the room.
1000
1156
  */
1001
1157
  private alignBits(out: u8[], op: i32): i32 {
1002
- let p: i32 = op
1003
- let bb: u64 = this.bitBuf
1004
- let bc: i32 = this.bitCount
1005
- deflateRoom(out, p, (bc + 7) >> 3)
1006
- while (bc > 0) {
1007
- uncheckedSet(out, p, toU8(bb & toU64(255)))
1008
- bb = bb >> toU64(8)
1009
- bc -= 8
1010
- p += 1
1158
+ const p: i32 = this.writeBits(out, op, toI32(out.length))
1159
+ if (p < 0) {
1160
+ this.overrun = true
1161
+ return op
1011
1162
  }
1012
- this.bitBuf = 0
1013
- this.bitCount = 0
1014
1163
  return p
1015
1164
  }
1016
1165
 
@@ -1019,7 +1168,7 @@ export class Deflater {
1019
1168
  * Compresses `src[start .. end)` as blocks into `out[op .. oe)`, matching
1020
1169
  * back as far as `histStart`; `final` marks the last block BFINAL. Answers
1021
1170
  * the new output position, with up to 31 bits still in the bit buffer, or
1022
- * -1 when a block does not fit.
1171
+ * -1 when a range lies outside its array or a block does not fit.
1023
1172
  */
1024
1173
  compressRange(
1025
1174
  src: u8[],
@@ -1032,10 +1181,10 @@ export class Deflater {
1032
1181
  oe: i32
1033
1182
  ): i32 {
1034
1183
  if (start < 0 || histStart < 0 || histStart > start || start > end || end > toI32(src.length)) {
1035
- panic("Deflater.compressRange: a range outside its input")
1184
+ return this.settle(toI32(-1))
1036
1185
  }
1037
- if (op < 0 || oe > toI32(out.length) || op > oe) {
1038
- panic("Deflater.compressRange: a range outside its output")
1186
+ if (op < 0 || oe < 0 || oe > toI32(out.length) || op > oe) {
1187
+ return this.settle(toI32(-1))
1039
1188
  }
1040
1189
  let p: i32 = start
1041
1190
  let o: i32 = op
@@ -1044,57 +1193,83 @@ export class Deflater {
1044
1193
  return o
1045
1194
  }
1046
1195
  // An empty final block, in the fixed code: ten bits.
1047
- if ((this.bitCount + 10 + 7) >> 3 > oe - o) {
1048
- return -1
1196
+ if (toI32((this.bitCount + toU32(17)) >> 3) > oe - o) {
1197
+ return this.settle(toI32(-1))
1049
1198
  }
1050
1199
  o = this.putBits(out, o, toI32(3), toI32(3))
1051
- return this.putBits(out, o, this.fixedLitCodes[256], this.fixedLitLens[256])
1200
+ return this.settle(this.putBits(out, o, deflateFixedLitCode(256), deflateFixedLitLength(256)))
1052
1201
  }
1053
1202
  if (this.level === 0) {
1054
1203
  return this.writeStored(src, start, end, final, out, o, oe)
1055
1204
  }
1056
1205
  while (p < end) {
1057
- if (p + this.delta > DEFLATE_REBASE) {
1058
- this.rebase(p)
1206
+ const v: i32 = this.position(p)
1207
+ if (v < 0) {
1208
+ return this.settle(toI32(-1))
1209
+ }
1210
+ if (v > DEFLATE_REBASE) {
1211
+ this.rebase(p, v)
1059
1212
  }
1060
1213
  const q: i32 =
1061
1214
  this.level >= 4
1062
1215
  ? this.collectLazy(src, p, end, histStart)
1063
1216
  : this.collectGreedy(src, p, end, histStart)
1217
+ if (q < 0) {
1218
+ return this.settle(toI32(-1))
1219
+ }
1064
1220
  o = this.writeBlock(src, p, q, final && q === end, out, o, oe)
1065
1221
  if (o < 0) {
1066
- return -1
1222
+ return this.settle(toI32(-1))
1067
1223
  }
1068
1224
  p = q
1069
1225
  }
1226
+ return this.settle(o)
1227
+ }
1228
+
1229
+ /**
1230
+ * Answers `o`, or -1 when a store since the last call would have run past
1231
+ * `out` (`overrun`), which it clears: the end of every writing entry point.
1232
+ */
1233
+ private settle(o: i32): i32 {
1234
+ if (this.overrun) {
1235
+ this.overrun = false
1236
+ return -1
1237
+ }
1070
1238
  return o
1071
1239
  }
1072
1240
 
1073
1241
  /**
1074
1242
  * Slides every table position down so that index `p` of the input is a
1075
1243
  * window above the floor again; a position more than a window behind `p`
1076
- * becomes 0, which is never a candidate.
1244
+ * becomes 0, which is never a candidate. `v` is `p`'s position.
1077
1245
  */
1078
- private rebase(p: i32): void {
1079
- const shift: i32 = p + this.delta - (DEFLATE_WINDOW + 1)
1246
+ private rebase(p: i32, v: i32): void {
1247
+ // 1073741824 is DEFLATE_REBASE, spelled out for the bounds prover.
1248
+ if (p < 0 || v <= 1073741824) {
1249
+ return
1250
+ }
1251
+ const shift: i32 = v - (DEFLATE_WINDOW + 1)
1252
+ // A position is never negative; the masks below say so to the prover.
1080
1253
  const head: i32[] = this.head
1081
1254
  const prev: i32[] = this.prev
1082
1255
  for (let i: i32 = 0; i < toI32(head.length); i += 1) {
1083
- const v: i32 = head[i] - shift
1084
- head[i] = v > 0 ? v : 0
1256
+ const h: i32 = (head[i] & 0x7fffffff) - shift
1257
+ head[i] = h > 0 ? h : 0
1085
1258
  }
1086
1259
  for (let i: i32 = 0; i < toI32(prev.length); i += 1) {
1087
- const v: i32 = prev[i] - shift
1088
- prev[i] = v > 0 ? v : 0
1260
+ const h: i32 = (prev[i] & 0x7fffffff) - shift
1261
+ prev[i] = h > 0 ? h : 0
1089
1262
  }
1090
- this.delta = this.delta - shift
1091
- this.base = this.base - shift
1263
+ this.delta = 32769 - p // DEFLATE_WINDOW + 1 - p
1264
+ this.base = (this.base & 0x7fffffff) - shift
1092
1265
  }
1093
1266
 
1094
1267
  /**
1095
1268
  * The best match at `p`, after recording `p` in the chains: answers
1096
1269
  * `len << 16 | dist`, or 0 for none at least `minMatch` long. `p + 4 <=
1097
- * end`, which the caller checks.
1270
+ * end`, which the caller checks. Answers -1, recording nothing, when a
1271
+ * table is not its size or `p` is outside that bound; the constructor and
1272
+ * the caller rule both out.
1098
1273
  */
1099
1274
  private longest(src: u8[], p: i32, end: i32, histStart: i32): i32 {
1100
1275
  const head: i32[] = this.head
@@ -1103,13 +1278,16 @@ export class Deflater {
1103
1278
  toI32(head.length) !== DEFLATE_HASH_SIZE ||
1104
1279
  toI32(prev.length) !== DEFLATE_WINDOW ||
1105
1280
  p < 0 ||
1281
+ p > 2147483639 ||
1282
+ end < 4 ||
1106
1283
  p > end - 4 ||
1107
1284
  end > toI32(src.length)
1108
1285
  ) {
1109
- panic("Deflater.longest: a table is not its size")
1286
+ return -1
1110
1287
  }
1111
1288
  const delta: i32 = this.delta
1112
- const minMatch: i32 = this.minMatch
1289
+ // The mask keeps every bit (3 or 4), and tells the bounds prover so.
1290
+ const minMatch: i32 = this.minMatch & 7
1113
1291
  const at: integer<0, 2147483639> = p
1114
1292
  const word: u32 = deflateLoad32(src, at)
1115
1293
  const h: i32 =
@@ -1126,33 +1304,42 @@ export class Deflater {
1126
1304
  const maxLen: i32 = roomy ? DEFLATE_MAX_MATCH : end - p
1127
1305
  let best: i32 = minMatch - 1
1128
1306
  let bestDist: i32 = 0
1129
- const limit: i32 = v - DEFLATE_WINDOW
1130
- const floor: i32 = limit > histStart + delta ? limit : histStart + delta
1307
+ // Cannot wrap: `v` and `histStart + delta` are positions in the
1308
+ // chains' numbering, which `rebase` keeps between 0 and 2^31 - 1.
1309
+ const limit: i32 = toI32(toU32(v) - toU32(DEFLATE_WINDOW))
1310
+ const hd: i32 = toI32(toU32(histStart) + toU32(delta))
1311
+ const floor: i32 = limit > hd ? limit : hd
1131
1312
  const nice: i32 = this.niceLength < maxLen ? this.niceLength : maxLen
1132
1313
  const mask: u32 = minMatch === 3 ? toU32(0xffffff) : ~toU32(0)
1133
1314
  let chain: i32 = this.maxChain
1134
1315
  while (cand >= floor && cand < v && chain > 0) {
1135
- const cd: i32 = cand - delta
1316
+ // Cannot wrap: `cand` lies in [histStart + delta, p + delta).
1317
+ const cd: i32 = toI32(toU32(cand) - toU32(delta))
1136
1318
  if (cd < 0 || cd > 2147483639) {
1137
1319
  break
1138
1320
  }
1139
1321
  const ci: integer<0, 2147483639> = cd
1140
1322
  // The byte that would make this match the longest yet, first: most
1141
1323
  // candidates fail on it.
1142
- if (uncheckedGet(src, ci + best) === uncheckedGet(src, p + best)) {
1324
+ // Cannot wrap: `ci` is below `p` and `best` below `maxLen`, so both
1325
+ // sums stay under `end`; a match length is at most 258.
1326
+ if (
1327
+ uncheckedGet(src, toI32(toU32(ci) + toU32(best))) === uncheckedGet(src, toI32(toU32(p) + toU32(best)))
1328
+ ) {
1143
1329
  let l: i32 = 0
1144
1330
  if (roomy) {
1145
1331
  const x: u64 = deflateLoad64(src, ci) ^ deflateLoad64(src, at)
1146
1332
  l =
1147
1333
  x !== toU64(0)
1148
1334
  ? deflateCtz64(x) >> 3
1149
- : toI32(8) + deflateMatchLength(src, ci + 8, p + 8, maxLen - 8)
1335
+ : toI32(toU32(8) + toU32(deflateMatchLength(src, ci + 8, p + 8, DEFLATE_MAX_MATCH - 8)))
1150
1336
  } else if (((deflateLoad32(src, ci) ^ word) & mask) === 0) {
1151
1337
  l = deflateMatchLength(src, ci, p, maxLen)
1152
1338
  }
1153
1339
  if (l > best) {
1154
1340
  best = l
1155
- bestDist = v - cand
1341
+ // Cannot wrap: `cand` is below `v`, by at most the window.
1342
+ bestDist = toI32(toU32(v) - toU32(cand))
1156
1343
  if (l >= nice) {
1157
1344
  break
1158
1345
  }
@@ -1171,23 +1358,6 @@ export class Deflater {
1171
1358
  return (best << 16) | bestDist
1172
1359
  }
1173
1360
 
1174
- /** Records `p` in the chains without searching; `p + 4 <= src.length`. */
1175
- private insert(src: u8[], p: i32): void {
1176
- const head: i32[] = this.head
1177
- const prev: i32[] = this.prev
1178
- if (toI32(head.length) !== DEFLATE_HASH_SIZE || toI32(prev.length) !== DEFLATE_WINDOW) {
1179
- panic("Deflater.insert: a table is not its size")
1180
- }
1181
- const word: u32 = deflateLoad32(src, p)
1182
- const h: i32 =
1183
- this.minMatch === 3
1184
- ? toI32(((word << 8) * toU32(DEFLATE_HASH_MUL)) >>> 17)
1185
- : toI32((word * toU32(DEFLATE_HASH_MUL)) >>> 17)
1186
- const v: i32 = p + this.delta
1187
- uncheckedSet(prev, v & (DEFLATE_WINDOW - 1), uncheckedGet(head, h))
1188
- uncheckedSet(head, h, v)
1189
- }
1190
-
1191
1361
  /** Clears the block's symbols and frequencies. */
1192
1362
  private startBlock(): void {
1193
1363
  this.litFreq.fill(0)
@@ -1195,44 +1365,12 @@ export class Deflater {
1195
1365
  this.count = 0
1196
1366
  }
1197
1367
 
1198
- /** Records the match `len`, `dist` as the block's next symbol. */
1199
- private addMatch(len: i32, dist: i32): void {
1200
- const tokens: i32[] = this.tokens
1201
- const n: i32 = this.count
1202
- if (n < 0 || n >= toI32(tokens.length) || len < 3 || len > 258 || dist < 1 || dist > DEFLATE_WINDOW) {
1203
- panic("Deflater.addMatch: a match outside the format")
1204
- }
1205
- uncheckedSet(tokens, n, (dist << 9) | (253 + len))
1206
- this.count = n + 1
1207
- const ls: i32 = uncheckedGet(this.lengthSymbol, len - 3)
1208
- const lf: i32[] = this.litFreq
1209
- uncheckedSet(lf, 257 + ls, uncheckedGet(lf, 257 + ls) + 1)
1210
- const ds: i32 =
1211
- dist <= 256
1212
- ? uncheckedGet(this.distSymbol, dist - 1)
1213
- : uncheckedGet(this.distSymbol, ((dist - 1) >> 7) + 256)
1214
- const df: i32[] = this.distFreq
1215
- uncheckedSet(df, ds, uncheckedGet(df, ds) + 1)
1216
- }
1217
-
1218
- /** Records the literal `b` as the block's next symbol. */
1219
- private addLiteral(b: i32): void {
1220
- const tokens: i32[] = this.tokens
1221
- const n: i32 = this.count
1222
- if (n < 0 || n >= toI32(tokens.length) || b < 0 || b > 255) {
1223
- panic("Deflater.addLiteral: a literal outside the format")
1224
- }
1225
- uncheckedSet(tokens, n, b)
1226
- this.count = n + 1
1227
- const lf: i32[] = this.litFreq
1228
- uncheckedSet(lf, b, uncheckedGet(lf, b) + 1)
1229
- }
1230
-
1231
1368
  /**
1232
1369
  * Fills the block's symbols greedily from `start`, and answers where the
1233
- * block ends: at `end`, or where the symbol buffer filled. The match
1234
- * finder, the chains and the symbol bookkeeping are written out in this one
1235
- * loop over locals, because this is the fast level's whole cost.
1370
+ * block ends: at `end`, or where the symbol buffer filled; -1 when a table
1371
+ * is not its size, which the constructor rules out. The match finder, the
1372
+ * chains and the symbol bookkeeping are written out in this one loop over
1373
+ * locals, because this is the fast level's whole cost.
1236
1374
  */
1237
1375
  private collectGreedy(src: u8[], start: i32, end: i32, histStart: i32): i32 {
1238
1376
  this.startBlock()
@@ -1252,14 +1390,17 @@ export class Deflater {
1252
1390
  toI32(lsym.length) < 256 ||
1253
1391
  toI32(dsym.length) < 512
1254
1392
  ) {
1255
- panic("Deflater.collectGreedy: a table is not its size")
1393
+ return -1
1256
1394
  }
1257
1395
  const delta: i32 = this.delta
1258
- const lo: i32 = histStart + delta
1396
+ // Cannot wrap: positions in the chains' numbering, input positions and
1397
+ // `end` are never negative, and `rebase` keeps the first under 2^31.
1398
+ const lo: i32 = toI32(toU32(histStart) + toU32(delta))
1259
1399
  const maxChain: i32 = this.maxChain
1260
1400
  const niceLength: i32 = this.niceLength
1261
1401
  const room: i32 = DEFLATE_BLOCK_TOKENS - 1
1262
- const last: i32 = end - 4
1402
+ const last: i32 = toI32(toU32(end) - toU32(4))
1403
+ const full: i32 = toI32(toU32(end) - toU32(DEFLATE_MAX_MATCH))
1263
1404
  let n: i32 = 0
1264
1405
  let p: i32 = start
1265
1406
  while (p < end && n < room) {
@@ -1268,35 +1409,52 @@ export class Deflater {
1268
1409
  if (p >= 0 && p <= last && p <= 2147483639) {
1269
1410
  const word: u32 = deflateLoad32(src, p)
1270
1411
  const h: i32 = toI32((word * toU32(DEFLATE_HASH_MUL)) >>> 17)
1271
- const v: i32 = p + delta
1412
+ const v: i32 = toI32(toU32(p) + toU32(delta))
1272
1413
  let cand: i32 = uncheckedGet(head, h)
1273
1414
  uncheckedSet(head, h, v)
1274
1415
  uncheckedSet(prev, v & (DEFLATE_WINDOW - 1), cand)
1275
- const maxLen: i32 = p <= end - DEFLATE_MAX_MATCH ? DEFLATE_MAX_MATCH : end - p
1416
+ // Cannot wrap: `p` is at most `last`, below `end`.
1417
+ const maxLen: i32 = p <= full ? DEFLATE_MAX_MATCH : toI32(toU32(end) - toU32(p))
1276
1418
  const nice: i32 = niceLength < maxLen ? niceLength : maxLen
1277
- const limit: i32 = v - DEFLATE_WINDOW
1419
+ const limit: i32 = toI32(toU32(v) - toU32(DEFLATE_WINDOW))
1278
1420
  let chain: i32 = maxChain
1279
1421
  while (cand >= limit && cand >= lo && cand < v && chain > 0) {
1280
- const ci: i32 = cand - delta
1422
+ // Cannot wrap: `cand` lies in [histStart + delta, p + delta).
1423
+ const ci: i32 = toI32(toU32(cand) - toU32(delta))
1281
1424
  if (ci >= 0 && ci <= 2147483639 && deflateLoad32(src, ci) === word) {
1282
1425
  let l: i32 = 0
1283
- if (p <= end - DEFLATE_MAX_MATCH && ci <= 2147483627) {
1426
+ if (p <= full && ci <= 2147483627) {
1284
1427
  const a4: i32 = ci + 4
1285
1428
  const b4: i32 = p + 4
1286
1429
  let x: u64 = toU64(1)
1287
1430
  if (a4 >= 0 && a4 <= 2147483639 && b4 >= 0 && b4 <= 2147483639) {
1288
1431
  x = deflateLoad64(src, a4) ^ deflateLoad64(src, b4)
1289
1432
  }
1433
+ // Cannot wrap: `p` is at most `end - 258`, `maxLen` is at least
1434
+ // 4 (`p` is at most `last`), and a match length is at most 258.
1290
1435
  l =
1291
1436
  x !== toU64(0)
1292
1437
  ? toI32(4) + (deflateCtz64(x) >> 3)
1293
- : toI32(12) + deflateMatchLength(src, ci + 12, p + 12, maxLen - 12)
1438
+ : toI32(
1439
+ toU32(12) +
1440
+ toU32(
1441
+ deflateMatchLength(
1442
+ src,
1443
+ ci + 12,
1444
+ toI32(toU32(p) + toU32(12)),
1445
+ DEFLATE_MAX_MATCH - 12
1446
+ )
1447
+ )
1448
+ )
1294
1449
  } else {
1295
- l = 4 + deflateMatchLength(src, ci + 4, p + 4, maxLen - 4)
1450
+ l = toI32(
1451
+ toU32(4) + toU32(deflateMatchLength(src, ci + 4, p + 4, toI32(toU32(maxLen) - toU32(4))))
1452
+ )
1296
1453
  }
1297
1454
  if (l > best) {
1298
1455
  best = l
1299
- bestDist = v - cand
1456
+ // Cannot wrap: `cand` is below `v`, by at most the window.
1457
+ bestDist = toI32(toU32(v) - toU32(cand))
1300
1458
  if (l >= nice) {
1301
1459
  break
1302
1460
  }
@@ -1307,15 +1465,18 @@ export class Deflater {
1307
1465
  }
1308
1466
  }
1309
1467
  if (best >= 4) {
1310
- uncheckedSet(tokens, n, (bestDist << 9) | (253 + best))
1468
+ // Cannot wrap: a match is 4 to 258 bytes at a distance of 1 to the
1469
+ // window, a length symbol is under 29, a count is at most the
1470
+ // block's token count, and the match ends by `end`.
1471
+ uncheckedSet(tokens, n, (bestDist << 9) | toI32(toU32(253) + toU32(best)))
1311
1472
  n += 1
1312
- const ls: i32 = 257 + uncheckedGet(lsym, best - 3)
1313
- uncheckedSet(lf, ls, uncheckedGet(lf, ls) + 1)
1314
- const ds: i32 =
1315
- bestDist <= 256 ? uncheckedGet(dsym, bestDist - 1) : uncheckedGet(dsym, ((bestDist - 1) >> 7) + 256)
1316
- uncheckedSet(df, ds, uncheckedGet(df, ds) + 1)
1473
+ const ls: i32 = toI32(toU32(257) + toU32(uncheckedGet(lsym, best - 3)))
1474
+ uncheckedSet(lf, ls, toI32(toU32(uncheckedGet(lf, ls)) + toU32(1)))
1475
+ const bd: i32 = toI32(toU32(bestDist) - toU32(1))
1476
+ const ds: i32 = bestDist <= 256 ? uncheckedGet(dsym, bd) : uncheckedGet(dsym, (bd >> 7) + 256)
1477
+ uncheckedSet(df, ds, toI32(toU32(uncheckedGet(df, ds)) + toU32(1)))
1317
1478
  // Every position the match covers goes into the chains.
1318
- const stop: i32 = p + best
1479
+ const stop: i32 = toI32(toU32(p) + toU32(best))
1319
1480
  const insertEnd: i32 = stop <= last ? stop : last + 1
1320
1481
  let vq: i32 = wrappingAdd(p, delta)
1321
1482
  for (let q: i32 = p + 1; q < insertEnd && q >= 0 && q <= 2147483639; q += 1) {
@@ -1330,7 +1491,8 @@ export class Deflater {
1330
1491
  const b: i32 = toI32(uncheckedGet(src, p))
1331
1492
  uncheckedSet(tokens, n, b)
1332
1493
  n += 1
1333
- uncheckedSet(lf, b, uncheckedGet(lf, b) + 1)
1494
+ // Cannot wrap, as for the counts above.
1495
+ uncheckedSet(lf, b, toI32(toU32(uncheckedGet(lf, b)) + toU32(1)))
1334
1496
  p += 1
1335
1497
  }
1336
1498
  }
@@ -1340,254 +1502,425 @@ export class Deflater {
1340
1502
 
1341
1503
  /**
1342
1504
  * Fills the block's symbols from `p`, deferring each match by a position
1343
- * while the next one finds a longer one; answers where the block ends.
1505
+ * while the next one finds a longer one; answers where the block ends, or
1506
+ * -1 when a table is not its size or the match finder answers a match
1507
+ * outside the format, which the constructor and `longest` rule out. The
1508
+ * symbol bookkeeping and the chain inserts are written out over locals, as
1509
+ * in `collectGreedy`.
1344
1510
  */
1345
1511
  private collectLazy(src: u8[], start: i32, end: i32, histStart: i32): i32 {
1346
1512
  this.startBlock()
1347
- let p: i32 = start
1513
+ const head: i32[] = this.head
1514
+ const prev: i32[] = this.prev
1515
+ const tokens: i32[] = this.tokens
1516
+ const lf: i32[] = this.litFreq
1517
+ const df: i32[] = this.distFreq
1518
+ const lsym: i32[] = this.lengthSymbol
1519
+ const dsym: i32[] = this.distSymbol
1520
+ if (
1521
+ toI32(head.length) !== DEFLATE_HASH_SIZE ||
1522
+ toI32(prev.length) !== DEFLATE_WINDOW ||
1523
+ toI32(tokens.length) !== DEFLATE_BLOCK_TOKENS ||
1524
+ toI32(lf.length) < 288 ||
1525
+ toI32(df.length) < 32 ||
1526
+ toI32(lsym.length) < 256 ||
1527
+ toI32(dsym.length) < 512
1528
+ ) {
1529
+ return -1
1530
+ }
1531
+ const three: boolean = this.minMatch === 3
1532
+ const lazyLength: i32 = this.lazyLength
1348
1533
  const room: i32 = DEFLATE_BLOCK_TOKENS - 2
1349
- while (p < end && this.count < room) {
1350
- let m: i32 = 0
1351
- if (p + 4 <= end) {
1534
+ // Cannot wrap: `end` is never negative.
1535
+ const last: i32 = toI32(toU32(end) - toU32(4))
1536
+ let n: i32 = 0
1537
+ let p: i32 = start
1538
+ // The match `longest` found one position on, when it beat the one at
1539
+ // `p` and the position was taken as a literal: the next turn takes it
1540
+ // up without searching again. 0 for none.
1541
+ let carry: i32 = 0
1542
+ // The first position `longest` has not recorded.
1543
+ let inserted: i32 = p
1544
+ // A carried match is written even when the block is otherwise full: the
1545
+ // room leaves two tokens of slack.
1546
+ while (p < end && (n < room || carry !== 0)) {
1547
+ let m: i32 = carry
1548
+ carry = 0
1549
+ if (m === 0 && p <= last) {
1352
1550
  m = this.longest(src, p, end, histStart)
1551
+ // Cannot wrap: `p` is at most `last`.
1552
+ inserted = toI32(toU32(p) + toU32(1))
1553
+ }
1554
+ if (m < 0) {
1555
+ return -1
1556
+ }
1557
+ if (m !== 0 && m >> 16 < lazyLength && p < last && n < room) {
1558
+ // Cannot wrap: `p` is below `last`, so `p + 2` is at most `end - 3`.
1559
+ const p1: i32 = toI32(toU32(p) + toU32(1))
1560
+ const m2: i32 = this.longest(src, p1, end, histStart)
1561
+ if (m2 < 0) {
1562
+ return -1
1563
+ }
1564
+ inserted = toI32(toU32(p) + toU32(2))
1565
+ if (m2 >> 16 > m >> 16) {
1566
+ carry = m2
1567
+ m = 0
1568
+ }
1353
1569
  }
1354
1570
  if (m === 0) {
1355
- this.addLiteral(toI32(uncheckedGet(src, p)))
1571
+ const b: i32 = toI32(uncheckedGet(src, p))
1572
+ uncheckedSet(tokens, n, b)
1573
+ // Cannot wrap: a literal is taken only below `room` (a carried match
1574
+ // is never one), and a count is at most the block's token count.
1575
+ n = toI32(toU32(n) + toU32(1))
1576
+ uncheckedSet(lf, b, toI32(toU32(uncheckedGet(lf, b)) + toU32(1)))
1356
1577
  p += 1
1357
1578
  } else {
1358
- let inserted: i32 = p + 1
1359
- while (m >> 16 < this.lazyLength && p + 5 <= end && this.count < room) {
1360
- const m2: i32 = this.longest(src, p + 1, end, histStart)
1361
- inserted = p + 2
1362
- if (m2 >> 16 > m >> 16) {
1363
- this.addLiteral(toI32(uncheckedGet(src, p)))
1364
- p += 1
1365
- m = m2
1366
- } else {
1367
- break
1368
- }
1369
- }
1370
1579
  const len: i32 = m >> 16
1371
- this.addMatch(len, m & 0xffff)
1372
- const stop: i32 = p + len
1373
- let q: i32 = inserted
1374
- const last: i32 = end - 4
1375
- while (q < stop && q <= last) {
1376
- this.insert(src, q)
1377
- q += 1
1580
+ const dist: i32 = m & 0xffff
1581
+ if (len < 3 || len > DEFLATE_MAX_MATCH || dist < 1 || dist > DEFLATE_WINDOW) {
1582
+ return -1
1583
+ }
1584
+ uncheckedSet(tokens, n, (dist << 9) | (253 + len))
1585
+ // Cannot wrap: `n` is at most `room`, a length symbol is under 29,
1586
+ // a count is at most the block's token count, and `longest` answers
1587
+ // only a match that ends by `end`.
1588
+ n = toI32(toU32(n) + toU32(1))
1589
+ const ls: i32 = toI32(toU32(257) + toU32(uncheckedGet(lsym, len - 3)))
1590
+ uncheckedSet(lf, ls, toI32(toU32(uncheckedGet(lf, ls)) + toU32(1)))
1591
+ const ds: i32 =
1592
+ dist <= 256 ? uncheckedGet(dsym, dist - 1) : uncheckedGet(dsym, ((dist - 1) >> 7) + 256)
1593
+ uncheckedSet(df, ds, toI32(toU32(uncheckedGet(df, ds)) + toU32(1)))
1594
+ // The positions the match covers that `longest` did not record go
1595
+ // into the chains.
1596
+ const stop: i32 = toI32(toU32(p) + toU32(len))
1597
+ const insertEnd: i32 = stop <= last ? stop : last + 1
1598
+ for (let q: i32 = inserted; q < insertEnd && q >= 0 && q <= 2147483639; q += 1) {
1599
+ const qa: integer<0, 2147483639> = q
1600
+ const word: u32 = deflateLoad32(src, qa)
1601
+ const hq: i32 = three
1602
+ ? toI32(((word << 8) * toU32(DEFLATE_HASH_MUL)) >>> 17)
1603
+ : toI32((word * toU32(DEFLATE_HASH_MUL)) >>> 17)
1604
+ // Cannot wrap: `rebase` keeps a position in the chains' numbering
1605
+ // between 0 and 2^31 - 1.
1606
+ const vq: i32 = toI32(toU32(q) + toU32(this.delta))
1607
+ uncheckedSet(prev, vq & (DEFLATE_WINDOW - 1), uncheckedGet(head, hq))
1608
+ uncheckedSet(head, hq, vq)
1378
1609
  }
1379
1610
  p = stop
1380
1611
  }
1381
1612
  }
1613
+ this.count = n
1382
1614
  return p
1383
1615
  }
1384
1616
 
1385
1617
  /**
1386
- * The bits a stored rendering of `n` bytes takes from a bit buffer holding
1387
- * `pending` bits: each piece of up to 65,535 bytes has three header bits,
1388
- * the padding to a byte and four bytes of `LEN` / `NLEN`.
1618
+ * The bytes a stored rendering of `n` bytes adds to them, counted from the
1619
+ * start of a bit buffer holding `pending` bits (under 64): each piece of
1620
+ * up to 65,535 bytes has three header bits, the padding to a byte and four
1621
+ * bytes of `LEN` / `NLEN`. The answer is under 2^18.
1389
1622
  */
1390
- private storedBits(n: i32, pending: i32): i32 {
1391
- let bits: i32 = 0
1392
- let left: i32 = n
1393
- let bc: i32 = pending
1394
- let first: boolean = true
1395
- while (first || left > 0) {
1396
- first = false
1397
- const take: i32 = left < DEFLATE_STORED_MAX ? left : DEFLATE_STORED_MAX
1398
- const header: i32 = ((bc + 3 + 7) & ~7) - bc
1399
- bits += header + 32 + 8 * take
1400
- bc = 0
1401
- left -= take
1623
+ private storedExtra(n: i32, pending: i32): i32 {
1624
+ let more: i32 = 0
1625
+ // `n` is below 2^31, so there are at most 32,768 pieces after the first:
1626
+ // the bound on `more` never stops the loop.
1627
+ for (let left: i32 = n; left > 65535 && more < 32768; left -= 65535) {
1628
+ more += 1
1402
1629
  }
1403
- return bits
1630
+ // The masks keep every bit, and tell the bounds prover so.
1631
+ return ((((pending & 63) + 10) >> 3) & 15) + 4 + (more & 0x7fff) * 5
1404
1632
  }
1405
1633
 
1406
1634
  /**
1407
1635
  * @internal Called by `GzipWriter` (std/compress/gzip.ts).
1408
1636
  * Writes `src[start .. end)` as stored blocks, the last BFINAL when
1409
1637
  * `final`; answers the new position, or -1 without writing when it does
1410
- * not fit in `out[op .. oe)`.
1638
+ * not fit in `out[op .. oe)` or the ranges are backwards or negative.
1411
1639
  */
1412
1640
  writeStored(src: u8[], start: i32, end: i32, final: boolean, out: u8[], op: i32, oe: i32): i32 {
1413
- const bits: i32 = this.storedBits(end - start, this.bitCount)
1414
- if ((this.bitCount + bits + 7) >> 3 > oe - op) {
1641
+ if (start < 0 || end < start || op < 0 || oe < op) {
1642
+ return -1
1643
+ }
1644
+ // Cannot wrap: `start <= end` and `op <= oe`, both from zero up.
1645
+ const n: i32 = toI32(toU32(end) - toU32(start))
1646
+ const room: i32 = toI32(toU32(oe) - toU32(op))
1647
+ // Under 2^18, as `storedExtra` says: the mask keeps every bit.
1648
+ const extra: i32 = this.storedExtra(n, toI32(this.bitCount)) & 0x3ffff
1649
+ // Cannot wrap: `extra <= room` by the first test.
1650
+ if (room < extra || n > toI32(toU32(room) - toU32(extra))) {
1415
1651
  return -1
1416
1652
  }
1417
1653
  let p: i32 = start
1654
+ let left: i32 = n
1418
1655
  let o: i32 = op
1419
1656
  let first: boolean = true
1420
- while (first || p < end) {
1657
+ while (first || left > 0) {
1421
1658
  first = false
1422
- const take: i32 = end - p < DEFLATE_STORED_MAX ? end - p : DEFLATE_STORED_MAX
1423
- const last: boolean = p + take === end
1424
- o = this.putBits(out, o, toI32(final && last ? 1 : 0), toI32(3))
1659
+ // `left` is never negative, so the mask keeps every bit; it tells the
1660
+ // bounds prover `take` fits a stored block's 16-bit length.
1661
+ const take: i32 = (left < DEFLATE_STORED_MAX ? left : DEFLATE_STORED_MAX) & 0xffff
1662
+ o = this.putBits(out, o, toI32(final && take === left ? 1 : 0), toI32(3))
1425
1663
  o = this.alignBits(out, o)
1426
- deflateRoom(out, o, 4)
1427
- uncheckedSet(out, o, toU8(take & 255))
1428
- uncheckedSet(out, o + 1, toU8(take >> 8))
1429
- uncheckedSet(out, o + 2, toU8(~take & 255))
1430
- uncheckedSet(out, o + 3, toU8((~take >> 8) & 255))
1431
- o += 4
1432
- copyBytes(out, o, src, p, take)
1433
- o += take
1434
- p += take
1664
+ if (o >= 0 && o <= toI32(out.length) - 4 && tryCopyBytes(out, o + 4, src, p, take)) {
1665
+ uncheckedSet(out, o, toU8(take & 255))
1666
+ uncheckedSet(out, o + 1, toU8(take >> 8))
1667
+ uncheckedSet(out, o + 2, toU8(~take & 255))
1668
+ uncheckedSet(out, o + 3, toU8((~take >> 8) & 255))
1669
+ // Cannot wrap: the copy put `take` bytes after `o + 4` inside `out`.
1670
+ o = toI32(toU32(o) + toU32(4 + take))
1671
+ } else {
1672
+ this.overrun = true
1673
+ }
1674
+ // Cannot wrap: `p + take` is at most `end`.
1675
+ p = toI32(toU32(p) + toU32(take))
1676
+ // Cannot wrap: `take <= left` on the branch that subtracts.
1677
+ left = left > take ? toI32(toU32(left) - toU32(take)) : 0
1435
1678
  }
1436
- return o
1679
+ return this.settle(o)
1437
1680
  }
1438
1681
 
1439
1682
  /**
1440
1683
  * Builds the run-length coded lengths of the dynamic header (§3.2.7) for
1441
1684
  * `hlit` literal/length and `hdist` distance lengths, and their
1442
- * frequencies in `clFreq`.
1685
+ * frequencies in `clFreq`. Answers false, building nothing, when the
1686
+ * scratch is not its size or the counts are past the format's, which the
1687
+ * constructor and `writeBlock` rule out.
1443
1688
  */
1444
- private buildRle(hlit: i32, hdist: i32): void {
1689
+ private buildRle(hlit: i32, hdist: i32): boolean {
1445
1690
  const rle: i32[] = this.rle
1446
1691
  const freq: i32[] = this.clFreq
1447
1692
  const ll: i32[] = this.litLens
1448
1693
  const dl: i32[] = this.distLens
1449
- if (toI32(rle.length) < 320 || toI32(freq.length) < 19 || hlit > 288 || hdist > 32) {
1450
- panic("Deflater.buildRle: a header outside its scratch")
1451
- }
1452
1694
  freq.fill(0)
1695
+ if (
1696
+ toI32(rle.length) < 320 ||
1697
+ toI32(freq.length) < 19 ||
1698
+ hlit < 0 ||
1699
+ hlit > 288 ||
1700
+ hdist < 0 ||
1701
+ hdist > 32
1702
+ ) {
1703
+ return false
1704
+ }
1705
+ // At most 320 lengths, each giving at most one entry: the masks on `n`
1706
+ // and the counts keep every bit, and tell the bounds prover so, and the
1707
+ // bound on `run` restates `i + run < total`.
1453
1708
  const total: i32 = hlit + hdist
1454
1709
  let n: i32 = 0
1455
1710
  let i: i32 = 0
1456
- while (i < total) {
1711
+ // `i` is never negative: the second test never stops the loop.
1712
+ while (i < total && i >= 0) {
1457
1713
  const l: i32 = i < hlit ? uncheckedGet(ll, i) : uncheckedGet(dl, i - hlit)
1458
1714
  let run: i32 = 1
1459
1715
  while (
1716
+ run < 320 &&
1460
1717
  i + run < total &&
1461
1718
  (i + run < hlit ? uncheckedGet(ll, i + run) : uncheckedGet(dl, i + run - hlit)) === l
1462
1719
  ) {
1463
1720
  run += 1
1464
1721
  }
1465
- i += run
1722
+ // Cannot wrap: `i + run` is at most `total`, at most 320.
1723
+ i = toI32(toU32(i) + toU32(run))
1466
1724
  if (l === 0) {
1467
- while (run >= 11) {
1468
- const r: i32 = run < 138 ? run : 138
1725
+ // `run` is at most 320, the bound on the scan above: the second test
1726
+ // never stops the loop, and the mask keeps every bit of `r`.
1727
+ while (run >= 11 && run <= 320) {
1728
+ const r: i32 = (run < 138 ? run : toI32(138)) & 255
1469
1729
  uncheckedSet(rle, n, ((r - 11) << 8) | 18)
1470
- n += 1
1471
- freq[18] += 1
1730
+ n = (n + 1) & 511
1731
+ freq[18] = (freq[18] & 511) + 1
1472
1732
  run -= r
1473
1733
  }
1474
1734
  if (run >= 3) {
1475
1735
  uncheckedSet(rle, n, ((run - 3) << 8) | 17)
1476
- n += 1
1477
- freq[17] += 1
1736
+ n = (n + 1) & 511
1737
+ freq[17] = (freq[17] & 511) + 1
1478
1738
  run = 0
1479
1739
  }
1480
1740
  } else {
1481
1741
  uncheckedSet(rle, n, l)
1482
- n += 1
1742
+ n = (n + 1) & 511
1483
1743
  if (l >= 0 && l < 19) {
1484
- uncheckedSet(freq, l, uncheckedGet(freq, l) + 1)
1744
+ uncheckedSet(freq, l, (uncheckedGet(freq, l) & 511) + 1)
1485
1745
  }
1486
1746
  run -= 1
1487
- while (run >= 3) {
1488
- const r: i32 = run < 6 ? run : 6
1747
+ // As above, the second test never stops the loop.
1748
+ while (run >= 3 && run <= 320) {
1749
+ const r: i32 = (run < 6 ? run : toI32(6)) & 7
1489
1750
  uncheckedSet(rle, n, ((r - 3) << 8) | 16)
1490
- n += 1
1491
- freq[16] += 1
1751
+ n = (n + 1) & 511
1752
+ freq[16] = (freq[16] & 511) + 1
1492
1753
  run -= r
1493
1754
  }
1494
1755
  }
1495
1756
  while (run > 0) {
1496
1757
  uncheckedSet(rle, n, l)
1497
- n += 1
1758
+ n = (n + 1) & 511
1498
1759
  if (l >= 0 && l < 19) {
1499
- uncheckedSet(freq, l, uncheckedGet(freq, l) + 1)
1760
+ uncheckedSet(freq, l, (uncheckedGet(freq, l) & 511) + 1)
1500
1761
  }
1501
1762
  run -= 1
1502
1763
  }
1503
1764
  }
1504
1765
  this.rleCount = n
1766
+ return true
1505
1767
  }
1506
1768
 
1507
1769
  /**
1508
1770
  * Writes the block's symbols, `src[start .. end)`'s, as the smallest of a
1509
1771
  * dynamic, a fixed and a stored block; answers the new position, or -1
1510
- * without writing when that does not fit in `out[op .. oe)`.
1772
+ * without writing when that does not fit in `out[op .. oe)`. Answers -1
1773
+ * too, the stream then unusable, when a table is not its size, a range is
1774
+ * backwards or negative, or the header holds a code-length symbol past 18,
1775
+ * which the constructor, `compressRange` and `buildRle` rule out.
1511
1776
  */
1512
1777
  private writeBlock(src: u8[], start: i32, end: i32, final: boolean, out: u8[], op: i32, oe: i32): i32 {
1513
1778
  const lf: i32[] = this.litFreq
1514
1779
  const df: i32[] = this.distFreq
1780
+ const ll: i32[] = this.litLens
1781
+ const dl: i32[] = this.distLens
1782
+ const cf: i32[] = this.clFreq
1783
+ const cl: i32[] = this.clLens
1784
+ const cc: i32[] = this.clCodes
1785
+ if (
1786
+ toI32(lf.length) < 288 ||
1787
+ toI32(ll.length) < 288 ||
1788
+ toI32(dl.length) < 32 ||
1789
+ toI32(cf.length) < 19 ||
1790
+ toI32(cl.length) < 19 ||
1791
+ toI32(cc.length) < 19 ||
1792
+ start < 0 ||
1793
+ end < start ||
1794
+ op < 0 ||
1795
+ oe < op
1796
+ ) {
1797
+ return -1
1798
+ }
1515
1799
  lf[256] = 1
1516
- deflateLengths(lf, 286, 15, this.litLens, this.scratch)
1517
- deflateLengths(df, 30, 15, this.distLens, this.scratch)
1518
- this.litLens[286] = 0
1519
- this.litLens[287] = 0
1520
- this.distLens[30] = 0
1521
- this.distLens[31] = 0
1522
- deflateCanonical(this.litLens, 286, this.litCodes, this.countScratch, this.nextScratch)
1523
- deflateCanonical(this.distLens, 30, this.distCodes, this.countScratch, this.nextScratch)
1800
+ if (!deflateLengths(lf, 286, 15, ll, this.scratch) || !deflateLengths(df, 30, 15, dl, this.scratch)) {
1801
+ return -1
1802
+ }
1803
+ ll[286] = 0
1804
+ ll[287] = 0
1805
+ dl[30] = 0
1806
+ dl[31] = 0
1807
+ if (
1808
+ !deflateCanonical(ll, 286, this.litCodes, this.countScratch, this.nextScratch) ||
1809
+ !deflateCanonical(dl, 30, this.distCodes, this.countScratch, this.nextScratch)
1810
+ ) {
1811
+ return -1
1812
+ }
1524
1813
  let hlit: i32 = 286
1525
- while (hlit > 257 && this.litLens[hlit - 1] === 0) {
1814
+ while (hlit > 257 && ll[hlit - 1] === 0) {
1526
1815
  hlit -= 1
1527
1816
  }
1528
1817
  let hdist: i32 = 30
1529
- while (hdist > 1 && this.distLens[hdist - 1] === 0) {
1818
+ while (hdist > 1 && dl[hdist - 1] === 0) {
1530
1819
  hdist -= 1
1531
1820
  }
1532
- this.buildRle(hlit, hdist)
1533
- deflateLengths(this.clFreq, 19, 7, this.clLens, this.scratch)
1534
- deflateCanonical(this.clLens, 19, this.clCodes, this.countScratch, this.nextScratch)
1821
+ // The call may move any of `this`'s tables, as far as the bounds prover
1822
+ // knows, so their sizes are checked again.
1823
+ if (
1824
+ !this.buildRle(hlit, hdist) ||
1825
+ toI32(cf.length) < 19 ||
1826
+ toI32(cl.length) < 19 ||
1827
+ toI32(cc.length) < 19
1828
+ ) {
1829
+ return -1
1830
+ }
1831
+ if (
1832
+ !deflateLengths(cf, 19, 7, cl, this.scratch) ||
1833
+ !deflateCanonical(cl, 19, cc, this.countScratch, this.nextScratch)
1834
+ ) {
1835
+ return -1
1836
+ }
1535
1837
  let hclen: i32 = 19
1536
- while (hclen > 4 && this.clLens[deflateClOrder(hclen - 1)] === 0) {
1838
+ while (hclen > 4) {
1839
+ const k: i32 = deflateClOrder(hclen - 1)
1840
+ if (k < 0 || k >= 19) {
1841
+ return -1
1842
+ }
1843
+ if (cl[k] !== 0) {
1844
+ break
1845
+ }
1537
1846
  hclen -= 1
1538
1847
  }
1539
- // The three sizes, exactly. Extra bits are the same in both codes.
1848
+ // The three sizes, exactly. Extra bits are the same in both codes. A
1849
+ // block holds at most 16,385 symbols of at most 15 bits and 13 extra
1850
+ // bits, so every frequency is below 2^16, every length below 16, every
1851
+ // extra below 16 and every sum below 2^24: the masks keep every bit, and
1852
+ // tell the bounds prover so.
1540
1853
  let extra: i32 = 0
1541
- let dynBits: i32 = hclen * 3 + 17
1854
+ let dynBits: i32 = (hclen & 31) * 3 + 17
1542
1855
  let fixBits: i32 = 3
1543
1856
  for (let s: i32 = 0; s < 286; s += 1) {
1544
- const f: i32 = uncheckedGet(lf, s)
1545
- dynBits += f * uncheckedGet(this.litLens, s)
1546
- fixBits += f * uncheckedGet(this.fixedLitLens, s)
1857
+ const f: i32 = uncheckedGet(lf, s) & 0xffff
1858
+ dynBits = (dynBits + f * (uncheckedGet(this.litLens, s) & 15)) & 0xffffff
1859
+ fixBits = (fixBits + f * (uncheckedGet(this.fixedLitLens, s) & 15)) & 0xffffff
1547
1860
  if (s >= 257) {
1548
- extra += f * uncheckedGet(this.lengthExtra, s - 257)
1861
+ extra = (extra + f * (uncheckedGet(this.lengthExtra, s - 257) & 15)) & 0xffffff
1549
1862
  }
1550
1863
  }
1551
1864
  for (let d: i32 = 0; d < 30; d += 1) {
1552
- const f: i32 = uncheckedGet(df, d)
1553
- dynBits += f * uncheckedGet(this.distLens, d)
1554
- fixBits += f * 5
1555
- extra += f * uncheckedGet(this.distExtra, d)
1865
+ const f: i32 = uncheckedGet(df, d) & 0xffff
1866
+ dynBits = (dynBits + f * (uncheckedGet(this.distLens, d) & 15)) & 0xffffff
1867
+ fixBits = (fixBits + f * 5) & 0xffffff
1868
+ extra = (extra + f * (uncheckedGet(this.distExtra, d) & 15)) & 0xffffff
1556
1869
  }
1557
1870
  for (let s: i32 = 0; s < 19; s += 1) {
1558
- dynBits += this.clFreq[s] * this.clLens[s]
1559
- }
1560
- dynBits += 2 * this.clFreq[16] + 3 * this.clFreq[17] + 7 * this.clFreq[18]
1561
- dynBits += extra
1562
- fixBits += extra
1563
- const storedBits: i32 = this.storedBits(end - start, this.bitCount)
1564
- if (storedBits <= dynBits && storedBits <= fixBits) {
1871
+ dynBits = (dynBits + (cf[s] & 0xffff) * (cl[s] & 15)) & 0xffffff
1872
+ }
1873
+ dynBits = (dynBits + (cf[16] & 0xffff) * 2 + (cf[17] & 0xffff) * 3 + (cf[18] & 0xffff) * 7) & 0xffffff
1874
+ dynBits = (dynBits + extra) & 0xffffff
1875
+ fixBits = (fixBits + extra) & 0xffffff
1876
+ const bc: i32 = toI32(this.bitCount) & 63
1877
+ // The stored size, `8 * (n + storedExtra) - bc` bits, is at most a size
1878
+ // `b` exactly when `n + storedExtra` is at most `(b + bc) >> 3` bytes.
1879
+ // Cannot wrap: `start <= end`, both from zero up.
1880
+ const n: i32 = toI32(toU32(end) - toU32(start))
1881
+ // Under 2^18, as `storedExtra` says: the mask keeps every bit.
1882
+ const storedExtra: i32 = this.storedExtra(n, bc) & 0x3ffff
1883
+ const dynBytes: i32 = (dynBits + bc) >> 3
1884
+ const fixBytes: i32 = (fixBits + bc) >> 3
1885
+ if (n <= dynBytes - storedExtra && n <= fixBytes - storedExtra) {
1565
1886
  return this.writeStored(src, start, end, final, out, op, oe)
1566
1887
  }
1567
1888
  const dynamic: boolean = dynBits < fixBits
1568
- const bits: i32 = dynamic ? dynBits : fixBits
1569
- if ((this.bitCount + bits + 7) >> 3 > oe - op) {
1889
+ const bits: i32 = (dynamic ? dynBits : fixBits) & 0xffffff
1890
+ // Cannot wrap: `op <= oe`, both from zero up.
1891
+ if ((bc + bits + 7) >> 3 > toI32(toU32(oe) - toU32(op))) {
1570
1892
  return -1
1571
1893
  }
1572
- let header: i32 = dynamic ? toI32(4) : toI32(2)
1573
- if (final) {
1574
- header += 1
1575
- }
1576
- let o: i32 = this.putBits(out, op, header, toI32(3))
1894
+ let o: i32 = this.putBits(
1895
+ out,
1896
+ op,
1897
+ (dynamic ? toI32(4) : toI32(2)) | (final ? toI32(1) : toI32(0)),
1898
+ toI32(3)
1899
+ )
1577
1900
  if (dynamic) {
1578
- o = this.putBits(out, o, (hlit - 257) | ((hdist - 1) << 5) | ((hclen - 4) << 10), toI32(14))
1901
+ // `hlit`, `hdist` and `hclen` are at least 257, 1 and 4.
1902
+ o = this.putBits(
1903
+ out,
1904
+ o,
1905
+ ((hlit & 511) - 257) | (((hdist & 63) - 1) << 5) | (((hclen & 31) - 4) << 10),
1906
+ toI32(14)
1907
+ )
1579
1908
  for (let i: i32 = 0; i < hclen; i += 1) {
1580
- o = this.putBits(out, o, this.clLens[deflateClOrder(i)], toI32(3))
1909
+ const k: i32 = deflateClOrder(i)
1910
+ if (k < 0 || k >= 19) {
1911
+ return -1
1912
+ }
1913
+ o = this.putBits(out, o, cl[k], toI32(3))
1581
1914
  }
1582
1915
  const rle: i32[] = this.rle
1583
- const n: i32 = this.rleCount
1584
- for (let i: i32 = 0; i < n && i < toI32(rle.length); i += 1) {
1916
+ const runs: i32 = this.rleCount
1917
+ for (let i: i32 = 0; i < runs && i < toI32(rle.length); i += 1) {
1585
1918
  const e: i32 = rle[i]
1586
1919
  const sym: i32 = e & 255
1587
1920
  if (sym < 0 || sym >= 19) {
1588
- panic("Deflater.writeBlock: a code-length symbol outside 0 to 18")
1921
+ return -1
1589
1922
  }
1590
- o = this.putBits(out, o, this.clCodes[sym], this.clLens[sym])
1923
+ o = this.putBits(out, o, cc[sym], cl[sym])
1591
1924
  if (sym === 16) {
1592
1925
  o = this.putBits(out, o, e >> 8, toI32(2))
1593
1926
  } else if (sym === 17) {
@@ -1612,8 +1945,9 @@ export class Deflater {
1612
1945
 
1613
1946
  /**
1614
1947
  * Writes the block's symbols and its end-of-block code under the given
1615
- * code into `out` at `op`; answers the new position. The room was checked
1616
- * by the block's exact size.
1948
+ * code into `out` at `op`; answers the new position, or -1 when a table is
1949
+ * not its size, which the constructor rules out. The room was checked by
1950
+ * the block's exact size.
1617
1951
  */
1618
1952
  private writeSymbols(lc: i32[], ll: i32[], dc: i32[], dl: i32[], out: u8[], op: i32): i32 {
1619
1953
  const tokens: i32[] = this.tokens
@@ -1637,50 +1971,59 @@ export class Deflater {
1637
1971
  toI32(dbase.length) < 30 ||
1638
1972
  toI32(dextra.length) < 30
1639
1973
  ) {
1640
- panic("Deflater.writeSymbols: a table is not its size")
1974
+ return -1
1641
1975
  }
1642
1976
  let bb: u64 = this.bitBuf
1643
- let bc: i32 = this.bitCount
1977
+ let bc: u32 = this.bitCount
1644
1978
  let o: i32 = op
1645
1979
  for (let i: i32 = 0; i < n; i += 1) {
1646
1980
  const t: i32 = uncheckedGet(tokens, i)
1647
1981
  if (t < 256) {
1648
1982
  bb = bb | (toU64(toU32(uncheckedGet(lc, t))) << toU64(bc))
1649
- bc += uncheckedGet(ll, t)
1983
+ bc += toU32(uncheckedGet(ll, t))
1650
1984
  } else {
1651
1985
  const len3: i32 = (t & 511) - 256
1652
1986
  const dist: i32 = t >> 9
1653
1987
  const s: i32 = uncheckedGet(lsym, len3)
1654
- bb = bb | (toU64(toU32(uncheckedGet(lc, 257 + s))) << toU64(bc))
1655
- bc += uncheckedGet(ll, 257 + s)
1656
- bb = bb | (toU64(toU32(len3 + 3 - uncheckedGet(lbase, s))) << toU64(bc))
1657
- bc += uncheckedGet(lextra, s)
1658
- if (bc >= 32) {
1659
- deflateRoom(out, o, 4)
1660
- uncheckedSet(out, o, toU8(bb))
1661
- uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1662
- uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
1663
- uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
1988
+ // Cannot wrap: a length symbol is under 29. The extra bits' values
1989
+ // are worked in u32, which gives the same bits as i32 would.
1990
+ const ls: i32 = toI32(toU32(257) + toU32(s))
1991
+ bb = bb | (toU64(toU32(uncheckedGet(lc, ls))) << toU64(bc))
1992
+ bc += toU32(uncheckedGet(ll, ls))
1993
+ bb = bb | (toU64(toU32(len3) + toU32(3) - toU32(uncheckedGet(lbase, s))) << toU64(bc))
1994
+ bc += toU32(uncheckedGet(lextra, s))
1995
+ if (bc >= toU32(32)) {
1996
+ if (o >= 0 && o <= toI32(out.length) - 4) {
1997
+ uncheckedSet(out, o, toU8(bb))
1998
+ uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1999
+ uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
2000
+ uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
2001
+ o += 4
2002
+ } else {
2003
+ this.overrun = true
2004
+ }
1664
2005
  bb = bb >> toU64(32)
1665
- bc -= 32
1666
- o += 4
2006
+ bc -= toU32(32)
1667
2007
  }
1668
2008
  const d: i32 =
1669
2009
  dist <= 256 ? uncheckedGet(dsym, dist - 1) : uncheckedGet(dsym, ((dist - 1) >> 7) + 256)
1670
2010
  bb = bb | (toU64(toU32(uncheckedGet(dc, d))) << toU64(bc))
1671
- bc += uncheckedGet(dl, d)
1672
- bb = bb | (toU64(toU32(dist - uncheckedGet(dbase, d))) << toU64(bc))
1673
- bc += uncheckedGet(dextra, d)
2011
+ bc += toU32(uncheckedGet(dl, d))
2012
+ bb = bb | (toU64(toU32(dist) - toU32(uncheckedGet(dbase, d))) << toU64(bc))
2013
+ bc += toU32(uncheckedGet(dextra, d))
1674
2014
  }
1675
- if (bc >= 32) {
1676
- deflateRoom(out, o, 4)
1677
- uncheckedSet(out, o, toU8(bb))
1678
- uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1679
- uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
1680
- uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
2015
+ if (bc >= toU32(32)) {
2016
+ if (o >= 0 && o <= toI32(out.length) - 4) {
2017
+ uncheckedSet(out, o, toU8(bb))
2018
+ uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
2019
+ uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
2020
+ uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
2021
+ o += 4
2022
+ } else {
2023
+ this.overrun = true
2024
+ }
1681
2025
  bb = bb >> toU64(32)
1682
- bc -= 32
1683
- o += 4
2026
+ bc -= toU32(32)
1684
2027
  }
1685
2028
  }
1686
2029
  this.bitBuf = bb
@@ -1693,16 +2036,20 @@ export class Deflater {
1693
2036
  * The most bytes `FixedDeflater.compress` writes for `n` bytes of input: nine
1694
2037
  * bits a byte, the block's header and end code, and the eight bytes of slack
1695
2038
  * its word-wide bit writer stores past the last whole byte. A negative `n`
1696
- * answers the bound of 0.
2039
+ * answers the bound of 0, and an `n` past 1,908,874,339, the largest whose
2040
+ * bound fits, answers -1: its bound would pass 2^31 - 1.
1697
2041
  *
1698
2042
  * @param n The length of the input, in bytes.
1699
2043
  * @returns A size in bytes, not a position: a `room` of this many always
1700
- * holds the block.
2044
+ * holds the block; or -1 for an `n` past 1,908,874,339.
1701
2045
  */
1702
2046
  export const fixedDeflateBound = (n: i32): i32 => {
1703
2047
  if (n < 0) {
1704
2048
  return 16
1705
2049
  }
2050
+ if (n > 1908874339) {
2051
+ return -1
2052
+ }
1706
2053
  return n + (n >> 3) + 16
1707
2054
  }
1708
2055
 
@@ -1730,7 +2077,7 @@ export class FixedDeflater {
1730
2077
 
1731
2078
  /** The tables, once. */
1732
2079
  constructor() {
1733
- this.head = new Array<i32>(1 << FIXED_HASH_BITS)
2080
+ this.head = new Array<i32>(FIXED_HASH_SIZE)
1734
2081
  this.literal = new Array<i32>(256)
1735
2082
  this.length = new Array<i32>(256)
1736
2083
  this.distSymbol = new Array<i32>(512)
@@ -1738,24 +2085,38 @@ export class FixedDeflater {
1738
2085
  this.distBase = new Array<i32>(30)
1739
2086
  this.distExtra = new Array<i32>(30)
1740
2087
  const lens: i32[] = new Array<i32>(288)
1741
- const codes: i32[] = new Array<i32>(288)
1742
- const count: i32[] = new Array<i32>(16)
1743
- const next: i32[] = new Array<i32>(16)
1744
2088
  for (let s: i32 = 0; s < 288; s += 1) {
1745
2089
  lens[s] = deflateFixedLitLength(s)
1746
2090
  }
1747
- deflateCanonical(lens, 288, codes, count, next)
1748
2091
  for (let b: i32 = 0; b < 256; b += 1) {
1749
- this.literal[b] = codes[b] | (lens[b] << 16)
2092
+ this.literal[b] = deflateFixedLitCode(b) | (lens[b] << 16)
1750
2093
  }
1751
2094
  for (let s: i32 = 0; s < 29; s += 1) {
1752
2095
  const base: i32 = deflateLengthBase(s)
1753
2096
  const extra: i32 = deflateLengthExtra(s)
1754
2097
  // Symbol 27 stops short of 258, which has symbol 28 to itself.
1755
- const top: i32 = s === 28 ? 259 : deflateLengthBase(s + 1)
1756
- for (let l: i32 = base; l < top && l >= 3 && l <= 258; l += 1) {
1757
- const n: i32 = lens[257 + s]
1758
- this.length[l - 3] = codes[257 + s] | ((l - base) << n) | ((n + extra) << 16)
2098
+ let top: i32 = 259
2099
+ if (s < 28) {
2100
+ const next: i32 = s + 1
2101
+ top = deflateLengthBase(next)
2102
+ }
2103
+ const n: i32 = deflateFixedLitLength(257 + s)
2104
+ // The bounds on `base`, `n` and `extra` hold for every symbol; they
2105
+ // let the prover see the entry's sums fit.
2106
+ for (
2107
+ let l: i32 = base;
2108
+ l < top &&
2109
+ l >= 3 &&
2110
+ l <= 258 &&
2111
+ base >= 3 &&
2112
+ base <= 258 &&
2113
+ n >= 0 &&
2114
+ n <= 9 &&
2115
+ extra >= 0 &&
2116
+ extra <= 5;
2117
+ l += 1
2118
+ ) {
2119
+ this.length[l - 3] = deflateFixedLitCode(257 + s) | ((l - base) << n) | ((n + extra) << 16)
1759
2120
  }
1760
2121
  }
1761
2122
  for (let d: i32 = 0; d < 30; d += 1) {
@@ -1766,8 +2127,11 @@ export class FixedDeflater {
1766
2127
  // Distances 1 to 256 directly; above, by (distance - 1) >> 7 from 256 on.
1767
2128
  for (let d: i32 = 0; d < 30; d += 1) {
1768
2129
  const lo: i32 = this.distBase[d]
1769
- const hi: i32 = d === 29 ? 32769 : this.distBase[d + 1]
1770
- for (let dist: i32 = lo; dist < hi; dist += 1) {
2130
+ let hi: i32 = 32769
2131
+ if (d < 29) {
2132
+ hi = this.distBase[d + 1]
2133
+ }
2134
+ for (let dist: i32 = lo; dist < hi && dist >= 1 && dist <= 32768; dist += 1) {
1771
2135
  if (dist <= 256) {
1772
2136
  this.distSymbol[dist - 1] = d
1773
2137
  } else {
@@ -1786,7 +2150,9 @@ export class FixedDeflater {
1786
2150
  * soon as it would need more than `room` bytes: a caller that only wants
1787
2151
  * the output when it is smaller passes the most it will take, and an input
1788
2152
  * that does not compress is abandoned part way. `fixedDeflateBound(len)`
1789
- * always fits. A window outside its array panics. Allocates nothing.
2153
+ * always fits. A window outside its array panics. Answers
2154
+ * `DEFLATE_NO_ROOM` too, writing nothing, when a table is not its size,
2155
+ * which the constructor rules out. Allocates nothing.
1790
2156
  *
1791
2157
  * @param src The array that holds the data to compress.
1792
2158
  * @param off Where in `src` the data starts.
@@ -1819,7 +2185,7 @@ export class FixedDeflater {
1819
2185
  toI32(dbase.length) !== 30 ||
1820
2186
  toI32(dextra.length) !== 30
1821
2187
  ) {
1822
- panic("FixedDeflater.compress: a table is not its size")
2188
+ return DEFLATE_NO_ROOM
1823
2189
  }
1824
2190
  // A table about the input's size: clearing it is most of a short call's
1825
2191
  // fixed cost, and a larger one finds no more matches.
@@ -1829,12 +2195,15 @@ export class FixedDeflater {
1829
2195
  }
1830
2196
  head.fill(0, 0, 1 << bits)
1831
2197
  const shift: u32 = toU32(32 - bits)
1832
- const end: i32 = off + len
2198
+ // Cannot wrap: `deflateWindow` has checked that both windows lie inside
2199
+ // their arrays, so every position below is between 0 and 2^31 - 1.
2200
+ const end: i32 = toI32(toU32(off) + toU32(len))
2201
+ const outEnd: i32 = toI32(toU32(at) + toU32(room))
1833
2202
  // Matches start where eight bytes can be read; the last few are literals.
1834
- const last: i32 = end - 8
2203
+ const last: i32 = toI32(toU32(end) - toU32(8))
1835
2204
  // A flush writes four bytes of the final output, so one that would pass
1836
2205
  // the room's end means the whole cannot fit.
1837
- const oe: i32 = at + room - 4
2206
+ const oe: i32 = toI32(toU32(outEnd) - toU32(4))
1838
2207
  // BFINAL = 1, BTYPE = 01.
1839
2208
  let bb: u64 = toU64(3)
1840
2209
  let bc: i32 = 3
@@ -1847,79 +2216,96 @@ export class FixedDeflater {
1847
2216
  const pi: integer<0, 2147483639> = p
1848
2217
  const w: u64 = deflateLoad64(src, pi)
1849
2218
  const h: i32 = toI32((toU32(w) * toU32(DEFLATE_HASH_MUL)) >>> shift)
1850
- const c: i32 = uncheckedGet(head, h) - 1 + off
1851
- uncheckedSet(head, h, p - off + 1)
1852
- dist = p - c
2219
+ // Cannot wrap: the table holds 0 or `q - off + 1` for an earlier
2220
+ // position `q`, so `c` lies in [off - 1, p).
2221
+ const c: i32 = toI32(toU32(uncheckedGet(head, h)) - toU32(1) + toU32(off))
2222
+ uncheckedSet(head, h, toI32(toU32(p) - toU32(off) + toU32(1)))
2223
+ dist = toI32(toU32(p) - toU32(c))
1853
2224
  if (c >= off && c >= 0 && c <= 2147483639 && dist <= FIXED_WINDOW) {
1854
2225
  const ci: integer<0, 2147483639> = c
1855
2226
  const x: u64 = deflateLoad64(src, ci) ^ w
1856
2227
  if (toU32(x) === toU32(0)) {
1857
- const max: i32 = end - p < DEFLATE_MAX_MATCH ? end - p : DEFLATE_MAX_MATCH
2228
+ // Cannot wrap: `p` is at most `end - 8`, so `max` is at least 8;
2229
+ // a match length is at most 258.
2230
+ const left: i32 = toI32(toU32(end) - toU32(p))
2231
+ const max: i32 = left < DEFLATE_MAX_MATCH ? left : DEFLATE_MAX_MATCH
1858
2232
  matched =
1859
2233
  x !== toU64(0)
1860
2234
  ? deflateCtz64(x) >> 3
1861
- : toI32(8) + deflateMatchLength(src, c + 8, p + 8, max - 8)
2235
+ : toI32(toU32(8) + toU32(deflateMatchLength(src, c + 8, p + 8, toI32(toU32(max) - toU32(8)))))
1862
2236
  }
1863
2237
  }
1864
2238
  }
1865
2239
  if (matched === 0) {
1866
2240
  const lc: i32 = uncheckedGet(literal, toI32(uncheckedGet(src, p)))
1867
2241
  bb = bb | (toU64(toU32(lc & 0xffff)) << toU64(bc))
1868
- bc += lc >> 16
2242
+ // Cannot wrap: `bc` is under 32 between flushes and a code is at
2243
+ // most 9 bits.
2244
+ bc = toI32(toU32(bc) + toU32(lc >> 16))
1869
2245
  p += 1
1870
2246
  } else {
1871
- const lc: i32 = uncheckedGet(length, matched - 3)
2247
+ // Cannot wrap: the first four bytes agree, so a match is at least 4.
2248
+ const lc: i32 = uncheckedGet(length, toI32(toU32(matched) - toU32(3)))
1872
2249
  bb = bb | (toU64(toU32(lc & 0xffff)) << toU64(bc))
1873
- bc += lc >> 16
2250
+ bc = toI32(toU32(bc) + toU32(lc >> 16))
1874
2251
  if (bc >= 32) {
1875
2252
  if (o > oe) {
1876
2253
  return DEFLATE_NO_ROOM
1877
2254
  }
1878
2255
  uncheckedSet(out, o, toU8(bb))
1879
- uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1880
- uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
1881
- uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
2256
+ // Cannot wrap: `o` is at most `outEnd - 4`.
2257
+ uncheckedSet(out, toI32(toU32(o) + toU32(1)), toU8(bb >> toU64(8)))
2258
+ uncheckedSet(out, toI32(toU32(o) + toU32(2)), toU8(bb >> toU64(16)))
2259
+ uncheckedSet(out, toI32(toU32(o) + toU32(3)), toU8(bb >> toU64(24)))
1882
2260
  bb = bb >> toU64(32)
1883
2261
  bc -= 32
1884
- o += 4
2262
+ o = toI32(toU32(o) + toU32(4))
1885
2263
  }
1886
- const d: i32 =
1887
- dist <= 256 ? uncheckedGet(dsym, dist - 1) : uncheckedGet(dsym, ((dist - 1) >> 7) + 256)
1888
- bb = bb | (toU64(toU32(uncheckedGet(dcode, d) | ((dist - uncheckedGet(dbase, d)) << 5))) << toU64(bc))
1889
- bc += 5 + uncheckedGet(dextra, d)
2264
+ // Cannot wrap: a distance is 1 to the window and at least its
2265
+ // base, a distance code with its extra bits is at most 18 bits,
2266
+ // `bc` is under 32 here, and the match ends by `end`.
2267
+ const d1: i32 = toI32(toU32(dist) - toU32(1))
2268
+ const d: i32 = dist <= 256 ? uncheckedGet(dsym, d1) : uncheckedGet(dsym, (d1 >> 7) + 256)
2269
+ const dx: i32 = toI32(toU32(dist) - toU32(uncheckedGet(dbase, d)))
2270
+ bb = bb | (toU64(toU32(uncheckedGet(dcode, d) | (dx << 5))) << toU64(bc))
2271
+ bc = toI32(toU32(bc) + toU32(5) + toU32(uncheckedGet(dextra, d)))
1890
2272
  // One position near the match's end goes into the table, for the
1891
2273
  // next repeat of what follows it; the rest are skipped.
1892
- const q: i32 = p + matched - 2
2274
+ const q: i32 = toI32(toU32(p) + toU32(matched) - toU32(2))
1893
2275
  if (q >= 0 && q <= last && q <= 2147483639) {
1894
2276
  const qi: integer<0, 2147483639> = q
1895
2277
  const hq: i32 = toI32((deflateLoad32(src, qi) * toU32(DEFLATE_HASH_MUL)) >>> shift)
1896
- uncheckedSet(head, hq, q - off + 1)
2278
+ uncheckedSet(head, hq, toI32(toU32(q) - toU32(off) + toU32(1)))
1897
2279
  }
1898
- p += matched
2280
+ p = toI32(toU32(p) + toU32(matched))
1899
2281
  }
1900
2282
  if (bc >= 32) {
1901
2283
  if (o > oe) {
1902
2284
  return DEFLATE_NO_ROOM
1903
2285
  }
1904
2286
  uncheckedSet(out, o, toU8(bb))
1905
- uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1906
- uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
1907
- uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
2287
+ // Cannot wrap: `o` is at most `outEnd - 4`.
2288
+ uncheckedSet(out, toI32(toU32(o) + toU32(1)), toU8(bb >> toU64(8)))
2289
+ uncheckedSet(out, toI32(toU32(o) + toU32(2)), toU8(bb >> toU64(16)))
2290
+ uncheckedSet(out, toI32(toU32(o) + toU32(3)), toU8(bb >> toU64(24)))
1908
2291
  bb = bb >> toU64(32)
1909
2292
  bc -= 32
1910
- o += 4
2293
+ o = toI32(toU32(o) + toU32(4))
1911
2294
  }
1912
2295
  }
1913
2296
  // The end-of-block code, 256: seven zero bits.
1914
- bc += 7
2297
+ // The mask keeps every bit (`bc` is under 32 after the last flush), and
2298
+ // tells the bounds prover so.
2299
+ bc = (bc & 31) + 7
1915
2300
  const bytes: i32 = (bc + 7) >> 3
1916
- if (o > at + room - bytes) {
2301
+ // Cannot wrap: `bytes` is at most 5, and `o` at most `outEnd - bytes`.
2302
+ if (o > toI32(toU32(outEnd) - toU32(bytes))) {
1917
2303
  return DEFLATE_NO_ROOM
1918
2304
  }
1919
2305
  for (let i: i32 = 0; i < bytes; i += 1) {
1920
- uncheckedSet(out, o + i, toU8(bb >> toU64(8 * i)))
2306
+ uncheckedSet(out, toI32(toU32(o) + toU32(i)), toU8(bb >> toU64(8 * i)))
1921
2307
  }
1922
- return o + bytes
2308
+ return toI32(toU32(o) + toU32(bytes))
1923
2309
  }
1924
2310
  }
1925
2311
 
@@ -1950,33 +2336,39 @@ export class InflateTable {
1950
2336
  * @param bits How many bits of the next code the main table indexes at
1951
2337
  * once; a longer code goes through a subtable.
1952
2338
  * @param symbols The size of the alphabet the table decodes, such as 288
1953
- * for literal/length codes or 32 for distances.
2339
+ * for literal/length codes or 32 for distances. Only its low 16 bits are
2340
+ * read.
1954
2341
  * @param capacity How many entries to allocate for the main table and
1955
- * all its subtables; `Inflater` passes zlib's `enough` figures.
2342
+ * all its subtables; `Inflater` passes zlib's `enough` figures. Only its
2343
+ * low 16 bits are read.
1956
2344
  */
1957
2345
  constructor(bits: i32, symbols: i32, capacity: i32) {
1958
2346
  this.bits = bits
1959
- this.entries = new Array<i32>(capacity)
2347
+ // Every figure `Inflater` passes is under 65536, so `toU16` keeps every
2348
+ // bit; a u16 length can never be negative, so it needs no check.
2349
+ this.entries = new Array<i32>(toU16(capacity))
1960
2350
  this.count = new Array<i32>(16)
1961
- this.symbols = new Array<i32>(symbols)
2351
+ this.symbols = new Array<i32>(toU16(symbols))
1962
2352
  }
1963
2353
  }
1964
2354
 
1965
2355
  /**
1966
2356
  * Copies `entries[0 .. end)` to `entries[end .. 2 * end)`: a table for codes
1967
2357
  * one bit longer, each shorter code repeated under both values of the new
1968
- * bit. Panics unless `2 * end` is within the table.
2358
+ * bit. Answers false, copying nothing, unless `2 * end` is within the table.
1969
2359
  */
1970
- const inflateDouble = (entries: i32[], end: i32): void => {
2360
+ const inflateDouble = (entries: i32[], end: i32): boolean => {
1971
2361
  if (end < 0 || end > toI32(entries.length) - end) {
1972
- panic("Inflater.build: a table doubled past its length")
2362
+ return false
1973
2363
  }
1974
2364
  // A counter below a bound needs no overflow check, and the loop without
1975
2365
  // one is a vector copy.
1976
- const twice: i32 = end + end
2366
+ // Cannot wrap: `2 * end` is at most the table's length, by the test above.
2367
+ const twice: i32 = toI32(toU32(end) + toU32(end))
1977
2368
  for (let j: i32 = end; j < twice; j += 1) {
1978
2369
  uncheckedSet(entries, j, uncheckedGet(entries, j - end))
1979
2370
  }
2371
+ return true
1980
2372
  }
1981
2373
 
1982
2374
  /** The kind of table `inflateBuild` builds: what each symbol decodes to. */
@@ -2015,6 +2407,11 @@ export class Inflater {
2015
2407
  private last: boolean
2016
2408
  /** Whether the Huffman block uses the fixed code. */
2017
2409
  private fixed: boolean
2410
+ /**
2411
+ * What building the fixed code answered: 0, or the error a fixed block
2412
+ * then answers, which the fixed lengths rule out.
2413
+ */
2414
+ private fixedStatus: i32
2018
2415
  /** Bytes of the current stored block still to copy. */
2019
2416
  private storedLeft: i32
2020
2417
  /** Bits read but not consumed, low bit first, and how many. */
@@ -2064,6 +2461,7 @@ export class Inflater {
2064
2461
  this.inPos = 0
2065
2462
  this.outPos = 0
2066
2463
  this.consumed = 0
2464
+ this.fixedStatus = 0
2067
2465
  for (let s: i32 = 0; s < 288; s += 1) {
2068
2466
  this.litEntries[s] = this.entryOf(INF_TABLE_LITLEN, s, toI32(0))
2069
2467
  }
@@ -2083,9 +2481,7 @@ export class Inflater {
2083
2481
  this.lens[d] = 5
2084
2482
  }
2085
2483
  const fd: i32 = this.build(this.fixedDist, this.lens, toI32(0), toI32(32), INF_TABLE_DIST)
2086
- if (fl !== 0 || fd !== 0) {
2087
- panic("Inflater: the fixed code did not build")
2088
- }
2484
+ this.fixedStatus = fl !== 0 ? fl : fd
2089
2485
  }
2090
2486
 
2091
2487
  /**
@@ -2104,35 +2500,54 @@ export class Inflater {
2104
2500
  }
2105
2501
 
2106
2502
  /**
2107
- * The table entry for symbol `s` of a table of `kind`.
2503
+ * The table entry for symbol `s` of a table of `kind`: an invalid entry,
2504
+ * which fails the stream when it is read, for a symbol past the alphabet
2505
+ * or a base table not its size, which the constructor rules out.
2108
2506
  */
2109
2507
  private entryOf(kind: i32, s: i32, len: i32): i32 {
2110
2508
  if (kind === INF_TABLE_CODELEN) {
2111
2509
  return (s << 16) | len
2112
2510
  }
2511
+ const db: i32[] = this.distBase
2512
+ const dx: i32[] = this.distExtra
2513
+ const lb: i32[] = this.lengthBase
2514
+ const lx: i32[] = this.lengthExtra
2515
+ if (
2516
+ s < 0 ||
2517
+ toI32(db.length) < 30 ||
2518
+ toI32(dx.length) < 30 ||
2519
+ toI32(lb.length) < 29 ||
2520
+ toI32(lx.length) < 29
2521
+ ) {
2522
+ return (INF_INVALID << 8) | len
2523
+ }
2113
2524
  if (kind === INF_TABLE_DIST) {
2114
2525
  if (s >= 30) {
2115
2526
  return (INF_INVALID << 8) | len
2116
2527
  }
2117
- return (this.distBase[s] << 16) | (this.distExtra[s] << 11) | len
2528
+ return (db[s] << 16) | (dx[s] << 11) | len
2118
2529
  }
2119
2530
  if (s < 256) {
2120
2531
  return (s << 16) | (INF_LITERAL << 8) | len
2121
2532
  }
2122
- if (s === 256) {
2533
+ // `s` is 256 here exactly when it is at most 256.
2534
+ if (s <= 256) {
2123
2535
  return (INF_END << 8) | len
2124
2536
  }
2125
2537
  if (s >= 286) {
2126
2538
  return (INF_INVALID << 8) | len
2127
2539
  }
2128
- return (this.lengthBase[s - 257] << 16) | (INF_LENGTH << 8) | (this.lengthExtra[s - 257] << 11) | len
2540
+ return (lb[s - 257] << 16) | (INF_LENGTH << 8) | (lx[s - 257] << 11) | len
2129
2541
  }
2130
2542
 
2131
2543
  /**
2132
2544
  * Builds `t` from the code lengths `lens[from .. from + n)`; answers 0, or
2133
2545
  * `DEFLATE_ERR_HUFFMAN` for an over-subscribed set or an incomplete one
2134
2546
  * (an incomplete set of a single one-bit code is allowed, as RFC 1951
2135
- * §3.2.7 allows one distance code).
2547
+ * §3.2.7 allows one distance code). Answers `DEFLATE_ERR_HUFFMAN` too,
2548
+ * the table then unusable, when `lens[from .. from + n)` is outside `lens`
2549
+ * or a table is not its size, which the callers and `InflateTable` rule
2550
+ * out.
2136
2551
  */
2137
2552
  private build(t: InflateTable, lens: i32[], from: i32, n: i32, kind: i32): i32 {
2138
2553
  const count: i32[] = t.count
@@ -2141,6 +2556,8 @@ export class Inflater {
2141
2556
  const offs: i32[] = this.offsets
2142
2557
  const bits: i32 = t.bits
2143
2558
  if (
2559
+ bits < 1 ||
2560
+ bits > 15 ||
2144
2561
  from < 0 ||
2145
2562
  n < 0 ||
2146
2563
  from > toI32(lens.length) - n ||
@@ -2149,14 +2566,15 @@ export class Inflater {
2149
2566
  toI32(offs.length) < 16 ||
2150
2567
  toI32(entries.length) < 1 << bits
2151
2568
  ) {
2152
- panic("Inflater.build: a table outside its scratch")
2569
+ return DEFLATE_ERR_HUFFMAN
2153
2570
  }
2154
2571
  for (let l: i32 = 0; l < 16; l += 1) {
2155
2572
  count[l] = 0
2156
2573
  }
2157
2574
  // `lens[from .. from + n)` was checked above. A length outside 0 to 15
2158
2575
  // shows in the OR of them all, tested once after the loop.
2159
- const hi: i32 = from + n
2576
+ // Cannot wrap: `from + n` is at most `lens.length`, checked above.
2577
+ const hi: i32 = toI32(toU32(from) + toU32(n))
2160
2578
  let seen: i32 = 0
2161
2579
  for (let i: i32 = from; i < hi; i += 1) {
2162
2580
  const l: i32 = uncheckedGet(lens, i)
@@ -2170,11 +2588,15 @@ export class Inflater {
2170
2588
  count[0] = 0
2171
2589
  // The Kraft sum: over-subscribed is an error; incomplete is allowed for
2172
2590
  // one one-bit code only.
2591
+ // A count, and so `codes`, is at most `n`, which the `u16` alphabet
2592
+ // size bounds, and `left` stays at most 2^15: the masks keep every bit,
2593
+ // and tell the bounds prover so.
2173
2594
  let left: i32 = 1
2174
2595
  let codes: i32 = 0
2175
2596
  for (let l: i32 = 1; l < 16; l += 1) {
2176
- left = (left << 1) - count[l]
2177
- codes += count[l]
2597
+ const c: i32 = count[l] & 0xffff
2598
+ left = (left & 0xffff) * 2 - c
2599
+ codes = (codes & 0xffff) + c
2178
2600
  if (left < 0) {
2179
2601
  return DEFLATE_ERR_HUFFMAN
2180
2602
  }
@@ -2186,7 +2608,8 @@ export class Inflater {
2186
2608
  // symbols (length 0) go after the rest, where nothing reads them.
2187
2609
  offs[1] = 0
2188
2610
  for (let l: i32 = 1; l < 15; l += 1) {
2189
- offs[l + 1] = offs[l] + count[l]
2611
+ // At most `codes`, as above.
2612
+ offs[l + 1] = (offs[l] & 0xffff) + (count[l] & 0xffff)
2190
2613
  }
2191
2614
  offs[0] = codes
2192
2615
  for (let i: i32 = from; i < hi; i += 1) {
@@ -2197,7 +2620,9 @@ export class Inflater {
2197
2620
  }
2198
2621
  offs[l] = wrappingAdd(at, 1)
2199
2622
  }
2200
- const size: i32 = 1 << bits
2623
+ // `bits` is at most 15: the mask keeps every bit, and tells the bounds
2624
+ // prover so.
2625
+ const size: i32 = (1 << bits) & 0xffff
2201
2626
  const slow: i32 = INF_SLOW << 8
2202
2627
  let tmpl: i32[] = this.clEntries
2203
2628
  if (kind === INF_TABLE_LITLEN) {
@@ -2222,14 +2647,22 @@ export class Inflater {
2222
2647
  const codesHere: i32 = uncheckedGet(count, l)
2223
2648
  for (let c: i32 = 0; c < codesHere; c += 1) {
2224
2649
  if (k >= 0 && k < toI32(syms.length)) {
2225
- const e: i32 = tmpl[syms[k]] | l
2650
+ const s: i32 = syms[k]
2651
+ if (s < 0 || s >= toI32(tmpl.length)) {
2652
+ return DEFLATE_ERR_HUFFMAN
2653
+ }
2654
+ const e: i32 = tmpl[s] | l
2226
2655
  const step: i32 = 1 << l
2227
- for (let r: i32 = deflateReverse(code, l); r < size; r += step) {
2656
+ // Cannot wrap: `r` is under `size` and `step` at most 2^15.
2657
+ for (let r: i32 = deflateReverse(code, l); r < size; r = toI32(toU32(r) + toU32(step))) {
2228
2658
  uncheckedSet(entries, r, e)
2229
2659
  }
2230
2660
  }
2231
- k += 1
2232
- code += 1
2661
+ // `k` is under `codes`, and `code` under 2^l (the set is not
2662
+ // over-subscribed): the masks keep every bit, and tell the bounds
2663
+ // prover so.
2664
+ k = (k & 0xffff) + 1
2665
+ code = (code & 0x7fff) + 1
2233
2666
  }
2234
2667
  code = code << 1
2235
2668
  }
@@ -2249,21 +2682,29 @@ export class Inflater {
2249
2682
  while (len <= bits && len >= 0 && len < toI32(count.length)) {
2250
2683
  here = count[len]
2251
2684
  while (here > 0) {
2252
- if (k < 0 || k >= toI32(syms.length) || code < 0 || code >= end || end > size) {
2253
- panic("Inflater.build: a code outside its table")
2685
+ if (k < 0 || k >= toI32(syms.length) || code < 0 || code >= end || end < 1 || end > size) {
2686
+ return DEFLATE_ERR_HUFFMAN
2254
2687
  }
2255
- uncheckedSet(entries, code, tmpl[syms[k]] | len)
2688
+ const s: i32 = syms[k]
2689
+ if (s < 0 || s >= toI32(tmpl.length)) {
2690
+ return DEFLATE_ERR_HUFFMAN
2691
+ }
2692
+ uncheckedSet(entries, code, tmpl[s] | len)
2256
2693
  k += 1
2257
2694
  if (code === end - 1) {
2258
2695
  // The last code, all ones: the code is complete within the table.
2259
2696
  while (end < size) {
2260
- inflateDouble(entries, end)
2697
+ if (!inflateDouble(entries, end)) {
2698
+ return DEFLATE_ERR_HUFFMAN
2699
+ }
2261
2700
  end = end << 1
2262
2701
  }
2263
2702
  return 0
2264
2703
  }
2265
- const bit: i32 = toI32(1) << (31 - toI32(Math.clz32(toU32(code ^ (end - 1)))))
2266
- code = (code & (bit - 1)) | bit
2704
+ // `code` differs from `end - 1`, so the count of leading zeros is
2705
+ // under 32: the mask keeps every bit, and tells the bounds prover so.
2706
+ const bit: u32 = toU32(1) << toU32(toI32(31) - (toI32(Math.clz32(toU32(code ^ (end - 1)))) & 31))
2707
+ code = toI32((toU32(code) & (bit - toU32(1))) | bit)
2267
2708
  here -= 1
2268
2709
  }
2269
2710
  len += 1
@@ -2271,7 +2712,9 @@ export class Inflater {
2271
2712
  len += 1
2272
2713
  }
2273
2714
  while (end < size && end < 1 << len) {
2274
- inflateDouble(entries, end)
2715
+ if (!inflateDouble(entries, end)) {
2716
+ return DEFLATE_ERR_HUFFMAN
2717
+ }
2275
2718
  end = end << 1
2276
2719
  }
2277
2720
  }
@@ -2287,41 +2730,60 @@ export class Inflater {
2287
2730
  let start: i32 = 0
2288
2731
  let subEnd: i32 = size
2289
2732
  while (true) {
2290
- if (len < bits || len > 15) {
2291
- panic("Inflater.build: a code outside its table")
2733
+ if (len < bits || len < 1 || len > 15) {
2734
+ return DEFLATE_ERR_HUFFMAN
2292
2735
  }
2293
2736
  if ((code & (size - 1)) !== prefix) {
2294
2737
  prefix = code & (size - 1)
2295
2738
  start = subEnd
2296
2739
  let subBits: i32 = len - bits
2297
2740
  let used: i32 = here
2298
- while (used < 1 << subBits && bits + subBits < 15) {
2741
+ // `used` is under 2^subBits when it doubles, and `bits + subBits` at
2742
+ // most 15 after the step: the masks keep every bit, and tell the
2743
+ // bounds prover so.
2744
+ while (subBits < 14 && bits + subBits < 15 && used < 1 << subBits) {
2299
2745
  subBits += 1
2300
- used = (used << 1) + count[bits + subBits]
2746
+ const at: i32 = (bits + (subBits & 15)) & 15
2747
+ used = (used & 0xffff) * 2 + (count[at] & 0xffff)
2301
2748
  }
2302
- subEnd = start + (1 << subBits)
2749
+ // Cannot wrap: `start` is at most the table's length, a `u16`, and
2750
+ // the width at most 2^14.
2751
+ subEnd = toI32(toU32(start) + (toU32(1) << toU32(subBits)))
2303
2752
  if (subEnd > limit || prefix < 0) {
2304
- panic("Inflater.build: a subtable past the table's room")
2753
+ return DEFLATE_ERR_HUFFMAN
2305
2754
  }
2306
2755
  uncheckedSet(entries, prefix, (start << 16) | (INF_SUB << 8) | (subBits << 11) | bits)
2307
2756
  }
2308
2757
  if (k < 0 || k >= toI32(syms.length)) {
2309
- panic("Inflater.build: a code outside its table")
2758
+ return DEFLATE_ERR_HUFFMAN
2759
+ }
2760
+ const s: i32 = syms[k]
2761
+ if (s < 0 || s >= toI32(tmpl.length)) {
2762
+ return DEFLATE_ERR_HUFFMAN
2310
2763
  }
2311
- const e: i32 = tmpl[syms[k]] | (len - bits)
2764
+ const e: i32 = tmpl[s] | (len - bits)
2312
2765
  k += 1
2313
2766
  const stride: i32 = toI32(1) << (len - bits)
2314
- let i: i32 = start + (code >> bits)
2767
+ // Cannot wrap: `start` and `subEnd` are at most the table's length, a
2768
+ // `u16`, and the code past the main table's bits and the stride under
2769
+ // 2^15.
2770
+ let i: i32 = toI32(toU32(start) + (toU32(code) >> toU32(bits)))
2315
2771
  while (i < subEnd && i >= 0) {
2316
2772
  uncheckedSet(entries, i, e)
2317
- i += stride
2773
+ i = toI32(toU32(i) + toU32(stride))
2318
2774
  }
2319
- if (code === (1 << len) - 1) {
2775
+ // `len` is at most 15: the mask keeps every bit, and tells the bounds
2776
+ // prover so.
2777
+ const full: i32 = ((1 << len) & 0xffff) - 1
2778
+ if (code === full) {
2320
2779
  return 0
2321
2780
  }
2322
- const bit: i32 = toI32(1) << (31 - toI32(Math.clz32(toU32(code ^ ((toI32(1) << len) - 1)))))
2323
- code = (code & (bit - 1)) | bit
2324
- here -= 1
2781
+ // As above: `code` is not `full`, so the leading zeros are under 32.
2782
+ const bit: u32 = toU32(1) << toU32(toI32(31) - (toI32(Math.clz32(toU32(code ^ full))) & 31))
2783
+ code = toI32((toU32(code) & (bit - toU32(1))) | bit)
2784
+ // At least one code of this length remains, and at most `n`: the mask
2785
+ // keeps every bit, and tells the bounds prover so.
2786
+ here = (here & 0xffff) - 1
2325
2787
  while (here === 0 && len < 15) {
2326
2788
  const next: i32 = len + 1
2327
2789
  if (next < 0 || next >= toI32(count.length)) {
@@ -2346,13 +2808,16 @@ export class Inflater {
2346
2808
  let first: i32 = 0
2347
2809
  let index: i32 = 0
2348
2810
  let b: u64 = bb
2811
+ // A built table has at most 320 symbols and no code past 15 bits, so a
2812
+ // count is below 2^9, `index` below 2^9 and `code` and `first` below
2813
+ // 2^17: the masks keep every bit, and tell the bounds prover so.
2349
2814
  for (let l: i32 = 1; l < 16 && l < toI32(count.length); l += 1) {
2350
2815
  if (l > bc) {
2351
2816
  return -1
2352
2817
  }
2353
- code = code | toI32(b & toU64(1))
2818
+ code = (code | toI32(b & toU64(1))) & 0x1ffff
2354
2819
  b = b >> toU64(1)
2355
- const c: i32 = count[l]
2820
+ const c: i32 = count[l] & 511
2356
2821
  if (code - c < first) {
2357
2822
  const at: i32 = index + (code - first)
2358
2823
  if (at < 0 || at >= toI32(syms.length)) {
@@ -2360,22 +2825,29 @@ export class Inflater {
2360
2825
  }
2361
2826
  return this.entryOf(kind, syms[at], l)
2362
2827
  }
2363
- index += c
2364
- first = (first + c) << 1
2365
- code = code << 1
2828
+ index = (index + c) & 511
2829
+ first = ((first + c) << 1) & 0x1ffff
2830
+ code = (code << 1) & 0x1ffff
2366
2831
  }
2367
2832
  return -2
2368
2833
  }
2369
2834
 
2370
- /** Reads bytes of `src` into the bit buffer from `inPos` while it has room and `end` allows. */
2371
- private fill(src: u8[], end: i32): void {
2835
+ /**
2836
+ * Reads bytes of `src` into the bit buffer from `inPos` while it has room
2837
+ * and `end` allows. Answers false, reading nothing, when `inPos` is
2838
+ * negative or `end` past `src`, which `inflate` rules out.
2839
+ */
2840
+ private fill(src: u8[], end: i32): boolean {
2372
2841
  let bb: u64 = this.bitBuf
2373
- let bc: i32 = this.bitCount
2842
+ // The buffer holds under 64 bits: the mask keeps every bit.
2843
+ let bc: i32 = this.bitCount & 63
2374
2844
  let ip: i32 = this.inPos
2375
2845
  if (ip < 0 || end > toI32(src.length)) {
2376
- panic("Inflater.fill: a window outside its input")
2846
+ return false
2377
2847
  }
2378
- if (ip <= end - 8) {
2848
+ // `ip < end - 7` keeps `ip` at most 2^31 - 9: the third test never
2849
+ // fails, and tells the bounds prover so.
2850
+ if (end >= 8 && ip < end - 7 && ip <= 2147483639) {
2379
2851
  // A word at once, whole bytes of it counted, as the fast loop does.
2380
2852
  const at: integer<0, 2147483639> = ip
2381
2853
  bb = bb | (deflateLoad64(src, at) << toU64(bc))
@@ -2391,13 +2863,15 @@ export class Inflater {
2391
2863
  this.bitBuf = bb
2392
2864
  this.bitCount = bc
2393
2865
  this.inPos = ip
2866
+ return true
2394
2867
  }
2395
2868
 
2396
2869
  /** The low `n` bits of the bit buffer, consumed; the caller has checked that `n` are there. */
2397
2870
  private take(n: i32): i32 {
2398
2871
  const v: i32 = toI32(this.bitBuf & ((toU64(1) << toU64(n)) - toU64(1)))
2399
2872
  this.bitBuf = this.bitBuf >> toU64(n)
2400
- this.bitCount = this.bitCount - n
2873
+ // Cannot wrap: the caller has checked that `n` bits are there.
2874
+ this.bitCount = toI32(toU32(this.bitCount) - toU32(n))
2401
2875
  return v
2402
2876
  }
2403
2877
 
@@ -2407,10 +2881,10 @@ export class Inflater {
2407
2881
  * framing after the final block, begins.
2408
2882
  */
2409
2883
  private unread(): void {
2410
- const drop: i32 = this.bitCount & 7
2411
- this.bitBuf = this.bitBuf >> toU64(drop)
2412
- this.bitCount = this.bitCount - drop
2413
- this.inPos = this.inPos - (this.bitCount >> 3)
2884
+ // The buffer holds under 64 bits, read from before `inPos`: the mask
2885
+ // keeps every bit, and the whole bytes cannot take `inPos` below zero.
2886
+ const bc: i32 = this.bitCount & 63
2887
+ this.inPos = toI32(toU32(this.inPos) - toU32(bc >> 3))
2414
2888
  this.bitBuf = 0
2415
2889
  this.bitCount = 0
2416
2890
  }
@@ -2418,21 +2892,26 @@ export class Inflater {
2418
2892
  /**
2419
2893
  * Reads a dynamic block's header (§3.2.7) from the bit buffer and `src`,
2420
2894
  * and builds its tables. Answers 0, `INFLATE_NEED_INPUT` when the input ran
2421
- * out first (nothing is consumed then: the caller rewinds), or an error.
2895
+ * out first (nothing is consumed then: the caller rewinds), or an error:
2896
+ * `DEFLATE_ERR_TRUNCATED` too when `inPos` is negative or `end` past
2897
+ * `src`, and `DEFLATE_ERR_HUFFMAN` when the code-length table is not its
2898
+ * size, which `inflate` and the constructor rule out.
2422
2899
  */
2423
2900
  private readDynamic(src: u8[], end: i32): i32 {
2424
2901
  // The bit buffer in locals: the lengths are stored into an `i32[]`,
2425
2902
  // which the fields could alias, and every symbol would reload them.
2426
2903
  let bb: u64 = this.bitBuf
2427
- let bc: i32 = this.bitCount
2904
+ // The buffer holds under 64 bits: the mask keeps every bit, and tells
2905
+ // the bounds prover so.
2906
+ let bc: i32 = this.bitCount & 63
2428
2907
  let ip: i32 = this.inPos
2429
2908
  if (ip < 0 || end > toI32(src.length)) {
2430
- panic("Inflater.readDynamic: a window outside its input")
2909
+ return DEFLATE_ERR_TRUNCATED
2431
2910
  }
2432
- if (ip <= end - 8) {
2911
+ if (end >= 8 && ip < end - 7 && ip <= 2147483639) {
2433
2912
  const at: integer<0, 2147483639> = ip
2434
2913
  bb = bb | (deflateLoad64(src, at) << toU64(bc))
2435
- ip += (63 - bc) >> 3
2914
+ ip += ((63 - bc) >> 3) & 7
2436
2915
  bc = bc | 56
2437
2916
  } else {
2438
2917
  while (bc <= 56 && ip < end) {
@@ -2453,15 +2932,24 @@ export class Inflater {
2453
2932
  return DEFLATE_ERR_HUFFMAN
2454
2933
  }
2455
2934
  const cl: i32[] = this.clLens
2935
+ if (toI32(cl.length) < 19) {
2936
+ return DEFLATE_ERR_HUFFMAN
2937
+ }
2456
2938
  for (let i: i32 = 0; i < 19; i += 1) {
2457
- cl[deflateClOrder(i)] = 0
2939
+ const k: i32 = deflateClOrder(i)
2940
+ if (k < 0 || k >= 19) {
2941
+ return DEFLATE_ERR_HUFFMAN
2942
+ }
2943
+ cl[k] = 0
2458
2944
  }
2459
2945
  for (let i: i32 = 0; i < hclen; i += 1) {
2946
+ // Under 64 bits, as above.
2947
+ bc = bc & 63
2460
2948
  if (bc < 3) {
2461
- if (ip >= 0 && ip <= end - 8 && ip <= 2147483639) {
2949
+ if (ip >= 0 && end >= 8 && ip < end - 7 && ip <= 2147483639) {
2462
2950
  const at: integer<0, 2147483639> = ip
2463
2951
  bb = bb | (deflateLoad64(src, at) << toU64(bc))
2464
- ip += (63 - bc) >> 3
2952
+ ip += ((63 - bc) >> 3) & 7
2465
2953
  bc = bc | 56
2466
2954
  } else {
2467
2955
  while (bc <= 56 && ip < end) {
@@ -2474,7 +2962,11 @@ export class Inflater {
2474
2962
  return INFLATE_NEED_INPUT
2475
2963
  }
2476
2964
  }
2477
- cl[deflateClOrder(i)] = toI32(bb & toU64(7))
2965
+ const k: i32 = deflateClOrder(i)
2966
+ if (k < 0 || k >= 19) {
2967
+ return DEFLATE_ERR_HUFFMAN
2968
+ }
2969
+ cl[k] = toI32(bb & toU64(7))
2478
2970
  bb = bb >> toU64(3)
2479
2971
  bc -= 3
2480
2972
  }
@@ -2485,17 +2977,19 @@ export class Inflater {
2485
2977
  const lens: i32[] = this.lens
2486
2978
  const entries: i32[] = this.codeLengths.entries
2487
2979
  if (toI32(entries.length) < 128) {
2488
- panic("Inflater.readDynamic: the code-length table is not its size")
2980
+ return DEFLATE_ERR_HUFFMAN
2489
2981
  }
2490
2982
  const total: i32 = hlit + hdist
2491
2983
  let i: i32 = 0
2492
2984
  while (i < total) {
2985
+ // Under 64 bits, as above.
2986
+ bc = bc & 63
2493
2987
  // A code-length code is at most 7 bits and its repeat count at most 7.
2494
2988
  if (bc < 14) {
2495
- if (ip >= 0 && ip <= end - 8 && ip <= 2147483639) {
2989
+ if (ip >= 0 && end >= 8 && ip < end - 7 && ip <= 2147483639) {
2496
2990
  const at: integer<0, 2147483639> = ip
2497
2991
  bb = bb | (deflateLoad64(src, at) << toU64(bc))
2498
- ip += (63 - bc) >> 3
2992
+ ip += ((63 - bc) >> 3) & 7
2499
2993
  bc = bc | 56
2500
2994
  } else {
2501
2995
  while (bc <= 56 && ip < end) {
@@ -2515,7 +3009,8 @@ export class Inflater {
2515
3009
  return INFLATE_NEED_INPUT
2516
3010
  }
2517
3011
  bb = bb >> toU64(l)
2518
- bc -= l
3012
+ // Cannot wrap: `l` is at most `bc`, checked above.
3013
+ bc = toI32(toU32(bc) - toU32(l))
2519
3014
  const sym: i32 = e >> 16
2520
3015
  if (sym < 16) {
2521
3016
  if (i < 0 || i >= toI32(lens.length)) {
@@ -2528,7 +3023,7 @@ export class Inflater {
2528
3023
  let value: i32 = 0
2529
3024
  let x: i32 = 0
2530
3025
  if (sym === 16) {
2531
- if (i === 0) {
3026
+ if (i <= 0 || i > toI32(lens.length)) {
2532
3027
  return DEFLATE_ERR_HUFFMAN
2533
3028
  }
2534
3029
  value = lens[i - 1]
@@ -2544,10 +3039,13 @@ export class Inflater {
2544
3039
  if (bc < x) {
2545
3040
  return INFLATE_NEED_INPUT
2546
3041
  }
2547
- rep += toI32(bb & ((toU64(1) << toU64(x)) - toU64(1)))
3042
+ // At most 7 bits: the mask keeps every bit, and tells the bounds
3043
+ // prover so.
3044
+ rep += toI32(bb & ((toU64(1) << toU64(x)) - toU64(1))) & 127
2548
3045
  bb = bb >> toU64(x)
2549
- bc -= x
2550
- if (i + rep > total) {
3046
+ // Cannot wrap: `x` is at most `bc`, checked above.
3047
+ bc = toI32(toU32(bc) - toU32(x))
3048
+ if (i < 0 || rep > total - i) {
2551
3049
  return DEFLATE_ERR_HUFFMAN
2552
3050
  }
2553
3051
  for (let k: i32 = 0; k < rep && i < toI32(lens.length); k += 1) {
@@ -2556,7 +3054,7 @@ export class Inflater {
2556
3054
  }
2557
3055
  }
2558
3056
  }
2559
- if (lens[256] === 0) {
3057
+ if (toI32(lens.length) <= 256 || lens[256] === 0) {
2560
3058
  return DEFLATE_ERR_HUFFMAN
2561
3059
  }
2562
3060
  const rl: i32 = this.build(this.lit, lens, toI32(0), hlit, INF_TABLE_LITLEN)
@@ -2620,9 +3118,11 @@ export class Inflater {
2620
3118
  const r: i32 = this.step(src, inEnd, more, out, outEnd, histStart)
2621
3119
  // Whole bytes the bit buffer read ahead go back to the input, so that a
2622
3120
  // caller may drop everything before `inPos`.
2623
- const back: i32 = this.bitCount >> 3
2624
- this.inPos = this.inPos - back
2625
- this.bitCount = this.bitCount - 8 * back
3121
+ // The buffer holds under 64 bits, read from before `inPos`: the mask
3122
+ // keeps every bit, and the whole bytes cannot take `inPos` below zero.
3123
+ const bc: i32 = this.bitCount & 63
3124
+ this.inPos = toI32(toU32(this.inPos) - toU32(bc >> 3))
3125
+ this.bitCount = bc & 7
2626
3126
  this.bitBuf = this.bitBuf & ((toU64(1) << toU64(this.bitCount)) - toU64(1))
2627
3127
  return r
2628
3128
  }
@@ -2643,7 +3143,9 @@ export class Inflater {
2643
3143
  const saveBuf: u64 = this.bitBuf
2644
3144
  const saveCount: i32 = this.bitCount
2645
3145
  const savePos: i32 = this.inPos
2646
- this.fill(src, inEnd)
3146
+ if (!this.fill(src, inEnd)) {
3147
+ return DEFLATE_ERR_TRUNCATED
3148
+ }
2647
3149
  if (this.bitCount < 3) {
2648
3150
  this.bitBuf = saveBuf
2649
3151
  this.bitCount = saveCount
@@ -2654,13 +3156,18 @@ export class Inflater {
2654
3156
  const type: i32 = header >> 1
2655
3157
  if (type === 0) {
2656
3158
  this.unread()
2657
- if (inEnd - this.inPos < 4) {
3159
+ const at: i32 = this.inPos
3160
+ if (at < 0) {
3161
+ return DEFLATE_ERR_TRUNCATED
3162
+ }
3163
+ // `at <= inEnd - 4` keeps `at` at most 2^31 - 5: the third test is
3164
+ // never true, and tells the bounds prover so.
3165
+ if (inEnd < 4 || at > inEnd - 4 || at > 2147483643) {
2658
3166
  this.bitBuf = saveBuf
2659
3167
  this.bitCount = saveCount
2660
3168
  this.inPos = savePos
2661
3169
  return more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2662
3170
  }
2663
- const at: i32 = this.inPos
2664
3171
  const len: i32 = toI32(uncheckedGet(src, at)) | (toI32(uncheckedGet(src, at + 1)) << 8)
2665
3172
  const nlen: i32 = toI32(uncheckedGet(src, at + 2)) | (toI32(uncheckedGet(src, at + 3)) << 8)
2666
3173
  if ((len ^ 0xffff) !== nlen) {
@@ -2671,6 +3178,9 @@ export class Inflater {
2671
3178
  this.last = (header & 1) !== 0
2672
3179
  this.state = INF_S_STORED
2673
3180
  } else if (type === 1) {
3181
+ if (this.fixedStatus !== 0) {
3182
+ return this.fixedStatus
3183
+ }
2674
3184
  this.last = (header & 1) !== 0
2675
3185
  this.fixed = true
2676
3186
  this.state = INF_S_HUFF
@@ -2692,19 +3202,26 @@ export class Inflater {
2692
3202
  return DEFLATE_ERR_BLOCK_TYPE
2693
3203
  }
2694
3204
  } else if (s === INF_S_STORED) {
2695
- let n: i32 = this.storedLeft
2696
- const inAvail: i32 = inEnd - this.inPos
2697
- const outAvail: i32 = outEnd - this.outPos
3205
+ const ip: i32 = this.inPos
3206
+ const opos: i32 = this.outPos
3207
+ // Cannot wrap: `inflate` checked `inPos <= inEnd` and
3208
+ // `outPos <= outEnd`, and every step keeps both.
3209
+ const inAvail: i32 = toI32(toU32(inEnd) - toU32(ip))
3210
+ const outAvail: i32 = toI32(toU32(outEnd) - toU32(opos))
3211
+ // A stored length is 16 bits: the mask keeps every bit.
3212
+ const left: i32 = this.storedLeft & 0xffff
3213
+ let n: i32 = left
2698
3214
  if (n > inAvail) {
2699
3215
  n = inAvail
2700
3216
  }
2701
3217
  if (n > outAvail) {
2702
3218
  n = outAvail
2703
3219
  }
2704
- copyBytes(out, this.outPos, src, this.inPos, n)
2705
- this.inPos += n
2706
- this.outPos += n
2707
- this.storedLeft -= n
3220
+ copyBytes(out, opos, src, ip, n)
3221
+ // Cannot wrap: `n` is at most `left` and each room.
3222
+ this.inPos = toI32(toU32(ip) + toU32(n))
3223
+ this.outPos = toI32(toU32(opos) + toU32(n))
3224
+ this.storedLeft = toI32(toU32(left) - toU32(n))
2708
3225
  if (this.storedLeft > 0) {
2709
3226
  if (this.outPos === outEnd) {
2710
3227
  return INFLATE_NEED_OUTPUT
@@ -2725,6 +3242,9 @@ export class Inflater {
2725
3242
  * The Huffman block loop: decodes symbols until the end of the block
2726
3243
  * (answers 0, the state back at a block header), or until the input or
2727
3244
  * the output runs short or the stream is malformed (answers that code).
3245
+ * Answers `DEFLATE_ERR_HUFFMAN` when a table is not its size, which the
3246
+ * constructor rules out, and `DEFLATE_ERR_TRUNCATED` when `inEnd` or
3247
+ * `outEnd` is negative, which `step` rules out.
2728
3248
  */
2729
3249
  private huffman(src: u8[], inEnd: i32, more: boolean, out: u8[], outEnd: i32, histStart: i32): i32 {
2730
3250
  const lt: InflateTable = this.fixed ? this.fixedLit : this.lit
@@ -2732,10 +3252,13 @@ export class Inflater {
2732
3252
  const le: i32[] = lt.entries
2733
3253
  const de: i32[] = dt.entries
2734
3254
  if (toI32(le.length) !== INF_LIT_ENOUGH || toI32(de.length) !== INF_DIST_ENOUGH) {
2735
- panic("Inflater.huffman: a table is not its size")
3255
+ return DEFLATE_ERR_HUFFMAN
2736
3256
  }
2737
- const litMask: u64 = toU64((1 << INF_LIT_BITS) - 1)
2738
- const distMask: u64 = toU64((1 << INF_DIST_BITS) - 1)
3257
+ if (inEnd < 0 || outEnd < 0) {
3258
+ return DEFLATE_ERR_TRUNCATED
3259
+ }
3260
+ const litMask: u64 = (toU64(1) << toU64(INF_LIT_BITS)) - toU64(1)
3261
+ const distMask: u64 = (toU64(1) << toU64(INF_DIST_BITS)) - toU64(1)
2739
3262
  // The fast loop runs while eight bytes of input can be loaded and the
2740
3263
  // longest match, with sixteen bytes of copy slack, fits the output.
2741
3264
  const inFast: i32 = inEnd - 8
@@ -2795,7 +3318,12 @@ export class Inflater {
2795
3318
  // A code longer than the table: its last bits index a subtable.
2796
3319
  bb = bb >> toU64(e)
2797
3320
  bc = wrappingSub(bc, e)
2798
- e = uncheckedGet(le, (e >> 16) + toI32(bb & toU64((toI32(1) << ((e >> 11) & 15)) - 1)))
3321
+ // Cannot wrap: the subtable starts under the table's length and
3322
+ // the index into it is under 2^15.
3323
+ e = uncheckedGet(
3324
+ le,
3325
+ toI32(toU32(e >> 16) + toU32(bb & ((toU64(1) << toU64((e >> 11) & 15)) - toU64(1))))
3326
+ )
2799
3327
  } else if ((e & 0x700) === INF_SLOW << 8) {
2800
3328
  // Only a table built for an incomplete code (none at all, or
2801
3329
  // one one-bit code) has these, and every code it does have
@@ -2821,14 +3349,20 @@ export class Inflater {
2821
3349
  }
2822
3350
  } else {
2823
3351
  const lx: i32 = (e >> 11) & 15
2824
- const len: i32 = (e >> 16) + toI32(bb & ((toU64(1) << toU64(lx)) - toU64(1)))
3352
+ // Cannot wrap: a length base is at most 258 and its extra bits
3353
+ // at most 5.
3354
+ const len: i32 = toI32(toU32(e >> 16) + toU32(bb & ((toU64(1) << toU64(lx)) - toU64(1))))
2825
3355
  bb = bb >> toU64(lx)
2826
3356
  bc = wrappingSub(bc, lx)
2827
3357
  let d: i32 = uncheckedGet(de, toI32(bb & distMask))
2828
3358
  if ((d & 0x700) === INF_SUB << 8) {
2829
3359
  bb = bb >> toU64(d)
2830
3360
  bc = wrappingSub(bc, d)
2831
- d = uncheckedGet(de, (d >> 16) + toI32(bb & toU64((toI32(1) << ((d >> 11) & 15)) - 1)))
3361
+ // Cannot wrap, as for the literal/length subtable.
3362
+ d = uncheckedGet(
3363
+ de,
3364
+ toI32(toU32(d >> 16) + toU32(bb & ((toU64(1) << toU64((d >> 11) & 15)) - toU64(1))))
3365
+ )
2832
3366
  }
2833
3367
  if ((d & 0x700) !== 0) {
2834
3368
  // A slow entry, as for the literal/length table, or one of
@@ -2839,10 +3373,12 @@ export class Inflater {
2839
3373
  bb = bb >> toU64(d)
2840
3374
  bc = wrappingSub(bc, d)
2841
3375
  const dx: i32 = (d >> 11) & 15
2842
- const dist: i32 = (d >> 16) + toI32(bb & ((toU64(1) << toU64(dx)) - toU64(1)))
3376
+ // Cannot wrap: a distance base is under 2^15 and its extra
3377
+ // bits at most 13, and `op` never falls below `histStart`.
3378
+ const dist: i32 = toI32(toU32(d >> 16) + toU32(bb & ((toU64(1) << toU64(dx)) - toU64(1))))
2843
3379
  bb = bb >> toU64(dx)
2844
3380
  bc = wrappingSub(bc, dx)
2845
- if (dist > op - histStart) {
3381
+ if (dist > toI32(toU32(op) - toU32(histStart))) {
2846
3382
  status = DEFLATE_ERR_DISTANCE
2847
3383
  break
2848
3384
  }
@@ -2858,8 +3394,9 @@ export class Inflater {
2858
3394
  // always hold; they are what lets the positions enter the
2859
3395
  // copy's range without a check, and the bytes loop after is
2860
3396
  // what would finish a copy they ever stopped.
3397
+ // Cannot wrap: `dist` is at most `op - histStart`.
2861
3398
  let to: i32 = op
2862
- let from: i32 = op - dist
3399
+ let from: i32 = toI32(toU32(op) - toU32(dist))
2863
3400
  while (to < stop && to >= 0 && to <= 2147483631 && from >= 0 && from <= 2147483631) {
2864
3401
  inflateCopy16(out, to, from)
2865
3402
  to = wrappingAdd(to, 16)
@@ -2872,7 +3409,8 @@ export class Inflater {
2872
3409
  }
2873
3410
  } else if (dist === 1) {
2874
3411
  // A run of one byte, sixteen at a time, bounded as above.
2875
- const four: u64 = toU64(uncheckedGet(out, op - 1)) * toU64(0x01010101)
3412
+ // Cannot wrap: `op` is past `histStart` by at least `dist`.
3413
+ const four: u64 = toU64(uncheckedGet(out, toI32(toU32(op) - toU32(1)))) * toU64(0x01010101)
2876
3414
  const w: u64 = four | (four << toU64(32))
2877
3415
  let to: i32 = op
2878
3416
  while (to < stop && to >= 0 && to <= 2147483631) {
@@ -2884,7 +3422,8 @@ export class Inflater {
2884
3422
  to = wrappingAdd(to, 1)
2885
3423
  }
2886
3424
  } else {
2887
- let from: i32 = op - dist
3425
+ // Cannot wrap, as above.
3426
+ let from: i32 = toI32(toU32(op) - toU32(dist))
2888
3427
  let to: i32 = op
2889
3428
  while (to < stop) {
2890
3429
  uncheckedSet(out, to, uncheckedGet(out, from))
@@ -2944,7 +3483,8 @@ export class Inflater {
2944
3483
  const kind: i32 = (e >> 8) & 7
2945
3484
  const n: i32 = e & 15
2946
3485
  bb = bb >> toU64(n)
2947
- bc -= n
3486
+ // Cannot wrap: `lookup` answers only a code whose bits are all here.
3487
+ bc = toI32(toU32(bc) - toU32(n))
2948
3488
  if (kind === INF_LITERAL) {
2949
3489
  if (op >= outEnd) {
2950
3490
  bb = sBb
@@ -2964,9 +3504,11 @@ export class Inflater {
2964
3504
  status = more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2965
3505
  break
2966
3506
  }
2967
- const len: i32 = (e >> 16) + toI32(bb & ((toU64(1) << toU64(lx)) - toU64(1)))
3507
+ // Cannot wrap, as in the fast loop; `lx` is at most `bc`, checked
3508
+ // above.
3509
+ const len: i32 = toI32(toU32(e >> 16) + toU32(bb & ((toU64(1) << toU64(lx)) - toU64(1))))
2968
3510
  bb = bb >> toU64(lx)
2969
- bc -= lx
3511
+ bc = toI32(toU32(bc) - toU32(lx))
2970
3512
  const d: i32 = this.lookup(dt, INF_TABLE_DIST, de, bb, bc)
2971
3513
  if (d === -1) {
2972
3514
  bb = sBb
@@ -2989,26 +3531,30 @@ export class Inflater {
2989
3531
  break
2990
3532
  }
2991
3533
  bb = bb >> toU64(dn)
2992
- const dist: i32 = (d >> 16) + toI32(bb & ((toU64(1) << toU64(dx)) - toU64(1)))
3534
+ // Cannot wrap, as in the fast loop; `dn + dx` is at most `bc`,
3535
+ // checked above, and `op` stays within [histStart, outEnd].
3536
+ const dist: i32 = toI32(toU32(d >> 16) + toU32(bb & ((toU64(1) << toU64(dx)) - toU64(1))))
2993
3537
  bb = bb >> toU64(dx)
2994
- bc -= dn + dx
2995
- if (dist > op - histStart) {
3538
+ bc = toI32(toU32(bc) - toU32(dn + dx))
3539
+ if (dist > toI32(toU32(op) - toU32(histStart))) {
2996
3540
  status = DEFLATE_ERR_DISTANCE
2997
3541
  break
2998
3542
  }
2999
- if (len > outEnd - op) {
3543
+ if (len > toI32(toU32(outEnd) - toU32(op))) {
3000
3544
  bb = sBb
3001
3545
  bc = sBc
3002
3546
  ip = sIp
3003
3547
  status = INFLATE_NEED_OUTPUT
3004
3548
  break
3005
3549
  }
3006
- let from: i32 = op - dist
3007
- const stop: i32 = op + len
3550
+ // Cannot wrap: `dist` is at most `op - histStart`, `len` at most
3551
+ // `outEnd - op`, and `from` stays below `op`.
3552
+ let from: i32 = toI32(toU32(op) - toU32(dist))
3553
+ const stop: i32 = toI32(toU32(op) + toU32(len))
3008
3554
  while (op < stop) {
3009
3555
  uncheckedSet(out, op, uncheckedGet(out, from))
3010
3556
  op += 1
3011
- from += 1
3557
+ from = toI32(toU32(from) + toU32(1))
3012
3558
  }
3013
3559
  } else if (kind === INF_END) {
3014
3560
  this.state = INF_S_BLOCK
@@ -3030,14 +3576,25 @@ export class Inflater {
3030
3576
  * from `t` (whose entries are `entries`), with its whole code length in
3031
3577
  * the low four bits, through a subtable or the slow way as the table
3032
3578
  * says: -1 when the bits run out before the code ends, -2 when no code
3033
- * matches. A code is decoded only once all its bits are here.
3579
+ * matches, as it is too for an entry outside `entries`, which `build`
3580
+ * rules out. A code is decoded only once all its bits are here.
3034
3581
  */
3035
3582
  private lookup(t: InflateTable, kind: i32, entries: i32[], bb: u64, bc: i32): i32 {
3036
- const mask: u64 = toU64((1 << t.bits) - 1)
3037
- let e: i32 = entries[toI32(bb & mask)]
3583
+ // Codes are at most 15 bits, and a table is under 2^15 entries: the
3584
+ // masks keep every bit, and tell the bounds prover so.
3585
+ const mask: u64 = (toU64(1) << toU64(t.bits & 15)) - toU64(1)
3586
+ const i: i32 = toI32(bb & mask) & 0x7fff
3587
+ if (i >= toI32(entries.length)) {
3588
+ return -2
3589
+ }
3590
+ let e: i32 = entries[i]
3038
3591
  if (((e >> 8) & 7) === INF_SUB) {
3039
3592
  const root: i32 = e & 15
3040
- const at: i32 = (e >> 16) + toI32((bb >> toU64(root)) & toU64((toI32(1) << ((e >> 11) & 15)) - 1))
3593
+ const subMask: u64 = (toU64(1) << toU64((e >> 11) & 15)) - toU64(1)
3594
+ const at: i32 = ((e >> 16) & 0x7fff) + (toI32((bb >> toU64(root)) & subMask) & 0x7fff)
3595
+ if (at >= toI32(entries.length)) {
3596
+ return -2
3597
+ }
3041
3598
  const sub: i32 = entries[at]
3042
3599
  e = (sub & ~15) | (root + (sub & 15))
3043
3600
  } else if (((e >> 8) & 7) === INF_SLOW) {
@@ -3074,18 +3631,21 @@ export class Inflater {
3074
3631
  if (limit < 0) {
3075
3632
  panic("Inflater.decompress: a negative limit")
3076
3633
  }
3077
- const room: i32 = toI32(out.length) - at
3078
- const end: i32 = at + (limit < room ? limit : room)
3634
+ // Cannot wrap: `deflateWindow` checked `off + len` against `src` and `at`
3635
+ // against `out`, and the input is read from `off` on.
3636
+ const inEnd: i32 = toI32(toU32(off) + toU32(len))
3637
+ const room: i32 = toI32(toU32(toI32(out.length)) - toU32(at))
3638
+ const end: i32 = toI32(toU32(at) + toU32(limit < room ? limit : room))
3079
3639
  this.reset()
3080
- const r: i32 = this.inflate(src, off, off + len, false, out, at, end, at)
3081
- this.consumed = this.inPos - off
3640
+ const r: i32 = this.inflate(src, off, inEnd, false, out, at, end, at)
3641
+ this.consumed = toI32(toU32(this.inPos) - toU32(off))
3082
3642
  if (r === INFLATE_NEED_OUTPUT) {
3083
3643
  return DEFLATE_ERR_OUTPUT_LIMIT
3084
3644
  }
3085
3645
  if (r !== INFLATE_DONE) {
3086
3646
  return r
3087
3647
  }
3088
- if (this.inPos !== off + len) {
3648
+ if (this.inPos !== inEnd) {
3089
3649
  return DEFLATE_ERR_TRAILING
3090
3650
  }
3091
3651
  return this.outPos