@amritk/nish-x86_64-linux 0.23.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +50 -23
  3. package/package.json +1 -1
  4. package/runtime/browser.mjs +4 -3
  5. package/runtime/core/arrays.d.ts +0 -2
  6. package/runtime/core/arrays.mjs +0 -2
  7. package/runtime/core/host.d.ts +8 -0
  8. package/runtime/core/host.mjs +50 -2
  9. package/runtime/core/numbers.mjs +2 -3
  10. package/runtime/nish.d.ts +100 -4
  11. package/runtime/nish.h +34 -0
  12. package/runtime/nish.mjs +23 -5
  13. package/runtime/node.mjs +57 -6
  14. package/runtime/runtime-net.c +45 -4
  15. package/runtime/runtime-os.c +115 -12
  16. package/runtime/runtime-term.c +2 -2
  17. package/runtime/runtime.c +1 -1
  18. package/scripts/build.sh +13 -3
  19. package/std/README.md +44 -7
  20. package/std/cli-args.ts +1216 -0
  21. package/std/cli-flags.ts +585 -0
  22. package/std/cli.ts +308 -19
  23. package/std/compress/checksum.ts +290 -0
  24. package/std/compress/deflate.ts +2790 -0
  25. package/std/compress/gzip.ts +761 -0
  26. package/std/compress/zlib.ts +168 -0
  27. package/std/crypto/LICENSE-fiat-crypto-p384 +21 -0
  28. package/std/crypto/p256.ts +63 -1
  29. package/std/crypto/p384.ts +6044 -0
  30. package/std/crypto/pki-roots.ts +322 -0
  31. package/std/crypto/pki.ts +1207 -0
  32. package/std/crypto/rsa.ts +663 -0
  33. package/std/crypto/sha256.ts +2 -3
  34. package/std/crypto/x25519.ts +3 -4
  35. package/std/crypto/x509.ts +1054 -58
  36. package/std/net/dns-config.ts +734 -0
  37. package/std/net/dns-message.ts +517 -0
  38. package/std/net/dns-resolver.ts +1015 -0
  39. package/std/net/dns.ts +478 -0
  40. package/std/net/http-compress.ts +393 -0
  41. package/std/net/http1-client.ts +1227 -0
  42. package/std/net/http1-server.ts +101 -1
  43. package/std/net/http1.ts +9 -9
  44. package/std/net/tls/client.ts +1094 -0
  45. package/std/net/tls/codec.ts +585 -3
  46. package/std/net/tls/record-client.ts +1192 -0
  47. package/std/net/tls/verify.ts +221 -0
  48. package/std/net/tls-tcp.ts +642 -11
  49. package/std/net/tls.ts +2 -2
  50. package/std/net/url.ts +559 -4
  51. package/std/yaml-write.ts +415 -0
@@ -0,0 +1,2790 @@
1
+ /**
2
+ * `nish/compress/deflate` — DEFLATE (RFC 1951), both ways, in pure Nish: a
3
+ * compressor with levels and a decompressor that refuses malformed input with
4
+ * an error code. `nish/compress/gzip` and `nish/compress/zlib` frame it.
5
+ *
6
+ * import { Deflater, Inflater, DEFLATE_FAST, deflateBound } from "nish/compress/deflate";
7
+ *
8
+ * const deflater = new Deflater(DEFLATE_FAST); // tables, once
9
+ * const out: u8[] = new Array<u8>(deflateBound(len));
10
+ * const end: i32 = deflater.compress(src, off, len, out, 0); // -1: no room
11
+ * const inflater = new Inflater();
12
+ * const n: i32 = inflater.decompress(out, 0, end, back, 0, limit); // < 0: an error
13
+ *
14
+ * **Sans-IO and allocation-free once built.** Both objects take caller-owned
15
+ * windows, `src[off .. off + len)` in and `out[at ..)` out, and answer where
16
+ * the output ends. Everything a call needs — the match finder's hash chains,
17
+ * the block's symbols, the Huffman scratch, the decoder's tables — is
18
+ * allocated by the constructor, about 330 KB for a `Deflater` and 4 KB for an
19
+ * `Inflater`, so build one per thread and reuse it: a call allocates nothing.
20
+ * The free functions `deflateCompress` and `deflateDecompress` build one for
21
+ * a single call, for a program that compresses once.
22
+ *
23
+ * **Levels.** `DEFLATE_STORE` (0) writes stored blocks only. 1 to 3 match
24
+ * greedily on a four-byte hash with a short chain (`DEFLATE_FAST` is 1, about
25
+ * libdeflate's level 1); 4 to 9 match lazily on a three-byte hash with longer
26
+ * chains (`DEFLATE_DEFAULT` is 6). Every block is written as whichever of
27
+ * dynamic Huffman, fixed Huffman and stored is smallest, by its exact size in
28
+ * bits, so no level ever expands its input by more than `deflateBound`
29
+ * allows. A block ends after 16,383 symbols.
30
+ *
31
+ * **Decompression is bounded and total.** `Inflater.decompress` writes at most
32
+ * `limit` bytes, and a stream that would write more answers
33
+ * `DEFLATE_ERR_OUTPUT_LIMIT`, so a small input cannot expand without bound.
34
+ * Every malformed stream — a reserved block type, a stored length whose
35
+ * complement is wrong, an over-subscribed or incomplete code, a symbol no code
36
+ * defines, a distance before the start of the output, input that ends inside
37
+ * the stream — answers its own negative `DEFLATE_ERR_*` code; nothing a stream
38
+ * holds can panic. Bytes after the final block are `DEFLATE_ERR_TRAILING`
39
+ * from `decompress`; `inflate`, the resumable step under it and
40
+ * `nish/compress/gzip`'s reader, stops at the final block and says where.
41
+ *
42
+ * **What is unchecked.** The hot loops read and write through `nish:unsafe`'s
43
+ * `uncheckedGet` and `uncheckedSet`. Each such index is one of: a table
44
+ * entry, below a size the constructor allocated and the `readonly` field
45
+ * keeps; a position the caller's window was checked to contain before the
46
+ * loop; or a match candidate, which the loop checks lies in
47
+ * `[histStart, p)` before reading it. A stream's distances and lengths are
48
+ * checked against the output before any copy.
49
+ *
50
+ * Written from RFC 1951; the code-length construction follows Moffat and
51
+ * Katajainen, "In-place calculation of minimum-redundancy codes" (1995), and
52
+ * the length limit is the Kraft-sum repair of the counts per length. Not
53
+ * ported from another implementation.
54
+ */
55
+ import { uncheckedGet, uncheckedSet, wrappingAdd, wrappingSub } from "nish:unsafe"
56
+ import { copyBytes } from "nish/bytes"
57
+
58
+ /** Level 0: stored blocks only, the input copied with five bytes of framing per 65,535. */
59
+ export const DEFLATE_STORE: i32 = 0
60
+
61
+ /** Level 1: greedy matching on a short hash chain, for speed over ratio. */
62
+ export const DEFLATE_FAST: i32 = 1
63
+
64
+ /** Level 6: lazy matching, zlib's and gzip's default balance. */
65
+ export const DEFLATE_DEFAULT: i32 = 6
66
+
67
+ /** Level 9: lazy matching on the longest chains. */
68
+ export const DEFLATE_BEST: i32 = 9
69
+
70
+ /** `compress` and its framings: `out` has no room for the whole stream. */
71
+ export const DEFLATE_NO_ROOM: i32 = -1
72
+
73
+ /** The input ends inside the stream. */
74
+ export const DEFLATE_ERR_TRUNCATED: i32 = -2
75
+
76
+ /** A block of the reserved type 3 (RFC 1951 §3.2.3). */
77
+ export const DEFLATE_ERR_BLOCK_TYPE: i32 = -3
78
+
79
+ /** A stored block whose `NLEN` is not the complement of its `LEN` (§3.2.4). */
80
+ export const DEFLATE_ERR_STORED_LENGTH: i32 = -4
81
+
82
+ /**
83
+ * A dynamic block's code is unusable (§3.2.7): an over-subscribed or
84
+ * incomplete set of lengths, a repeat with nothing to repeat or past the end,
85
+ * more than 286 literal/length or 30 distance codes, or no end-of-block code.
86
+ */
87
+ export const DEFLATE_ERR_HUFFMAN: i32 = -5
88
+
89
+ /** A code the block's tables do not define, or literal/length 286 or 287, or distance 30 or 31. */
90
+ export const DEFLATE_ERR_SYMBOL: i32 = -6
91
+
92
+ /** A distance that reaches back before the start of the output. */
93
+ export const DEFLATE_ERR_DISTANCE: i32 = -7
94
+
95
+ /** The output would pass `limit` bytes, or the end of `out`. */
96
+ export const DEFLATE_ERR_OUTPUT_LIMIT: i32 = -8
97
+
98
+ /** `decompress`: bytes follow the final block. */
99
+ export const DEFLATE_ERR_TRAILING: i32 = -15
100
+
101
+ /** `Inflater.inflate`: the final block has ended; `inPos` is the first byte after it. */
102
+ export const INFLATE_DONE: i32 = 1
103
+
104
+ /** `Inflater.inflate`: every byte given was used and the stream goes on; call again with more. */
105
+ export const INFLATE_NEED_INPUT: i32 = 2
106
+
107
+ /** `Inflater.inflate`: the next symbol does not fit before `outEnd`; make room and call again. */
108
+ export const INFLATE_NEED_OUTPUT: i32 = 3
109
+
110
+ /** The farthest a match reaches back (§3.2.5), and the size of the chain table. */
111
+ const DEFLATE_WINDOW: i32 = 32768
112
+
113
+ /** The longest match (§3.2.5). */
114
+ const DEFLATE_MAX_MATCH: i32 = 258
115
+
116
+ /** The bits of a hash, and the size of the head table. */
117
+ const DEFLATE_HASH_SIZE: i32 = 32768
118
+
119
+ /** The symbols one block holds before it is written. */
120
+ const DEFLATE_BLOCK_TOKENS: i32 = 16384
121
+
122
+ /** A table position this far up is slid back down before the next block. */
123
+ const DEFLATE_REBASE: i32 = 1073741824
124
+
125
+ /** The largest stored block (§3.2.4). */
126
+ const DEFLATE_STORED_MAX: i32 = 65535
127
+
128
+ /** Huffman's multiplier for the hash (Knuth's 2^32 / phi). */
129
+ const DEFLATE_HASH_MUL: i64 = 2654435761
130
+
131
+ /** Decoder table entry kinds, in bits 8 to 10 of an entry. */
132
+ const INF_LITERAL: i32 = 0
133
+ const INF_LENGTH: i32 = 1
134
+ const INF_END: i32 = 2
135
+ const INF_SLOW: i32 = 3
136
+ const INF_INVALID: i32 = 4
137
+ /** A pointer to a subtable: its start as the value, its bits as the extra bits, the main table's bits as the length. */
138
+ const INF_SUB: i32 = 5
139
+
140
+ /**
141
+ * The bits the literal/length and distance tables index directly; a longer
142
+ * code is decoded through a subtable after the main table.
143
+ */
144
+ const INF_LIT_BITS: i32 = 11
145
+ const INF_DIST_BITS: i32 = 8
146
+
147
+ /**
148
+ * The most entries a table with its subtables can need, over every complete
149
+ * code of up to 15 bits: what zlib's `enough` program computes for 288
150
+ * symbols with 11 root bits and for 32 with 8 (`enough 288 11 15`,
151
+ * `enough 32 8 15`), the figures libdeflate sizes its tables by.
152
+ */
153
+ const INF_LIT_ENOUGH: i32 = 2342
154
+ const INF_DIST_ENOUGH: i32 = 402
155
+
156
+ /** The output the fast loop keeps in hand: the longest match and 32 bytes of copy slack. */
157
+ const INF_FAST_ROOM: i32 = 290
158
+ const INF_CL_BITS: i32 = 7
159
+
160
+ /** The decoder's resumable states. */
161
+ const INF_S_BLOCK: i32 = 0
162
+ const INF_S_STORED: i32 = 1
163
+ const INF_S_HUFF: i32 = 2
164
+ const INF_S_DONE: i32 = 3
165
+
166
+ /**
167
+ * The most bytes `Deflater.compress` writes for `n` bytes of input, at any
168
+ * level: the input stored, five bytes of framing for every 65,535 and for
169
+ * every block, and slack for the last partial byte. `n` is at most
170
+ * 2^31 - 1 less the framing; a negative `n` answers 0.
171
+ */
172
+ export const deflateBound = (n: i32): i32 => {
173
+ if (n < 0) {
174
+ return 0
175
+ }
176
+ return n + ((n >> 16) + (n >> 14) + 2) * 5 + 8
177
+ }
178
+
179
+ /**
180
+ * The most bytes a compressed body of `n` input bytes takes in any of this
181
+ * directory's formats: `deflateBound(n)` with room for gzip's 18 bytes of
182
+ * header and trailer, which covers zlib's 6.
183
+ */
184
+ export const compressBound = (n: i32): i32 => deflateBound(n) + 18
185
+
186
+ /**
187
+ * Copies `b[from .. from + 16)` to `b[to .. to + 16)` eight bytes at a time,
188
+ * each word read after the one before it is written, which is LZ77's
189
+ * meaning when `to - from` is at least 8. The caller has checked the range.
190
+ */
191
+ const inflateCopy16 = (b: u8[], to: integer<0, 2147483631>, from: integer<0, 2147483631>): void => {
192
+ deflateStore64(b, to, deflateLoad64(b, from))
193
+ deflateStore64(b, to + 8, deflateLoad64(b, from + 8))
194
+ }
195
+
196
+ /** Stores `w` twice into `b[to .. to + 16)`; the caller has checked the range. */
197
+ const inflateFill16 = (b: u8[], to: integer<0, 2147483631>, w: u64): void => {
198
+ deflateStore64(b, to, w)
199
+ deflateStore64(b, to + 8, w)
200
+ }
201
+
202
+ /** Panics unless `buf[off .. off + len)` lies inside `buf`. */
203
+ const deflateWindow = (what: string, buf: u8[], off: i32, len: i32): void => {
204
+ if (off < 0 || len < 0 || off > toI32(buf.length) - len) {
205
+ panic(`${what}: the window [${off}, ${off} + ${len}) is outside a buffer of ${toI32(buf.length)} bytes`)
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Panics unless `out[p .. p + n)` lies inside `out`: the check every store of
211
+ * the bit writer makes before its unchecked stores. A block's exact size was
212
+ * checked against the room before it was written, so this never fires.
213
+ */
214
+ const deflateRoom = (out: u8[], p: i32, n: i32): void => {
215
+ if (p < 0 || p > toI32(out.length) - n) {
216
+ panic("Deflater: a write past the room its block was sized for")
217
+ }
218
+ }
219
+
220
+ /**
221
+ * The little-endian 32-bit word at `b[p .. p + 4)`; the caller has checked the
222
+ * range. `p`'s range is what lets `p + 3` be an `add nsw`, which is what lets
223
+ * LLVM fold the four byte loads into one.
224
+ */
225
+ const deflateLoad32 = (b: u8[], p: integer<0, 2147483639>): u32 =>
226
+ toU32(uncheckedGet(b, p)) |
227
+ (toU32(uncheckedGet(b, p + 1)) << 8) |
228
+ (toU32(uncheckedGet(b, p + 2)) << 16) |
229
+ (toU32(uncheckedGet(b, p + 3)) << 24)
230
+
231
+ /**
232
+ * The little-endian 64-bit word at `b[p .. p + 8)`; the caller has checked the
233
+ * range. Eight byte loads, not two `deflateLoad32`s: LLVM folds these into
234
+ * one load, and a word built from two halves keeps `deflateStore64` from
235
+ * becoming one store.
236
+ */
237
+ const deflateLoad64 = (b: u8[], p: integer<0, 2147483639>): u64 =>
238
+ toU64(uncheckedGet(b, p)) |
239
+ (toU64(uncheckedGet(b, p + 1)) << toU64(8)) |
240
+ (toU64(uncheckedGet(b, p + 2)) << toU64(16)) |
241
+ (toU64(uncheckedGet(b, p + 3)) << toU64(24)) |
242
+ (toU64(uncheckedGet(b, p + 4)) << toU64(32)) |
243
+ (toU64(uncheckedGet(b, p + 5)) << toU64(40)) |
244
+ (toU64(uncheckedGet(b, p + 6)) << toU64(48)) |
245
+ (toU64(uncheckedGet(b, p + 7)) << toU64(56))
246
+
247
+ /** Stores `w` little-endian into `b[p .. p + 8)`; the caller has checked the range. */
248
+ const deflateStore64 = (b: u8[], p: integer<0, 2147483639>, w: u64): void => {
249
+ uncheckedSet(b, p, toU8(w))
250
+ uncheckedSet(b, p + 1, toU8(w >> toU64(8)))
251
+ uncheckedSet(b, p + 2, toU8(w >> toU64(16)))
252
+ uncheckedSet(b, p + 3, toU8(w >> toU64(24)))
253
+ uncheckedSet(b, p + 4, toU8(w >> toU64(32)))
254
+ uncheckedSet(b, p + 5, toU8(w >> toU64(40)))
255
+ uncheckedSet(b, p + 6, toU8(w >> toU64(48)))
256
+ uncheckedSet(b, p + 7, toU8(w >> toU64(56)))
257
+ }
258
+
259
+ /** The number of trailing zero bits of a nonzero `x`. */
260
+ const deflateCtz64 = (x: u64): i32 => {
261
+ // Both halves, then a select rather than a branch on which is nonzero.
262
+ const lo: u32 = toU32(x)
263
+ const hi: u32 = toU32(x >> toU64(32))
264
+ const low: i32 = toI32(31) - Math.clz32(lo & (toU32(0) - lo))
265
+ const high: i32 = toI32(63) - Math.clz32(hi & (toU32(0) - hi))
266
+ return lo !== 0 ? low : high
267
+ }
268
+
269
+ /**
270
+ * How many bytes from `a` and from `b` agree, at most `max`; `a < b` and
271
+ * `b + max` lie inside `src`, which the caller has checked.
272
+ */
273
+ const deflateMatchLength = (src: u8[], a: i32, b: i32, max: i32): i32 => {
274
+ if (a < 0 || b > 2147483639 - max) {
275
+ panic("deflateMatchLength: a match outside its input")
276
+ }
277
+ let k: i32 = 0
278
+ while (k + 8 <= max) {
279
+ const pa: i32 = a + k
280
+ const pb: i32 = b + k
281
+ if (pa >= 0 && pa <= 2147483639 && pb >= 0 && pb <= 2147483639) {
282
+ const x: u64 = deflateLoad64(src, pa) ^ deflateLoad64(src, pb)
283
+ if (x !== toU64(0)) {
284
+ return k + (deflateCtz64(x) >> 3)
285
+ }
286
+ } else {
287
+ return k
288
+ }
289
+ k += 8
290
+ }
291
+ while (k < max && uncheckedGet(src, a + k) === uncheckedGet(src, b + k)) {
292
+ k += 1
293
+ }
294
+ return k
295
+ }
296
+
297
+ /** `code`'s low `len` bits in the reverse order, as DEFLATE packs a Huffman code (§3.1.1). */
298
+ const deflateReverse = (code: i32, len: i32): i32 => {
299
+ let v: i32 = code
300
+ let r: i32 = 0
301
+ for (let i: i32 = 0; i < len; i += 1) {
302
+ r = (r << 1) | (v & 1)
303
+ v = v >> 1
304
+ }
305
+ return r
306
+ }
307
+
308
+ /** The base length of each length symbol 257 + s (§3.2.5). */
309
+ const deflateLengthBase = (s: i32): i32 => {
310
+ if (s < 8) {
311
+ return 3 + s
312
+ }
313
+ if (s === 28) {
314
+ return 258
315
+ }
316
+ return ((toI32(4) + (s & 3)) << ((s >> 2) - 1)) + 3
317
+ }
318
+
319
+ /** The extra bits of each length symbol 257 + s (§3.2.5). */
320
+ const deflateLengthExtra = (s: i32): i32 => (s < 8 || s === 28 ? 0 : (s >> 2) - 1)
321
+
322
+ /** The base distance of each distance symbol (§3.2.5). */
323
+ const deflateDistBase = (d: i32): i32 => {
324
+ if (d < 4) {
325
+ return 1 + d
326
+ }
327
+ const extra: i32 = (d >> 1) - 1
328
+ return ((toI32(2) + (d & 1)) << extra) + 1
329
+ }
330
+
331
+ /** The extra bits of each distance symbol (§3.2.5). */
332
+ const deflateDistExtra = (d: i32): i32 => (d < 4 ? 0 : (d >> 1) - 1)
333
+
334
+ /** The order the code-length code's lengths are sent in (§3.2.7). */
335
+ const deflateClOrder = (i: i32): i32 => {
336
+ switch (i) {
337
+ case 0:
338
+ return 16
339
+ case 1:
340
+ return 17
341
+ case 2:
342
+ return 18
343
+ case 3:
344
+ return 0
345
+ case 4:
346
+ return 8
347
+ case 5:
348
+ return 7
349
+ case 6:
350
+ return 9
351
+ case 7:
352
+ return 6
353
+ case 8:
354
+ return 10
355
+ case 9:
356
+ return 5
357
+ case 10:
358
+ return 11
359
+ case 11:
360
+ return 4
361
+ case 12:
362
+ return 12
363
+ case 13:
364
+ return 3
365
+ case 14:
366
+ return 13
367
+ case 15:
368
+ return 2
369
+ case 16:
370
+ return 14
371
+ case 17:
372
+ return 1
373
+ default:
374
+ return 15
375
+ }
376
+ }
377
+
378
+ /** The fixed literal/length code's length for symbol `s` (§3.2.6). */
379
+ const deflateFixedLitLength = (s: i32): i32 => {
380
+ if (s < 144) {
381
+ return 8
382
+ }
383
+ if (s < 256) {
384
+ return 9
385
+ }
386
+ if (s < 280) {
387
+ return 7
388
+ }
389
+ return 8
390
+ }
391
+
392
+ /**
393
+ * Fills `codes[0 .. n)` with the canonical code (§3.2.2) of the lengths
394
+ * `lens[0 .. n)`, each already bit-reversed for the LSB-first stream. `count`
395
+ * and `next` are scratch of at least 16 entries. A length of 0 gets code 0.
396
+ */
397
+ const deflateCanonical = (lens: i32[], n: i32, codes: i32[], count: i32[], next: i32[]): void => {
398
+ if (
399
+ n < 0 ||
400
+ n > toI32(lens.length) ||
401
+ n > toI32(codes.length) ||
402
+ toI32(count.length) < 16 ||
403
+ toI32(next.length) < 16
404
+ ) {
405
+ panic("deflateCanonical: a table smaller than its symbols")
406
+ }
407
+ for (let i: i32 = 0; i < 16; i += 1) {
408
+ count[i] = 0
409
+ }
410
+ for (let s: i32 = 0; s < n; s += 1) {
411
+ const l: i32 = lens[s]
412
+ if (l >= 0 && l < 16) {
413
+ count[l] += 1
414
+ }
415
+ }
416
+ count[0] = 0
417
+ let code: i32 = 0
418
+ for (let l: i32 = 1; l < 16; l += 1) {
419
+ code = (code + count[l - 1]) << 1
420
+ next[l] = code
421
+ }
422
+ // Each length's next code is kept bit-reversed, as it is written, and
423
+ // incremented that way: clear the ones below its highest zero and set it.
424
+ for (let l: i32 = 1; l < 16; l += 1) {
425
+ next[l] = deflateReverse(next[l], l)
426
+ }
427
+ for (let s: i32 = 0; s < n; s += 1) {
428
+ const l: i32 = lens[s]
429
+ if (l > 0 && l < 16) {
430
+ const r: i32 = next[l]
431
+ codes[s] = r
432
+ const top: i32 = (toI32(1) << l) - 1
433
+ if (r !== top) {
434
+ const bit: i32 = toI32(1) << (31 - toI32(Math.clz32(toU32(r ^ top))))
435
+ next[l] = (r & (bit - 1)) | bit
436
+ }
437
+ } else {
438
+ codes[s] = 0
439
+ }
440
+ }
441
+ }
442
+
443
+ /**
444
+ * The scratch `deflateLengths` sorts and folds in, sized for the 288
445
+ * literal/length symbols, the largest alphabet.
446
+ */
447
+ export class DeflateHuffmanScratch {
448
+ /** Symbols sorted by frequency, then by symbol. */
449
+ readonly syms: i32[]
450
+ /** Their frequencies, then (in place) the tree, then their lengths. */
451
+ readonly keys: i32[]
452
+ /** The other half of each radix pass. */
453
+ readonly tmpSyms: i32[]
454
+ readonly tmpKeys: i32[]
455
+ /** The radix pass's 256 buckets. */
456
+ readonly buckets: i32[]
457
+ /** How many codes have each length, 0 to 32. */
458
+ readonly perLength: i32[]
459
+
460
+ /** Allocates the scratch. */
461
+ constructor() {
462
+ this.syms = new Array<i32>(288)
463
+ this.keys = new Array<i32>(288)
464
+ this.tmpSyms = new Array<i32>(288)
465
+ this.tmpKeys = new Array<i32>(288)
466
+ this.buckets = new Array<i32>(256)
467
+ this.perLength = new Array<i32>(33)
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Sets `lens[0 .. n)` to code lengths of at most `limit` bits for the
473
+ * frequencies `freq[0 .. n)`: a minimum-redundancy code (Moffat and
474
+ * Katajainen's in-place construction over the symbols sorted by frequency),
475
+ * then, if a length passed `limit`, the counts per length repaired until the
476
+ * Kraft sum is exactly 1 again. A symbol of frequency 0 gets length 0. With
477
+ * fewer than two used symbols, symbols are given length 1 until two have
478
+ * one, so the code is always complete. Frequencies are below 2^16.
479
+ */
480
+ const deflateLengths = (freq: i32[], n: i32, limit: i32, lens: i32[], w: DeflateHuffmanScratch): void => {
481
+ const syms: i32[] = w.syms
482
+ const keys: i32[] = w.keys
483
+ const tsyms: i32[] = w.tmpSyms
484
+ const tkeys: i32[] = w.tmpKeys
485
+ const buckets: i32[] = w.buckets
486
+ const per: i32[] = w.perLength
487
+ if (
488
+ n < 2 ||
489
+ n > 288 ||
490
+ n > toI32(freq.length) ||
491
+ n > toI32(lens.length) ||
492
+ toI32(syms.length) < 288 ||
493
+ toI32(keys.length) < 288 ||
494
+ toI32(tsyms.length) < 288 ||
495
+ toI32(tkeys.length) < 288 ||
496
+ toI32(buckets.length) < 256 ||
497
+ toI32(per.length) < 33 ||
498
+ limit < 1 ||
499
+ limit > 15
500
+ ) {
501
+ panic("deflateLengths: an alphabet outside its scratch")
502
+ }
503
+ // The used symbols, by a two-pass radix sort on the 16-bit frequency.
504
+ let used: i32 = 0
505
+ for (let s: i32 = 0; s < n; s += 1) {
506
+ lens[s] = 0
507
+ const f: i32 = freq[s]
508
+ if (f > 0) {
509
+ uncheckedSet(tsyms, used, s)
510
+ uncheckedSet(tkeys, used, f)
511
+ used += 1
512
+ }
513
+ }
514
+ if (used < 2) {
515
+ // One code or none: every decoder wants a complete code, so give two
516
+ // symbols one bit each.
517
+ let given: i32 = 0
518
+ for (let s: i32 = 0; s < n && given < 2; s += 1) {
519
+ if (freq[s] > 0) {
520
+ lens[s] = 1
521
+ given += 1
522
+ }
523
+ }
524
+ for (let s: i32 = 0; s < n && given < 2; s += 1) {
525
+ if (lens[s] === 0) {
526
+ lens[s] = 1
527
+ given += 1
528
+ }
529
+ }
530
+ return
531
+ }
532
+ for (let pass: i32 = 0; pass < 2; pass += 1) {
533
+ const shift: i32 = pass * 8
534
+ for (let b: i32 = 0; b < 256; b += 1) {
535
+ uncheckedSet(buckets, b, 0)
536
+ }
537
+ const fromSyms: i32[] = pass === 0 ? tsyms : syms
538
+ const fromKeys: i32[] = pass === 0 ? tkeys : keys
539
+ const toSyms: i32[] = pass === 0 ? syms : tsyms
540
+ const toKeys: i32[] = pass === 0 ? keys : tkeys
541
+ for (let i: i32 = 0; i < used; i += 1) {
542
+ const b: i32 = (uncheckedGet(fromKeys, i) >> shift) & 255
543
+ uncheckedSet(buckets, b, uncheckedGet(buckets, b) + 1)
544
+ }
545
+ let sum: i32 = 0
546
+ for (let b: i32 = 0; b < 256; b += 1) {
547
+ const c: i32 = uncheckedGet(buckets, b)
548
+ uncheckedSet(buckets, b, sum)
549
+ sum += c
550
+ }
551
+ for (let i: i32 = 0; i < used; i += 1) {
552
+ const k: i32 = uncheckedGet(fromKeys, i)
553
+ const b: i32 = (k >> shift) & 255
554
+ const at: i32 = uncheckedGet(buckets, b)
555
+ uncheckedSet(buckets, b, at + 1)
556
+ uncheckedSet(toSyms, at, uncheckedGet(fromSyms, i))
557
+ uncheckedSet(toKeys, at, k)
558
+ }
559
+ }
560
+ // Two passes leave the sorted run back in `tsyms` / `tkeys`.
561
+ for (let i: i32 = 0; i < used; i += 1) {
562
+ uncheckedSet(syms, i, uncheckedGet(tsyms, i))
563
+ uncheckedSet(keys, i, uncheckedGet(tkeys, i))
564
+ }
565
+ // Moffat and Katajainen, phase 1: each internal node's weight, and each
566
+ // node's parent, in place over the ascending weights.
567
+ uncheckedSet(keys, 0, uncheckedGet(keys, 0) + uncheckedGet(keys, 1))
568
+ let root: i32 = 0
569
+ let leaf: i32 = 2
570
+ for (let next: i32 = 1; next < used - 1; next += 1) {
571
+ if (leaf >= used || uncheckedGet(keys, root) < uncheckedGet(keys, leaf)) {
572
+ uncheckedSet(keys, next, uncheckedGet(keys, root))
573
+ uncheckedSet(keys, root, next)
574
+ root += 1
575
+ } else {
576
+ uncheckedSet(keys, next, uncheckedGet(keys, leaf))
577
+ leaf += 1
578
+ }
579
+ if (leaf >= used || (root < next && uncheckedGet(keys, root) < uncheckedGet(keys, leaf))) {
580
+ uncheckedSet(keys, next, uncheckedGet(keys, next) + uncheckedGet(keys, root))
581
+ uncheckedSet(keys, root, next)
582
+ root += 1
583
+ } else {
584
+ uncheckedSet(keys, next, uncheckedGet(keys, next) + uncheckedGet(keys, leaf))
585
+ leaf += 1
586
+ }
587
+ }
588
+ // Phase 2: each internal node's depth.
589
+ uncheckedSet(keys, used - 2, 0)
590
+ for (let next: i32 = used - 3; next >= 0; next -= 1) {
591
+ uncheckedSet(keys, next, uncheckedGet(keys, uncheckedGet(keys, next)) + 1)
592
+ }
593
+ // Phase 3: how many leaves sit at each depth.
594
+ for (let l: i32 = 0; l < 33; l += 1) {
595
+ per[l] = 0
596
+ }
597
+ let avail: i32 = 1
598
+ let usedHere: i32 = 0
599
+ let depth: i32 = 0
600
+ root = used - 2
601
+ let next: i32 = used - 1
602
+ while (avail > 0) {
603
+ while (root >= 0 && uncheckedGet(keys, root) === depth) {
604
+ usedHere += 1
605
+ root -= 1
606
+ }
607
+ while (avail > usedHere) {
608
+ if (depth < 33) {
609
+ per[depth] += 1
610
+ }
611
+ next -= 1
612
+ avail -= 1
613
+ }
614
+ avail = 2 * usedHere
615
+ depth += 1
616
+ usedHere = 0
617
+ }
618
+ // The length limit: fold the deeper codes into `limit`, then lengthen
619
+ // shorter codes until the Kraft sum is exactly 2^limit again.
620
+ if (per[limit + 1] > 0 || depth > limit + 1) {
621
+ for (let l: i32 = limit + 1; l < 33; l += 1) {
622
+ per[limit] += per[l]
623
+ per[l] = 0
624
+ }
625
+ let total: i32 = 0
626
+ for (let l: i32 = limit; l > 0; l -= 1) {
627
+ total += per[l] << (limit - l)
628
+ }
629
+ while (total !== 1 << limit) {
630
+ per[limit] -= 1
631
+ for (let l: i32 = limit - 1; l > 0; l -= 1) {
632
+ if (per[l] !== 0) {
633
+ per[l] -= 1
634
+ per[l + 1] += 2
635
+ break
636
+ }
637
+ }
638
+ total -= 1
639
+ }
640
+ }
641
+ // The most frequent symbols take the shortest lengths.
642
+ let j: i32 = used
643
+ for (let l: i32 = 1; l <= limit; l += 1) {
644
+ for (let c: i32 = per[l]; c > 0; c -= 1) {
645
+ j -= 1
646
+ if (j >= 0) {
647
+ const s: i32 = uncheckedGet(syms, j)
648
+ if (s >= 0 && s < n) {
649
+ lens[s] = l
650
+ }
651
+ }
652
+ }
653
+ }
654
+ }
655
+
656
+ /**
657
+ * A DEFLATE compressor at one level: the match finder's tables, one block of
658
+ * symbols, the Huffman scratch and the bit writer, allocated once. Not shared
659
+ * between threads; reuse it for every call on one.
660
+ */
661
+ export class Deflater {
662
+ /** `head[h]`: the most recent position whose hash is `h`, plus `delta`; 0 for none. */
663
+ readonly head: i32[]
664
+ /** `prev[p & 32767]`: the position before `p` with `p`'s hash. */
665
+ readonly prev: i32[]
666
+ /** The block's symbols: a literal byte, or `dist << 9 | (256 + len - 3)`. */
667
+ readonly tokens: i32[]
668
+ /** The block's literal/length and distance frequencies. */
669
+ readonly litFreq: i32[]
670
+ readonly distFreq: i32[]
671
+ /** The dynamic code for the block. */
672
+ readonly litLens: i32[]
673
+ readonly litCodes: i32[]
674
+ readonly distLens: i32[]
675
+ readonly distCodes: i32[]
676
+ /** The code-length code, and the run-length coded lengths it codes. */
677
+ readonly clFreq: i32[]
678
+ readonly clLens: i32[]
679
+ readonly clCodes: i32[]
680
+ readonly rle: i32[]
681
+ /** The fixed code (§3.2.6). */
682
+ readonly fixedLitLens: i32[]
683
+ readonly fixedLitCodes: i32[]
684
+ readonly fixedDistLens: i32[]
685
+ readonly fixedDistCodes: i32[]
686
+ /** Length - 3 to length symbol - 257; distance to distance symbol, as `deflateDistSymbol` reads it. */
687
+ readonly lengthSymbol: i32[]
688
+ readonly distSymbol: i32[]
689
+ /** Base and extra bits of each length and distance symbol. */
690
+ readonly lengthBase: i32[]
691
+ readonly lengthExtra: i32[]
692
+ readonly distBase: i32[]
693
+ readonly distExtra: i32[]
694
+ /** Canonical-code and length-building scratch. */
695
+ readonly countScratch: i32[]
696
+ readonly nextScratch: i32[]
697
+ readonly scratch: DeflateHuffmanScratch
698
+ /** Bits written but not yet stored, low bit first, and how many. */
699
+ bitBuf: u64
700
+ bitCount: i32
701
+ /** The level, 0 to 9. */
702
+ readonly level: i32
703
+ /** Candidates tried per position. */
704
+ readonly maxChain: i32
705
+ /** A match this long is taken without looking further. */
706
+ readonly niceLength: i32
707
+ /** A match shorter than this is checked against the next position's (levels 4 to 9); 0 for greedy. */
708
+ readonly lazyLength: i32
709
+ /** The shortest match taken: 4 at levels 1 to 3, whose hash covers four bytes, else 3. */
710
+ readonly minMatch: i32
711
+ /** A table position is an index of the current input plus this. */
712
+ delta: i32
713
+ /** The next call's `delta` floor: past every position the tables hold, by a whole window. */
714
+ base: i32
715
+ /** How many of `tokens` the block holds. */
716
+ count: i32
717
+ /** How many entries of `rle` the block uses. */
718
+ rleCount: i32
719
+
720
+ /** A compressor at `level`, 0 to 9; another level panics. */
721
+ constructor(level: i32) {
722
+ if (level < 0 || level > 9) {
723
+ panic(`Deflater: level ${level} is outside 0 to 9`)
724
+ }
725
+ this.level = level
726
+ let chain: i32 = 0
727
+ let nice: i32 = 0
728
+ let lazy: i32 = 0
729
+ switch (level) {
730
+ case 1:
731
+ chain = 2
732
+ nice = 32
733
+ break
734
+ case 2:
735
+ chain = 6
736
+ nice = 64
737
+ break
738
+ case 3:
739
+ chain = 12
740
+ nice = 128
741
+ break
742
+ case 4:
743
+ chain = 12
744
+ nice = 64
745
+ lazy = 8
746
+ break
747
+ case 5:
748
+ chain = 24
749
+ nice = 128
750
+ lazy = 16
751
+ break
752
+ case 6:
753
+ chain = 48
754
+ nice = 128
755
+ lazy = 16
756
+ break
757
+ case 7:
758
+ chain = 96
759
+ nice = 258
760
+ lazy = 32
761
+ break
762
+ case 8:
763
+ chain = 256
764
+ nice = 258
765
+ lazy = 128
766
+ break
767
+ case 9:
768
+ chain = 1024
769
+ nice = 258
770
+ lazy = 258
771
+ break
772
+ default:
773
+ break
774
+ }
775
+ this.maxChain = chain
776
+ this.niceLength = nice
777
+ this.lazyLength = lazy
778
+ this.minMatch = level >= 4 ? 3 : 4
779
+ this.head = new Array<i32>(DEFLATE_HASH_SIZE)
780
+ this.prev = new Array<i32>(DEFLATE_WINDOW)
781
+ this.delta = 0
782
+ this.base = DEFLATE_WINDOW + 1
783
+ this.tokens = new Array<i32>(DEFLATE_BLOCK_TOKENS)
784
+ this.count = 0
785
+ this.litFreq = new Array<i32>(288)
786
+ this.distFreq = new Array<i32>(32)
787
+ this.litLens = new Array<i32>(288)
788
+ this.litCodes = new Array<i32>(288)
789
+ this.distLens = new Array<i32>(32)
790
+ this.distCodes = new Array<i32>(32)
791
+ this.clFreq = new Array<i32>(19)
792
+ this.clLens = new Array<i32>(19)
793
+ this.clCodes = new Array<i32>(19)
794
+ this.rle = new Array<i32>(320)
795
+ this.rleCount = 0
796
+ this.fixedLitLens = new Array<i32>(288)
797
+ this.fixedLitCodes = new Array<i32>(288)
798
+ this.fixedDistLens = new Array<i32>(32)
799
+ this.fixedDistCodes = new Array<i32>(32)
800
+ this.lengthSymbol = new Array<i32>(256)
801
+ this.distSymbol = new Array<i32>(512)
802
+ this.lengthBase = new Array<i32>(29)
803
+ this.lengthExtra = new Array<i32>(29)
804
+ this.distBase = new Array<i32>(30)
805
+ this.distExtra = new Array<i32>(30)
806
+ this.countScratch = new Array<i32>(16)
807
+ this.nextScratch = new Array<i32>(16)
808
+ this.scratch = new DeflateHuffmanScratch()
809
+ this.bitBuf = 0
810
+ this.bitCount = 0
811
+ for (let s: i32 = 0; s < 29; s += 1) {
812
+ this.lengthBase[s] = deflateLengthBase(s)
813
+ this.lengthExtra[s] = deflateLengthExtra(s)
814
+ }
815
+ for (let s: i32 = 0; s < 29; s += 1) {
816
+ const lo: i32 = this.lengthBase[s] - 3
817
+ // Symbol 27 stops short of 258, which has symbol 28 to itself.
818
+ let hi: i32 = 256
819
+ if (s < 27) {
820
+ hi = this.lengthBase[s + 1] - 3
821
+ } else if (s === 27) {
822
+ hi = 255
823
+ }
824
+ for (let l: i32 = lo; l < hi && l >= 0 && l < 256; l += 1) {
825
+ this.lengthSymbol[l] = s
826
+ }
827
+ }
828
+ for (let d: i32 = 0; d < 30; d += 1) {
829
+ this.distBase[d] = deflateDistBase(d)
830
+ this.distExtra[d] = deflateDistExtra(d)
831
+ }
832
+ // Distances 1 to 256 directly; above, by (distance - 1) >> 7 from 256 on.
833
+ for (let d: i32 = 0; d < 30; d += 1) {
834
+ const lo: i32 = this.distBase[d]
835
+ const hi: i32 = d === 29 ? 32769 : this.distBase[d + 1]
836
+ for (let dist: i32 = lo; dist < hi; dist += 1) {
837
+ if (dist <= 256) {
838
+ this.distSymbol[dist - 1] = d
839
+ } else {
840
+ const at: i32 = ((dist - 1) >> 7) + 256
841
+ if (at < 512) {
842
+ this.distSymbol[at] = d
843
+ }
844
+ }
845
+ }
846
+ }
847
+ for (let s: i32 = 0; s < 288; s += 1) {
848
+ this.fixedLitLens[s] = deflateFixedLitLength(s)
849
+ }
850
+ for (let d: i32 = 0; d < 32; d += 1) {
851
+ this.fixedDistLens[d] = 5
852
+ }
853
+ deflateCanonical(this.fixedLitLens, 288, this.fixedLitCodes, this.countScratch, this.nextScratch)
854
+ deflateCanonical(this.fixedDistLens, 32, this.fixedDistCodes, this.countScratch, this.nextScratch)
855
+ }
856
+
857
+ /**
858
+ * Forgets the history: the next call starts a stream from nothing. Only a
859
+ * streaming writer needs it; `compress` starts a new stream on every call.
860
+ */
861
+ reset(): void {
862
+ this.bitBuf = 0
863
+ this.bitCount = 0
864
+ }
865
+
866
+ /**
867
+ * Compresses `src[off .. off + len)` into `out` from `at` as one raw
868
+ * DEFLATE stream, and answers where it ends, or `DEFLATE_NO_ROOM` when
869
+ * `out` cannot hold it: `deflateBound(len)` bytes always can. A window
870
+ * outside its array panics. Allocates nothing.
871
+ */
872
+ compress(src: u8[], off: i32, len: i32, out: u8[], at: i32): i32 {
873
+ deflateWindow("Deflater.compress", src, off, len)
874
+ deflateWindow("Deflater.compress", out, at, 0)
875
+ this.bitBuf = 0
876
+ this.bitCount = 0
877
+ this.begin(off)
878
+ const end: i32 = this.compressRange(src, off, off + len, off, true, out, at, toI32(out.length))
879
+ this.finish(off + len)
880
+ if (end < 0) {
881
+ return DEFLATE_NO_ROOM
882
+ }
883
+ return this.flushBits(out, end, toI32(out.length))
884
+ }
885
+
886
+ /**
887
+ * Starts a stream whose history begins at index `start` of the next input:
888
+ * every position the tables hold is pushed a window behind it.
889
+ */
890
+ begin(start: i32): void {
891
+ if (this.base > DEFLATE_REBASE) {
892
+ this.head.fill(0)
893
+ this.prev.fill(0)
894
+ this.base = DEFLATE_WINDOW + 1
895
+ }
896
+ this.delta = this.base - start
897
+ }
898
+
899
+ /**
900
+ * Ends a stream whose input ended at index `end`: the next stream's
901
+ * positions start a window past every position the tables now hold.
902
+ */
903
+ finish(end: i32): void {
904
+ this.base = end + this.delta + DEFLATE_WINDOW + 1
905
+ }
906
+
907
+ /**
908
+ * Moves the tables' positions down by `shift`, as the input they index
909
+ * moves down by `shift` bytes; a position that falls below 0 is dropped.
910
+ * The streaming writer calls it when it slides its window.
911
+ */
912
+ slide(shift: i32): void {
913
+ this.delta = this.delta + shift
914
+ }
915
+
916
+ /**
917
+ * Writes the whole bytes of the bit buffer, and the last partial byte
918
+ * padded with zeros, into `out` at `op`; answers the end, or
919
+ * `DEFLATE_NO_ROOM`.
920
+ */
921
+ flushBits(out: u8[], op: i32, oe: i32): i32 {
922
+ const bytes: i32 = (this.bitCount + 7) >> 3
923
+ if (op < 0 || oe > toI32(out.length) || bytes > oe - op) {
924
+ return DEFLATE_NO_ROOM
925
+ }
926
+ let p: i32 = op
927
+ let bb: u64 = this.bitBuf
928
+ for (let i: i32 = 0; i < bytes; i += 1) {
929
+ uncheckedSet(out, p, toU8(bb & toU64(255)))
930
+ bb = bb >> toU64(8)
931
+ p += 1
932
+ }
933
+ this.bitBuf = 0
934
+ this.bitCount = 0
935
+ return p
936
+ }
937
+
938
+ /**
939
+ * Appends the low `n` bits of `v` (`n` at most 32) to the bit buffer,
940
+ * storing whole words into `out` at `op`; answers the new `op`. The caller
941
+ * has checked the room.
942
+ */
943
+ putBits(out: u8[], op: i32, v: i32, n: i32): i32 {
944
+ let bb: u64 = this.bitBuf | (toU64(toU32(v)) << toU64(this.bitCount))
945
+ let bc: i32 = this.bitCount + n
946
+ let p: i32 = op
947
+ if (bc >= 32) {
948
+ deflateRoom(out, p, 4)
949
+ uncheckedSet(out, p, toU8(bb & toU64(255)))
950
+ uncheckedSet(out, p + 1, toU8((bb >> toU64(8)) & toU64(255)))
951
+ uncheckedSet(out, p + 2, toU8((bb >> toU64(16)) & toU64(255)))
952
+ uncheckedSet(out, p + 3, toU8((bb >> toU64(24)) & toU64(255)))
953
+ bb = bb >> toU64(32)
954
+ bc -= 32
955
+ p += 4
956
+ }
957
+ this.bitBuf = bb
958
+ this.bitCount = bc
959
+ return p
960
+ }
961
+
962
+ /**
963
+ * Stores whole bytes of the bit buffer into `out` at `op` and drops the
964
+ * partial byte's padding: the byte alignment a stored block's `LEN`
965
+ * starts at. Answers the new `op`; the caller has checked the room.
966
+ */
967
+ alignBits(out: u8[], op: i32): i32 {
968
+ let p: i32 = op
969
+ let bb: u64 = this.bitBuf
970
+ let bc: i32 = this.bitCount
971
+ deflateRoom(out, p, (bc + 7) >> 3)
972
+ while (bc > 0) {
973
+ uncheckedSet(out, p, toU8(bb & toU64(255)))
974
+ bb = bb >> toU64(8)
975
+ bc -= 8
976
+ p += 1
977
+ }
978
+ this.bitBuf = 0
979
+ this.bitCount = 0
980
+ return p
981
+ }
982
+
983
+ /**
984
+ * Compresses `src[start .. end)` as blocks into `out[op .. oe)`, matching
985
+ * back as far as `histStart`; `final` marks the last block BFINAL. Answers
986
+ * the new output position, with up to 31 bits still in the bit buffer, or
987
+ * -1 when a block does not fit.
988
+ */
989
+ compressRange(
990
+ src: u8[],
991
+ start: i32,
992
+ end: i32,
993
+ histStart: i32,
994
+ final: boolean,
995
+ out: u8[],
996
+ op: i32,
997
+ oe: i32
998
+ ): i32 {
999
+ if (start < 0 || histStart < 0 || histStart > start || start > end || end > toI32(src.length)) {
1000
+ panic("Deflater.compressRange: a range outside its input")
1001
+ }
1002
+ if (op < 0 || oe > toI32(out.length) || op > oe) {
1003
+ panic("Deflater.compressRange: a range outside its output")
1004
+ }
1005
+ let p: i32 = start
1006
+ let o: i32 = op
1007
+ if (start === end) {
1008
+ if (!final) {
1009
+ return o
1010
+ }
1011
+ // An empty final block, in the fixed code: ten bits.
1012
+ if ((this.bitCount + 10 + 7) >> 3 > oe - o) {
1013
+ return -1
1014
+ }
1015
+ o = this.putBits(out, o, toI32(3), toI32(3))
1016
+ return this.putBits(out, o, this.fixedLitCodes[256], this.fixedLitLens[256])
1017
+ }
1018
+ if (this.level === 0) {
1019
+ return this.writeStored(src, start, end, final, out, o, oe)
1020
+ }
1021
+ while (p < end) {
1022
+ if (p + this.delta > DEFLATE_REBASE) {
1023
+ this.rebase(p)
1024
+ }
1025
+ const q: i32 =
1026
+ this.level >= 4
1027
+ ? this.collectLazy(src, p, end, histStart)
1028
+ : this.collectGreedy(src, p, end, histStart)
1029
+ o = this.writeBlock(src, p, q, final && q === end, out, o, oe)
1030
+ if (o < 0) {
1031
+ return -1
1032
+ }
1033
+ p = q
1034
+ }
1035
+ return o
1036
+ }
1037
+
1038
+ /**
1039
+ * Slides every table position down so that index `p` of the input is a
1040
+ * window above the floor again; a position more than a window behind `p`
1041
+ * becomes 0, which is never a candidate.
1042
+ */
1043
+ rebase(p: i32): void {
1044
+ const shift: i32 = p + this.delta - (DEFLATE_WINDOW + 1)
1045
+ const head: i32[] = this.head
1046
+ const prev: i32[] = this.prev
1047
+ for (let i: i32 = 0; i < toI32(head.length); i += 1) {
1048
+ const v: i32 = head[i] - shift
1049
+ head[i] = v > 0 ? v : 0
1050
+ }
1051
+ for (let i: i32 = 0; i < toI32(prev.length); i += 1) {
1052
+ const v: i32 = prev[i] - shift
1053
+ prev[i] = v > 0 ? v : 0
1054
+ }
1055
+ this.delta = this.delta - shift
1056
+ this.base = this.base - shift
1057
+ }
1058
+
1059
+ /**
1060
+ * The best match at `p`, after recording `p` in the chains: answers
1061
+ * `len << 16 | dist`, or 0 for none at least `minMatch` long. `p + 4 <=
1062
+ * end`, which the caller checks.
1063
+ */
1064
+ longest(src: u8[], p: i32, end: i32, histStart: i32): i32 {
1065
+ const head: i32[] = this.head
1066
+ const prev: i32[] = this.prev
1067
+ if (
1068
+ toI32(head.length) !== DEFLATE_HASH_SIZE ||
1069
+ toI32(prev.length) !== DEFLATE_WINDOW ||
1070
+ p < 0 ||
1071
+ p > end - 4 ||
1072
+ end > toI32(src.length)
1073
+ ) {
1074
+ panic("Deflater.longest: a table is not its size")
1075
+ }
1076
+ const delta: i32 = this.delta
1077
+ const minMatch: i32 = this.minMatch
1078
+ const at: integer<0, 2147483639> = p
1079
+ const word: u32 = deflateLoad32(src, at)
1080
+ const h: i32 =
1081
+ minMatch === 3
1082
+ ? toI32(((word << 8) * toU32(DEFLATE_HASH_MUL)) >>> 17)
1083
+ : toI32((word * toU32(DEFLATE_HASH_MUL)) >>> 17)
1084
+ const v: i32 = wrappingAdd(p, delta)
1085
+ let cand: i32 = uncheckedGet(head, h)
1086
+ uncheckedSet(head, h, v)
1087
+ uncheckedSet(prev, v & (DEFLATE_WINDOW - 1), cand)
1088
+ // Where a whole longest match fits, eight bytes past `p` can be read
1089
+ // whatever the match, and nothing is clamped.
1090
+ const roomy: boolean = p <= end - DEFLATE_MAX_MATCH
1091
+ const maxLen: i32 = roomy ? DEFLATE_MAX_MATCH : end - p
1092
+ let best: i32 = minMatch - 1
1093
+ let bestDist: i32 = 0
1094
+ const limit: i32 = v - DEFLATE_WINDOW
1095
+ const floor: i32 = limit > histStart + delta ? limit : histStart + delta
1096
+ const nice: i32 = this.niceLength < maxLen ? this.niceLength : maxLen
1097
+ const mask: u32 = minMatch === 3 ? toU32(0xffffff) : ~toU32(0)
1098
+ let chain: i32 = this.maxChain
1099
+ while (cand >= floor && cand < v && chain > 0) {
1100
+ const cd: i32 = cand - delta
1101
+ if (cd < 0 || cd > 2147483639) {
1102
+ break
1103
+ }
1104
+ const ci: integer<0, 2147483639> = cd
1105
+ // The byte that would make this match the longest yet, first: most
1106
+ // candidates fail on it.
1107
+ if (uncheckedGet(src, ci + best) === uncheckedGet(src, p + best)) {
1108
+ let l: i32 = 0
1109
+ if (roomy) {
1110
+ const x: u64 = deflateLoad64(src, ci) ^ deflateLoad64(src, at)
1111
+ l =
1112
+ x !== toU64(0)
1113
+ ? deflateCtz64(x) >> 3
1114
+ : toI32(8) + deflateMatchLength(src, ci + 8, p + 8, maxLen - 8)
1115
+ } else if (((deflateLoad32(src, ci) ^ word) & mask) === 0) {
1116
+ l = deflateMatchLength(src, ci, p, maxLen)
1117
+ }
1118
+ if (l > best) {
1119
+ best = l
1120
+ bestDist = v - cand
1121
+ if (l >= nice) {
1122
+ break
1123
+ }
1124
+ }
1125
+ }
1126
+ cand = uncheckedGet(prev, cand & (DEFLATE_WINDOW - 1))
1127
+ chain -= 1
1128
+ }
1129
+ if (bestDist === 0 || best < minMatch) {
1130
+ return 0
1131
+ }
1132
+ // A three-byte match far back costs more than its three literals.
1133
+ if (best === 3 && bestDist > 4096) {
1134
+ return 0
1135
+ }
1136
+ return (best << 16) | bestDist
1137
+ }
1138
+
1139
+ /** Records `p` in the chains without searching; `p + 4 <= src.length`. */
1140
+ insert(src: u8[], p: i32): void {
1141
+ const head: i32[] = this.head
1142
+ const prev: i32[] = this.prev
1143
+ if (toI32(head.length) !== DEFLATE_HASH_SIZE || toI32(prev.length) !== DEFLATE_WINDOW) {
1144
+ panic("Deflater.insert: a table is not its size")
1145
+ }
1146
+ const word: u32 = deflateLoad32(src, p)
1147
+ const h: i32 =
1148
+ this.minMatch === 3
1149
+ ? toI32(((word << 8) * toU32(DEFLATE_HASH_MUL)) >>> 17)
1150
+ : toI32((word * toU32(DEFLATE_HASH_MUL)) >>> 17)
1151
+ const v: i32 = p + this.delta
1152
+ uncheckedSet(prev, v & (DEFLATE_WINDOW - 1), uncheckedGet(head, h))
1153
+ uncheckedSet(head, h, v)
1154
+ }
1155
+
1156
+ /** Clears the block's symbols and frequencies. */
1157
+ startBlock(): void {
1158
+ this.litFreq.fill(0)
1159
+ this.distFreq.fill(0)
1160
+ this.count = 0
1161
+ }
1162
+
1163
+ /** Records the match `len`, `dist` as the block's next symbol. */
1164
+ addMatch(len: i32, dist: i32): void {
1165
+ const tokens: i32[] = this.tokens
1166
+ const n: i32 = this.count
1167
+ if (n < 0 || n >= toI32(tokens.length) || len < 3 || len > 258 || dist < 1 || dist > DEFLATE_WINDOW) {
1168
+ panic("Deflater.addMatch: a match outside the format")
1169
+ }
1170
+ uncheckedSet(tokens, n, (dist << 9) | (253 + len))
1171
+ this.count = n + 1
1172
+ const ls: i32 = uncheckedGet(this.lengthSymbol, len - 3)
1173
+ const lf: i32[] = this.litFreq
1174
+ uncheckedSet(lf, 257 + ls, uncheckedGet(lf, 257 + ls) + 1)
1175
+ const ds: i32 =
1176
+ dist <= 256
1177
+ ? uncheckedGet(this.distSymbol, dist - 1)
1178
+ : uncheckedGet(this.distSymbol, ((dist - 1) >> 7) + 256)
1179
+ const df: i32[] = this.distFreq
1180
+ uncheckedSet(df, ds, uncheckedGet(df, ds) + 1)
1181
+ }
1182
+
1183
+ /** Records the literal `b` as the block's next symbol. */
1184
+ addLiteral(b: i32): void {
1185
+ const tokens: i32[] = this.tokens
1186
+ const n: i32 = this.count
1187
+ if (n < 0 || n >= toI32(tokens.length) || b < 0 || b > 255) {
1188
+ panic("Deflater.addLiteral: a literal outside the format")
1189
+ }
1190
+ uncheckedSet(tokens, n, b)
1191
+ this.count = n + 1
1192
+ const lf: i32[] = this.litFreq
1193
+ uncheckedSet(lf, b, uncheckedGet(lf, b) + 1)
1194
+ }
1195
+
1196
+ /**
1197
+ * Fills the block's symbols greedily from `start`, and answers where the
1198
+ * block ends: at `end`, or where the symbol buffer filled. The match
1199
+ * finder, the chains and the symbol bookkeeping are written out in this one
1200
+ * loop over locals, because this is the fast level's whole cost.
1201
+ */
1202
+ collectGreedy(src: u8[], start: i32, end: i32, histStart: i32): i32 {
1203
+ this.startBlock()
1204
+ const head: i32[] = this.head
1205
+ const prev: i32[] = this.prev
1206
+ const tokens: i32[] = this.tokens
1207
+ const lf: i32[] = this.litFreq
1208
+ const df: i32[] = this.distFreq
1209
+ const lsym: i32[] = this.lengthSymbol
1210
+ const dsym: i32[] = this.distSymbol
1211
+ if (
1212
+ toI32(head.length) !== DEFLATE_HASH_SIZE ||
1213
+ toI32(prev.length) !== DEFLATE_WINDOW ||
1214
+ toI32(tokens.length) !== DEFLATE_BLOCK_TOKENS ||
1215
+ toI32(lf.length) < 288 ||
1216
+ toI32(df.length) < 32 ||
1217
+ toI32(lsym.length) < 256 ||
1218
+ toI32(dsym.length) < 512
1219
+ ) {
1220
+ panic("Deflater.collectGreedy: a table is not its size")
1221
+ }
1222
+ const delta: i32 = this.delta
1223
+ const lo: i32 = histStart + delta
1224
+ const maxChain: i32 = this.maxChain
1225
+ const niceLength: i32 = this.niceLength
1226
+ const room: i32 = DEFLATE_BLOCK_TOKENS - 1
1227
+ const last: i32 = end - 4
1228
+ let n: i32 = 0
1229
+ let p: i32 = start
1230
+ while (p < end && n < room) {
1231
+ let best: i32 = 0
1232
+ let bestDist: i32 = 0
1233
+ if (p >= 0 && p <= last && p <= 2147483639) {
1234
+ const word: u32 = deflateLoad32(src, p)
1235
+ const h: i32 = toI32((word * toU32(DEFLATE_HASH_MUL)) >>> 17)
1236
+ const v: i32 = p + delta
1237
+ let cand: i32 = uncheckedGet(head, h)
1238
+ uncheckedSet(head, h, v)
1239
+ uncheckedSet(prev, v & (DEFLATE_WINDOW - 1), cand)
1240
+ const maxLen: i32 = p <= end - DEFLATE_MAX_MATCH ? DEFLATE_MAX_MATCH : end - p
1241
+ const nice: i32 = niceLength < maxLen ? niceLength : maxLen
1242
+ const limit: i32 = v - DEFLATE_WINDOW
1243
+ let chain: i32 = maxChain
1244
+ while (cand >= limit && cand >= lo && cand < v && chain > 0) {
1245
+ const ci: i32 = cand - delta
1246
+ if (ci >= 0 && ci <= 2147483639 && deflateLoad32(src, ci) === word) {
1247
+ let l: i32 = 0
1248
+ if (p <= end - DEFLATE_MAX_MATCH && ci <= 2147483627) {
1249
+ const a4: i32 = ci + 4
1250
+ const b4: i32 = p + 4
1251
+ let x: u64 = toU64(1)
1252
+ if (a4 >= 0 && a4 <= 2147483639 && b4 >= 0 && b4 <= 2147483639) {
1253
+ x = deflateLoad64(src, a4) ^ deflateLoad64(src, b4)
1254
+ }
1255
+ l =
1256
+ x !== toU64(0)
1257
+ ? toI32(4) + (deflateCtz64(x) >> 3)
1258
+ : toI32(12) + deflateMatchLength(src, ci + 12, p + 12, maxLen - 12)
1259
+ } else {
1260
+ l = 4 + deflateMatchLength(src, ci + 4, p + 4, maxLen - 4)
1261
+ }
1262
+ if (l > best) {
1263
+ best = l
1264
+ bestDist = v - cand
1265
+ if (l >= nice) {
1266
+ break
1267
+ }
1268
+ }
1269
+ }
1270
+ cand = uncheckedGet(prev, cand & (DEFLATE_WINDOW - 1))
1271
+ chain -= 1
1272
+ }
1273
+ }
1274
+ if (best >= 4) {
1275
+ uncheckedSet(tokens, n, (bestDist << 9) | (253 + best))
1276
+ n += 1
1277
+ const ls: i32 = 257 + uncheckedGet(lsym, best - 3)
1278
+ uncheckedSet(lf, ls, uncheckedGet(lf, ls) + 1)
1279
+ const ds: i32 =
1280
+ bestDist <= 256 ? uncheckedGet(dsym, bestDist - 1) : uncheckedGet(dsym, ((bestDist - 1) >> 7) + 256)
1281
+ uncheckedSet(df, ds, uncheckedGet(df, ds) + 1)
1282
+ // Every position the match covers goes into the chains.
1283
+ const stop: i32 = p + best
1284
+ const insertEnd: i32 = stop <= last ? stop : last + 1
1285
+ let vq: i32 = wrappingAdd(p, delta)
1286
+ for (let q: i32 = p + 1; q < insertEnd && q >= 0 && q <= 2147483639; q += 1) {
1287
+ const qa: integer<0, 2147483639> = q
1288
+ const hq: i32 = toI32((deflateLoad32(src, qa) * toU32(DEFLATE_HASH_MUL)) >>> 17)
1289
+ vq = wrappingAdd(vq, 1)
1290
+ uncheckedSet(prev, vq & (DEFLATE_WINDOW - 1), uncheckedGet(head, hq))
1291
+ uncheckedSet(head, hq, vq)
1292
+ }
1293
+ p = stop
1294
+ } else {
1295
+ const b: i32 = toI32(uncheckedGet(src, p))
1296
+ uncheckedSet(tokens, n, b)
1297
+ n += 1
1298
+ uncheckedSet(lf, b, uncheckedGet(lf, b) + 1)
1299
+ p += 1
1300
+ }
1301
+ }
1302
+ this.count = n
1303
+ return p
1304
+ }
1305
+
1306
+ /**
1307
+ * Fills the block's symbols from `p`, deferring each match by a position
1308
+ * while the next one finds a longer one; answers where the block ends.
1309
+ */
1310
+ collectLazy(src: u8[], start: i32, end: i32, histStart: i32): i32 {
1311
+ this.startBlock()
1312
+ let p: i32 = start
1313
+ const room: i32 = DEFLATE_BLOCK_TOKENS - 2
1314
+ while (p < end && this.count < room) {
1315
+ let m: i32 = 0
1316
+ if (p + 4 <= end) {
1317
+ m = this.longest(src, p, end, histStart)
1318
+ }
1319
+ if (m === 0) {
1320
+ this.addLiteral(toI32(uncheckedGet(src, p)))
1321
+ p += 1
1322
+ } else {
1323
+ let inserted: i32 = p + 1
1324
+ while (m >> 16 < this.lazyLength && p + 5 <= end && this.count < room) {
1325
+ const m2: i32 = this.longest(src, p + 1, end, histStart)
1326
+ inserted = p + 2
1327
+ if (m2 >> 16 > m >> 16) {
1328
+ this.addLiteral(toI32(uncheckedGet(src, p)))
1329
+ p += 1
1330
+ m = m2
1331
+ } else {
1332
+ break
1333
+ }
1334
+ }
1335
+ const len: i32 = m >> 16
1336
+ this.addMatch(len, m & 0xffff)
1337
+ const stop: i32 = p + len
1338
+ let q: i32 = inserted
1339
+ const last: i32 = end - 4
1340
+ while (q < stop && q <= last) {
1341
+ this.insert(src, q)
1342
+ q += 1
1343
+ }
1344
+ p = stop
1345
+ }
1346
+ }
1347
+ return p
1348
+ }
1349
+
1350
+ /**
1351
+ * The bits a stored rendering of `n` bytes takes from a bit buffer holding
1352
+ * `pending` bits: each piece of up to 65,535 bytes has three header bits,
1353
+ * the padding to a byte and four bytes of `LEN` / `NLEN`.
1354
+ */
1355
+ storedBits(n: i32, pending: i32): i32 {
1356
+ let bits: i32 = 0
1357
+ let left: i32 = n
1358
+ let bc: i32 = pending
1359
+ let first: boolean = true
1360
+ while (first || left > 0) {
1361
+ first = false
1362
+ const take: i32 = left < DEFLATE_STORED_MAX ? left : DEFLATE_STORED_MAX
1363
+ const header: i32 = ((bc + 3 + 7) & ~7) - bc
1364
+ bits += header + 32 + 8 * take
1365
+ bc = 0
1366
+ left -= take
1367
+ }
1368
+ return bits
1369
+ }
1370
+
1371
+ /**
1372
+ * Writes `src[start .. end)` as stored blocks, the last BFINAL when
1373
+ * `final`; answers the new position, or -1 without writing when it does
1374
+ * not fit in `out[op .. oe)`.
1375
+ */
1376
+ writeStored(src: u8[], start: i32, end: i32, final: boolean, out: u8[], op: i32, oe: i32): i32 {
1377
+ const bits: i32 = this.storedBits(end - start, this.bitCount)
1378
+ if ((this.bitCount + bits + 7) >> 3 > oe - op) {
1379
+ return -1
1380
+ }
1381
+ let p: i32 = start
1382
+ let o: i32 = op
1383
+ let first: boolean = true
1384
+ while (first || p < end) {
1385
+ first = false
1386
+ const take: i32 = end - p < DEFLATE_STORED_MAX ? end - p : DEFLATE_STORED_MAX
1387
+ const last: boolean = p + take === end
1388
+ o = this.putBits(out, o, toI32(final && last ? 1 : 0), toI32(3))
1389
+ o = this.alignBits(out, o)
1390
+ deflateRoom(out, o, 4)
1391
+ uncheckedSet(out, o, toU8(take & 255))
1392
+ uncheckedSet(out, o + 1, toU8(take >> 8))
1393
+ uncheckedSet(out, o + 2, toU8(~take & 255))
1394
+ uncheckedSet(out, o + 3, toU8((~take >> 8) & 255))
1395
+ o += 4
1396
+ copyBytes(out, o, src, p, take)
1397
+ o += take
1398
+ p += take
1399
+ }
1400
+ return o
1401
+ }
1402
+
1403
+ /**
1404
+ * Builds the run-length coded lengths of the dynamic header (§3.2.7) for
1405
+ * `hlit` literal/length and `hdist` distance lengths, and their
1406
+ * frequencies in `clFreq`.
1407
+ */
1408
+ buildRle(hlit: i32, hdist: i32): void {
1409
+ const rle: i32[] = this.rle
1410
+ const freq: i32[] = this.clFreq
1411
+ const ll: i32[] = this.litLens
1412
+ const dl: i32[] = this.distLens
1413
+ if (toI32(rle.length) < 320 || toI32(freq.length) < 19 || hlit > 288 || hdist > 32) {
1414
+ panic("Deflater.buildRle: a header outside its scratch")
1415
+ }
1416
+ freq.fill(0)
1417
+ const total: i32 = hlit + hdist
1418
+ let n: i32 = 0
1419
+ let i: i32 = 0
1420
+ while (i < total) {
1421
+ const l: i32 = i < hlit ? uncheckedGet(ll, i) : uncheckedGet(dl, i - hlit)
1422
+ let run: i32 = 1
1423
+ while (
1424
+ i + run < total &&
1425
+ (i + run < hlit ? uncheckedGet(ll, i + run) : uncheckedGet(dl, i + run - hlit)) === l
1426
+ ) {
1427
+ run += 1
1428
+ }
1429
+ i += run
1430
+ if (l === 0) {
1431
+ while (run >= 11) {
1432
+ const r: i32 = run < 138 ? run : 138
1433
+ uncheckedSet(rle, n, ((r - 11) << 8) | 18)
1434
+ n += 1
1435
+ freq[18] += 1
1436
+ run -= r
1437
+ }
1438
+ if (run >= 3) {
1439
+ uncheckedSet(rle, n, ((run - 3) << 8) | 17)
1440
+ n += 1
1441
+ freq[17] += 1
1442
+ run = 0
1443
+ }
1444
+ } else {
1445
+ uncheckedSet(rle, n, l)
1446
+ n += 1
1447
+ if (l >= 0 && l < 19) {
1448
+ uncheckedSet(freq, l, uncheckedGet(freq, l) + 1)
1449
+ }
1450
+ run -= 1
1451
+ while (run >= 3) {
1452
+ const r: i32 = run < 6 ? run : 6
1453
+ uncheckedSet(rle, n, ((r - 3) << 8) | 16)
1454
+ n += 1
1455
+ freq[16] += 1
1456
+ run -= r
1457
+ }
1458
+ }
1459
+ while (run > 0) {
1460
+ uncheckedSet(rle, n, l)
1461
+ n += 1
1462
+ if (l >= 0 && l < 19) {
1463
+ uncheckedSet(freq, l, uncheckedGet(freq, l) + 1)
1464
+ }
1465
+ run -= 1
1466
+ }
1467
+ }
1468
+ this.rleCount = n
1469
+ }
1470
+
1471
+ /**
1472
+ * Writes the block's symbols, `src[start .. end)`'s, as the smallest of a
1473
+ * dynamic, a fixed and a stored block; answers the new position, or -1
1474
+ * without writing when that does not fit in `out[op .. oe)`.
1475
+ */
1476
+ writeBlock(src: u8[], start: i32, end: i32, final: boolean, out: u8[], op: i32, oe: i32): i32 {
1477
+ const lf: i32[] = this.litFreq
1478
+ const df: i32[] = this.distFreq
1479
+ lf[256] = 1
1480
+ deflateLengths(lf, 286, 15, this.litLens, this.scratch)
1481
+ deflateLengths(df, 30, 15, this.distLens, this.scratch)
1482
+ this.litLens[286] = 0
1483
+ this.litLens[287] = 0
1484
+ this.distLens[30] = 0
1485
+ this.distLens[31] = 0
1486
+ deflateCanonical(this.litLens, 286, this.litCodes, this.countScratch, this.nextScratch)
1487
+ deflateCanonical(this.distLens, 30, this.distCodes, this.countScratch, this.nextScratch)
1488
+ let hlit: i32 = 286
1489
+ while (hlit > 257 && this.litLens[hlit - 1] === 0) {
1490
+ hlit -= 1
1491
+ }
1492
+ let hdist: i32 = 30
1493
+ while (hdist > 1 && this.distLens[hdist - 1] === 0) {
1494
+ hdist -= 1
1495
+ }
1496
+ this.buildRle(hlit, hdist)
1497
+ deflateLengths(this.clFreq, 19, 7, this.clLens, this.scratch)
1498
+ deflateCanonical(this.clLens, 19, this.clCodes, this.countScratch, this.nextScratch)
1499
+ let hclen: i32 = 19
1500
+ while (hclen > 4 && this.clLens[deflateClOrder(hclen - 1)] === 0) {
1501
+ hclen -= 1
1502
+ }
1503
+ // The three sizes, exactly. Extra bits are the same in both codes.
1504
+ let extra: i32 = 0
1505
+ let dynBits: i32 = hclen * 3 + 17
1506
+ let fixBits: i32 = 3
1507
+ for (let s: i32 = 0; s < 286; s += 1) {
1508
+ const f: i32 = uncheckedGet(lf, s)
1509
+ dynBits += f * uncheckedGet(this.litLens, s)
1510
+ fixBits += f * uncheckedGet(this.fixedLitLens, s)
1511
+ if (s >= 257) {
1512
+ extra += f * uncheckedGet(this.lengthExtra, s - 257)
1513
+ }
1514
+ }
1515
+ for (let d: i32 = 0; d < 30; d += 1) {
1516
+ const f: i32 = uncheckedGet(df, d)
1517
+ dynBits += f * uncheckedGet(this.distLens, d)
1518
+ fixBits += f * 5
1519
+ extra += f * uncheckedGet(this.distExtra, d)
1520
+ }
1521
+ for (let s: i32 = 0; s < 19; s += 1) {
1522
+ dynBits += this.clFreq[s] * this.clLens[s]
1523
+ }
1524
+ dynBits += 2 * this.clFreq[16] + 3 * this.clFreq[17] + 7 * this.clFreq[18]
1525
+ dynBits += extra
1526
+ fixBits += extra
1527
+ const storedBits: i32 = this.storedBits(end - start, this.bitCount)
1528
+ if (storedBits <= dynBits && storedBits <= fixBits) {
1529
+ return this.writeStored(src, start, end, final, out, op, oe)
1530
+ }
1531
+ const dynamic: boolean = dynBits < fixBits
1532
+ const bits: i32 = dynamic ? dynBits : fixBits
1533
+ if ((this.bitCount + bits + 7) >> 3 > oe - op) {
1534
+ return -1
1535
+ }
1536
+ let header: i32 = dynamic ? toI32(4) : toI32(2)
1537
+ if (final) {
1538
+ header += 1
1539
+ }
1540
+ let o: i32 = this.putBits(out, op, header, toI32(3))
1541
+ if (dynamic) {
1542
+ o = this.putBits(out, o, (hlit - 257) | ((hdist - 1) << 5) | ((hclen - 4) << 10), toI32(14))
1543
+ for (let i: i32 = 0; i < hclen; i += 1) {
1544
+ o = this.putBits(out, o, this.clLens[deflateClOrder(i)], toI32(3))
1545
+ }
1546
+ const rle: i32[] = this.rle
1547
+ const n: i32 = this.rleCount
1548
+ for (let i: i32 = 0; i < n && i < toI32(rle.length); i += 1) {
1549
+ const e: i32 = rle[i]
1550
+ const sym: i32 = e & 255
1551
+ if (sym < 0 || sym >= 19) {
1552
+ panic("Deflater.writeBlock: a code-length symbol outside 0 to 18")
1553
+ }
1554
+ o = this.putBits(out, o, this.clCodes[sym], this.clLens[sym])
1555
+ if (sym === 16) {
1556
+ o = this.putBits(out, o, e >> 8, toI32(2))
1557
+ } else if (sym === 17) {
1558
+ o = this.putBits(out, o, e >> 8, toI32(3))
1559
+ } else if (sym === 18) {
1560
+ o = this.putBits(out, o, e >> 8, toI32(7))
1561
+ }
1562
+ }
1563
+ o = this.writeSymbols(this.litCodes, this.litLens, this.distCodes, this.distLens, out, o)
1564
+ } else {
1565
+ o = this.writeSymbols(
1566
+ this.fixedLitCodes,
1567
+ this.fixedLitLens,
1568
+ this.fixedDistCodes,
1569
+ this.fixedDistLens,
1570
+ out,
1571
+ o
1572
+ )
1573
+ }
1574
+ return o
1575
+ }
1576
+
1577
+ /**
1578
+ * Writes the block's symbols and its end-of-block code under the given
1579
+ * code into `out` at `op`; answers the new position. The room was checked
1580
+ * by the block's exact size.
1581
+ */
1582
+ writeSymbols(lc: i32[], ll: i32[], dc: i32[], dl: i32[], out: u8[], op: i32): i32 {
1583
+ const tokens: i32[] = this.tokens
1584
+ const n: i32 = this.count
1585
+ const lsym: i32[] = this.lengthSymbol
1586
+ const lbase: i32[] = this.lengthBase
1587
+ const lextra: i32[] = this.lengthExtra
1588
+ const dsym: i32[] = this.distSymbol
1589
+ const dbase: i32[] = this.distBase
1590
+ const dextra: i32[] = this.distExtra
1591
+ if (
1592
+ toI32(lc.length) < 288 ||
1593
+ toI32(ll.length) < 288 ||
1594
+ toI32(dc.length) < 32 ||
1595
+ toI32(dl.length) < 32 ||
1596
+ n > toI32(tokens.length) ||
1597
+ toI32(lsym.length) < 256 ||
1598
+ toI32(lbase.length) < 29 ||
1599
+ toI32(lextra.length) < 29 ||
1600
+ toI32(dsym.length) < 512 ||
1601
+ toI32(dbase.length) < 30 ||
1602
+ toI32(dextra.length) < 30
1603
+ ) {
1604
+ panic("Deflater.writeSymbols: a table is not its size")
1605
+ }
1606
+ let bb: u64 = this.bitBuf
1607
+ let bc: i32 = this.bitCount
1608
+ let o: i32 = op
1609
+ for (let i: i32 = 0; i < n; i += 1) {
1610
+ const t: i32 = uncheckedGet(tokens, i)
1611
+ if (t < 256) {
1612
+ bb = bb | (toU64(toU32(uncheckedGet(lc, t))) << toU64(bc))
1613
+ bc += uncheckedGet(ll, t)
1614
+ } else {
1615
+ const len3: i32 = (t & 511) - 256
1616
+ const dist: i32 = t >> 9
1617
+ const s: i32 = uncheckedGet(lsym, len3)
1618
+ bb = bb | (toU64(toU32(uncheckedGet(lc, 257 + s))) << toU64(bc))
1619
+ bc += uncheckedGet(ll, 257 + s)
1620
+ bb = bb | (toU64(toU32(len3 + 3 - uncheckedGet(lbase, s))) << toU64(bc))
1621
+ bc += uncheckedGet(lextra, s)
1622
+ if (bc >= 32) {
1623
+ deflateRoom(out, o, 4)
1624
+ uncheckedSet(out, o, toU8(bb))
1625
+ uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1626
+ uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
1627
+ uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
1628
+ bb = bb >> toU64(32)
1629
+ bc -= 32
1630
+ o += 4
1631
+ }
1632
+ const d: i32 =
1633
+ dist <= 256 ? uncheckedGet(dsym, dist - 1) : uncheckedGet(dsym, ((dist - 1) >> 7) + 256)
1634
+ bb = bb | (toU64(toU32(uncheckedGet(dc, d))) << toU64(bc))
1635
+ bc += uncheckedGet(dl, d)
1636
+ bb = bb | (toU64(toU32(dist - uncheckedGet(dbase, d))) << toU64(bc))
1637
+ bc += uncheckedGet(dextra, d)
1638
+ }
1639
+ if (bc >= 32) {
1640
+ deflateRoom(out, o, 4)
1641
+ uncheckedSet(out, o, toU8(bb))
1642
+ uncheckedSet(out, o + 1, toU8(bb >> toU64(8)))
1643
+ uncheckedSet(out, o + 2, toU8(bb >> toU64(16)))
1644
+ uncheckedSet(out, o + 3, toU8(bb >> toU64(24)))
1645
+ bb = bb >> toU64(32)
1646
+ bc -= 32
1647
+ o += 4
1648
+ }
1649
+ }
1650
+ this.bitBuf = bb
1651
+ this.bitCount = bc
1652
+ return this.putBits(out, o, lc[256], ll[256])
1653
+ }
1654
+ }
1655
+
1656
+ /**
1657
+ * One Huffman decoding table: the entries for every `bits`-bit prefix, and
1658
+ * for the codes longer than that, the count per length and the symbols in
1659
+ * canonical order that a bit-at-a-time decode walks (§3.2.2).
1660
+ */
1661
+ export class InflateTable {
1662
+ /**
1663
+ * `entries[peek]`: value << 16 | extra << 11 | kind << 8 | length. The low
1664
+ * byte is the length alone, so a bit buffer shifts by an entry as it is.
1665
+ */
1666
+ readonly entries: i32[]
1667
+ /** The prefix the table indexes. */
1668
+ readonly bits: i32
1669
+ /** How many codes have each length 0 to 15. */
1670
+ readonly count: i32[]
1671
+ /** The symbols, ordered by code. */
1672
+ readonly symbols: i32[]
1673
+
1674
+ /**
1675
+ * A table indexing `bits` bits, for an alphabet of up to `symbols`
1676
+ * symbols, with room for `capacity` entries: the main table and its
1677
+ * subtables.
1678
+ */
1679
+ constructor(bits: i32, symbols: i32, capacity: i32) {
1680
+ this.bits = bits
1681
+ this.entries = new Array<i32>(capacity)
1682
+ this.count = new Array<i32>(16)
1683
+ this.symbols = new Array<i32>(symbols)
1684
+ }
1685
+ }
1686
+
1687
+ /**
1688
+ * Copies `entries[0 .. end)` to `entries[end .. 2 * end)`: a table for codes
1689
+ * one bit longer, each shorter code repeated under both values of the new
1690
+ * bit. Panics unless `2 * end` is within the table.
1691
+ */
1692
+ const inflateDouble = (entries: i32[], end: i32): void => {
1693
+ if (end < 0 || end > toI32(entries.length) - end) {
1694
+ panic("Inflater.build: a table doubled past its length")
1695
+ }
1696
+ // A counter below a bound needs no overflow check, and the loop without
1697
+ // one is a vector copy.
1698
+ const twice: i32 = end + end
1699
+ for (let j: i32 = end; j < twice; j += 1) {
1700
+ uncheckedSet(entries, j, uncheckedGet(entries, j - end))
1701
+ }
1702
+ }
1703
+
1704
+ /** The kind of table `inflateBuild` builds: what each symbol decodes to. */
1705
+ const INF_TABLE_LITLEN: i32 = 0
1706
+ const INF_TABLE_DIST: i32 = 1
1707
+ const INF_TABLE_CODELEN: i32 = 2
1708
+
1709
+ /**
1710
+ * A DEFLATE decompressor: the decoding tables, the fixed code's, and the state
1711
+ * that lets `inflate` stop at the end of its input or output and resume.
1712
+ * Not shared between threads.
1713
+ */
1714
+ export class Inflater {
1715
+ readonly lit: InflateTable
1716
+ readonly dist: InflateTable
1717
+ readonly codeLengths: InflateTable
1718
+ readonly fixedLit: InflateTable
1719
+ readonly fixedDist: InflateTable
1720
+ /** The lengths a dynamic header sends, literal/length then distance. */
1721
+ readonly lens: i32[]
1722
+ /** The order-indexed code-length code lengths. */
1723
+ readonly clLens: i32[]
1724
+ /** Scratch for building a table. */
1725
+ readonly offsets: i32[]
1726
+ /** Each symbol's table entry with a length of 0, per kind of table: `entryOf(kind, s, 0)`. */
1727
+ readonly litEntries: i32[]
1728
+ readonly distEntries: i32[]
1729
+ readonly clEntries: i32[]
1730
+ readonly lengthBase: i32[]
1731
+ readonly lengthExtra: i32[]
1732
+ readonly distBase: i32[]
1733
+ readonly distExtra: i32[]
1734
+ /** Where `inflate` resumes: the block header, a stored block, a Huffman block, or done. */
1735
+ state: i32
1736
+ /** Whether the block being read is the final one. */
1737
+ last: boolean
1738
+ /** Whether the Huffman block uses the fixed code. */
1739
+ fixed: boolean
1740
+ /** Bytes of the current stored block still to copy. */
1741
+ storedLeft: i32
1742
+ /** Bits read but not consumed, low bit first, and how many. */
1743
+ bitBuf: u64
1744
+ bitCount: i32
1745
+ /** Where the last `inflate` stopped in its input and its output. */
1746
+ inPos: i32
1747
+ outPos: i32
1748
+ /** The input bytes the last `decompress` read, its final block included. */
1749
+ consumed: i32
1750
+
1751
+ /** Builds the tables, the fixed code's among them. */
1752
+ constructor() {
1753
+ this.lit = new InflateTable(INF_LIT_BITS, 288, INF_LIT_ENOUGH)
1754
+ this.dist = new InflateTable(INF_DIST_BITS, 32, INF_DIST_ENOUGH)
1755
+ this.codeLengths = new InflateTable(INF_CL_BITS, 19, 1 << INF_CL_BITS)
1756
+ this.fixedLit = new InflateTable(INF_LIT_BITS, 288, INF_LIT_ENOUGH)
1757
+ this.fixedDist = new InflateTable(INF_DIST_BITS, 32, INF_DIST_ENOUGH)
1758
+ this.lens = new Array<i32>(320)
1759
+ this.clLens = new Array<i32>(19)
1760
+ this.offsets = new Array<i32>(16)
1761
+ this.lengthBase = new Array<i32>(29)
1762
+ this.lengthExtra = new Array<i32>(29)
1763
+ this.distBase = new Array<i32>(32)
1764
+ this.distExtra = new Array<i32>(32)
1765
+ for (let s: i32 = 0; s < 29; s += 1) {
1766
+ this.lengthBase[s] = deflateLengthBase(s)
1767
+ this.lengthExtra[s] = deflateLengthExtra(s)
1768
+ }
1769
+ for (let d: i32 = 0; d < 30; d += 1) {
1770
+ this.distBase[d] = deflateDistBase(d)
1771
+ this.distExtra[d] = deflateDistExtra(d)
1772
+ }
1773
+ this.litEntries = new Array<i32>(288)
1774
+ this.distEntries = new Array<i32>(32)
1775
+ this.clEntries = new Array<i32>(19)
1776
+ this.state = INF_S_BLOCK
1777
+ this.last = false
1778
+ this.fixed = false
1779
+ this.storedLeft = 0
1780
+ this.bitBuf = 0
1781
+ this.bitCount = 0
1782
+ this.inPos = 0
1783
+ this.outPos = 0
1784
+ this.consumed = 0
1785
+ for (let s: i32 = 0; s < 288; s += 1) {
1786
+ this.litEntries[s] = this.entryOf(INF_TABLE_LITLEN, s, toI32(0))
1787
+ }
1788
+ for (let s: i32 = 0; s < 32; s += 1) {
1789
+ this.distEntries[s] = this.entryOf(INF_TABLE_DIST, s, toI32(0))
1790
+ }
1791
+ for (let s: i32 = 0; s < 19; s += 1) {
1792
+ this.clEntries[s] = this.entryOf(INF_TABLE_CODELEN, s, toI32(0))
1793
+ }
1794
+ for (let s: i32 = 0; s < 288; s += 1) {
1795
+ this.lens[s] = deflateFixedLitLength(s)
1796
+ }
1797
+ // The fixed distance code has 32 five-bit codes, 30 and 31 among them,
1798
+ // which decode as errors (§3.2.6).
1799
+ const fl: i32 = this.build(this.fixedLit, this.lens, toI32(0), toI32(288), INF_TABLE_LITLEN)
1800
+ for (let d: i32 = 0; d < 32; d += 1) {
1801
+ this.lens[d] = 5
1802
+ }
1803
+ const fd: i32 = this.build(this.fixedDist, this.lens, toI32(0), toI32(32), INF_TABLE_DIST)
1804
+ if (fl !== 0 || fd !== 0) {
1805
+ panic("Inflater: the fixed code did not build")
1806
+ }
1807
+ }
1808
+
1809
+ /** Starts a new stream: the next `inflate` reads a first block header. */
1810
+ reset(): void {
1811
+ this.state = INF_S_BLOCK
1812
+ this.last = false
1813
+ this.fixed = false
1814
+ this.storedLeft = 0
1815
+ this.bitBuf = 0
1816
+ this.bitCount = 0
1817
+ }
1818
+
1819
+ /**
1820
+ * The table entry for symbol `s` of a table of `kind`.
1821
+ */
1822
+ entryOf(kind: i32, s: i32, len: i32): i32 {
1823
+ if (kind === INF_TABLE_CODELEN) {
1824
+ return (s << 16) | len
1825
+ }
1826
+ if (kind === INF_TABLE_DIST) {
1827
+ if (s >= 30) {
1828
+ return (INF_INVALID << 8) | len
1829
+ }
1830
+ return (this.distBase[s] << 16) | (this.distExtra[s] << 11) | len
1831
+ }
1832
+ if (s < 256) {
1833
+ return (s << 16) | (INF_LITERAL << 8) | len
1834
+ }
1835
+ if (s === 256) {
1836
+ return (INF_END << 8) | len
1837
+ }
1838
+ if (s >= 286) {
1839
+ return (INF_INVALID << 8) | len
1840
+ }
1841
+ return (this.lengthBase[s - 257] << 16) | (INF_LENGTH << 8) | (this.lengthExtra[s - 257] << 11) | len
1842
+ }
1843
+
1844
+ /**
1845
+ * Builds `t` from the code lengths `lens[from .. from + n)`; answers 0, or
1846
+ * `DEFLATE_ERR_HUFFMAN` for an over-subscribed set or an incomplete one
1847
+ * (an incomplete set of a single one-bit code is allowed, as RFC 1951
1848
+ * §3.2.7 allows one distance code).
1849
+ */
1850
+ build(t: InflateTable, lens: i32[], from: i32, n: i32, kind: i32): i32 {
1851
+ const count: i32[] = t.count
1852
+ const syms: i32[] = t.symbols
1853
+ const entries: i32[] = t.entries
1854
+ const offs: i32[] = this.offsets
1855
+ const bits: i32 = t.bits
1856
+ if (
1857
+ from < 0 ||
1858
+ n < 0 ||
1859
+ from > toI32(lens.length) - n ||
1860
+ n > toI32(syms.length) ||
1861
+ toI32(count.length) < 16 ||
1862
+ toI32(offs.length) < 16 ||
1863
+ toI32(entries.length) < 1 << bits
1864
+ ) {
1865
+ panic("Inflater.build: a table outside its scratch")
1866
+ }
1867
+ for (let l: i32 = 0; l < 16; l += 1) {
1868
+ count[l] = 0
1869
+ }
1870
+ // `lens[from .. from + n)` was checked above. A length outside 0 to 15
1871
+ // shows in the OR of them all, tested once after the loop.
1872
+ const hi: i32 = from + n
1873
+ let seen: i32 = 0
1874
+ for (let i: i32 = from; i < hi; i += 1) {
1875
+ const l: i32 = uncheckedGet(lens, i)
1876
+ seen = seen | l
1877
+ const c: i32 = l & 15
1878
+ count[c] = wrappingAdd(count[c], 1)
1879
+ }
1880
+ if ((seen & ~15) !== 0) {
1881
+ return DEFLATE_ERR_HUFFMAN
1882
+ }
1883
+ count[0] = 0
1884
+ // The Kraft sum: over-subscribed is an error; incomplete is allowed for
1885
+ // one one-bit code only.
1886
+ let left: i32 = 1
1887
+ let codes: i32 = 0
1888
+ for (let l: i32 = 1; l < 16; l += 1) {
1889
+ left = (left << 1) - count[l]
1890
+ codes += count[l]
1891
+ if (left < 0) {
1892
+ return DEFLATE_ERR_HUFFMAN
1893
+ }
1894
+ }
1895
+ if (left > 0 && codes !== 0 && !(kind !== INF_TABLE_CODELEN && codes === 1 && count[1] === 1)) {
1896
+ return DEFLATE_ERR_HUFFMAN
1897
+ }
1898
+ // Sorted by length, then symbol, with no branch per symbol: the unused
1899
+ // symbols (length 0) go after the rest, where nothing reads them.
1900
+ offs[1] = 0
1901
+ for (let l: i32 = 1; l < 15; l += 1) {
1902
+ offs[l + 1] = offs[l] + count[l]
1903
+ }
1904
+ offs[0] = codes
1905
+ for (let i: i32 = from; i < hi; i += 1) {
1906
+ const l: i32 = uncheckedGet(lens, i) & 15
1907
+ const at: i32 = offs[l]
1908
+ if (at >= 0 && at < toI32(syms.length)) {
1909
+ syms[at] = i - from
1910
+ }
1911
+ offs[l] = wrappingAdd(at, 1)
1912
+ }
1913
+ const size: i32 = 1 << bits
1914
+ const slow: i32 = INF_SLOW << 8
1915
+ let tmpl: i32[] = this.clEntries
1916
+ if (kind === INF_TABLE_LITLEN) {
1917
+ tmpl = this.litEntries
1918
+ } else if (kind === INF_TABLE_DIST) {
1919
+ tmpl = this.distEntries
1920
+ }
1921
+ let len: i32 = 1
1922
+ while (len < 16 && count[len] === 0) {
1923
+ len += 1
1924
+ }
1925
+ if (left > 0 || len > bits) {
1926
+ // No code, one incomplete one-bit code, or every code longer than the
1927
+ // table: every prefix starts as the slow way, which also finds an
1928
+ // undefined code, and the short codes are written over it.
1929
+ for (let i: i32 = 0; i < size; i += 1) {
1930
+ uncheckedSet(entries, i, slow)
1931
+ }
1932
+ let code: i32 = 0
1933
+ let k: i32 = 0
1934
+ for (let l: i32 = 1; l <= bits && l < 16; l += 1) {
1935
+ const codesHere: i32 = uncheckedGet(count, l)
1936
+ for (let c: i32 = 0; c < codesHere; c += 1) {
1937
+ if (k >= 0 && k < toI32(syms.length)) {
1938
+ const e: i32 = tmpl[syms[k]] | l
1939
+ const step: i32 = 1 << l
1940
+ for (let r: i32 = deflateReverse(code, l); r < size; r += step) {
1941
+ uncheckedSet(entries, r, e)
1942
+ }
1943
+ }
1944
+ k += 1
1945
+ code += 1
1946
+ }
1947
+ code = code << 1
1948
+ }
1949
+ return 0
1950
+ }
1951
+ // A complete code whose shortest codes fit the table. The codes in
1952
+ // canonical order, kept bit-reversed (the table is indexed by the
1953
+ // stream's low bits first): each is written once into a table of
1954
+ // `end = 2^len` entries, and the table is doubled by copying each time
1955
+ // the length grows, which repeats every code at every slot it prefixes.
1956
+ // A reversed code is incremented by clearing the ones below its highest
1957
+ // zero and setting that zero.
1958
+ let code: i32 = 0
1959
+ let end: i32 = 1 << len
1960
+ let k: i32 = 0
1961
+ let here: i32 = 0
1962
+ while (len <= bits && len >= 0 && len < toI32(count.length)) {
1963
+ here = count[len]
1964
+ while (here > 0) {
1965
+ if (k < 0 || k >= toI32(syms.length) || code < 0 || code >= end || end > size) {
1966
+ panic("Inflater.build: a code outside its table")
1967
+ }
1968
+ uncheckedSet(entries, code, tmpl[syms[k]] | len)
1969
+ k += 1
1970
+ if (code === end - 1) {
1971
+ // The last code, all ones: the code is complete within the table.
1972
+ while (end < size) {
1973
+ inflateDouble(entries, end)
1974
+ end = end << 1
1975
+ }
1976
+ return 0
1977
+ }
1978
+ const bit: i32 = toI32(1) << (31 - toI32(Math.clz32(toU32(code ^ (end - 1)))))
1979
+ code = (code & (bit - 1)) | bit
1980
+ here -= 1
1981
+ }
1982
+ len += 1
1983
+ while (len < 16 && count[len] === 0) {
1984
+ len += 1
1985
+ }
1986
+ while (end < size && end < 1 << len) {
1987
+ inflateDouble(entries, end)
1988
+ end = end << 1
1989
+ }
1990
+ }
1991
+ here = len < 16 ? count[len] : 0
1992
+ // Codes longer than the table remain, `here` of them of length `len`,
1993
+ // and `code` is the next, reversed, its low `bits` bits a slot of the
1994
+ // main table. The codes that share a slot get a subtable after the
1995
+ // tables already built, as wide as it takes for them to fill it (the
1996
+ // code is complete, so they do), and the slot points to it. A subtable
1997
+ // entry carries the bits past the main table's as its length.
1998
+ const limit: i32 = toI32(entries.length)
1999
+ let prefix: i32 = -1
2000
+ let start: i32 = 0
2001
+ let subEnd: i32 = size
2002
+ while (true) {
2003
+ if (len < bits || len > 15) {
2004
+ panic("Inflater.build: a code outside its table")
2005
+ }
2006
+ if ((code & (size - 1)) !== prefix) {
2007
+ prefix = code & (size - 1)
2008
+ start = subEnd
2009
+ let subBits: i32 = len - bits
2010
+ let used: i32 = here
2011
+ while (used < 1 << subBits && bits + subBits < 15) {
2012
+ subBits += 1
2013
+ used = (used << 1) + count[bits + subBits]
2014
+ }
2015
+ subEnd = start + (1 << subBits)
2016
+ if (subEnd > limit || prefix < 0) {
2017
+ panic("Inflater.build: a subtable past the table's room")
2018
+ }
2019
+ uncheckedSet(entries, prefix, (start << 16) | (INF_SUB << 8) | (subBits << 11) | bits)
2020
+ }
2021
+ if (k < 0 || k >= toI32(syms.length)) {
2022
+ panic("Inflater.build: a code outside its table")
2023
+ }
2024
+ const e: i32 = tmpl[syms[k]] | (len - bits)
2025
+ k += 1
2026
+ const stride: i32 = toI32(1) << (len - bits)
2027
+ let i: i32 = start + (code >> bits)
2028
+ while (i < subEnd && i >= 0) {
2029
+ uncheckedSet(entries, i, e)
2030
+ i += stride
2031
+ }
2032
+ if (code === (1 << len) - 1) {
2033
+ return 0
2034
+ }
2035
+ const bit: i32 = toI32(1) << (31 - toI32(Math.clz32(toU32(code ^ ((toI32(1) << len) - 1)))))
2036
+ code = (code & (bit - 1)) | bit
2037
+ here -= 1
2038
+ while (here === 0 && len < 15) {
2039
+ const next: i32 = len + 1
2040
+ if (next < 0 || next >= toI32(count.length)) {
2041
+ break
2042
+ }
2043
+ len = next
2044
+ here = count[next]
2045
+ }
2046
+ }
2047
+ }
2048
+
2049
+ /**
2050
+ * Decodes the symbol at the bottom of `bb`, holding `bc` valid bits, one
2051
+ * bit at a time from the counts (§3.2.2): answers the table entry of the
2052
+ * symbol with its true code length, or -1 when the bits run out before a
2053
+ * code ends (`bc` too small), or -2 when no code matches.
2054
+ */
2055
+ slowDecode(t: InflateTable, kind: i32, bb: u64, bc: i32): i32 {
2056
+ const count: i32[] = t.count
2057
+ const syms: i32[] = t.symbols
2058
+ let code: i32 = 0
2059
+ let first: i32 = 0
2060
+ let index: i32 = 0
2061
+ let b: u64 = bb
2062
+ for (let l: i32 = 1; l < 16 && l < toI32(count.length); l += 1) {
2063
+ if (l > bc) {
2064
+ return -1
2065
+ }
2066
+ code = code | toI32(b & toU64(1))
2067
+ b = b >> toU64(1)
2068
+ const c: i32 = count[l]
2069
+ if (code - c < first) {
2070
+ const at: i32 = index + (code - first)
2071
+ if (at < 0 || at >= toI32(syms.length)) {
2072
+ return -2
2073
+ }
2074
+ return this.entryOf(kind, syms[at], l)
2075
+ }
2076
+ index += c
2077
+ first = (first + c) << 1
2078
+ code = code << 1
2079
+ }
2080
+ return -2
2081
+ }
2082
+
2083
+ /** Reads bytes of `src` into the bit buffer from `inPos` while it has room and `end` allows. */
2084
+ fill(src: u8[], end: i32): void {
2085
+ let bb: u64 = this.bitBuf
2086
+ let bc: i32 = this.bitCount
2087
+ let ip: i32 = this.inPos
2088
+ if (ip < 0 || end > toI32(src.length)) {
2089
+ panic("Inflater.fill: a window outside its input")
2090
+ }
2091
+ if (ip <= end - 8) {
2092
+ // A word at once, whole bytes of it counted, as the fast loop does.
2093
+ const at: integer<0, 2147483639> = ip
2094
+ bb = bb | (deflateLoad64(src, at) << toU64(bc))
2095
+ ip += (63 - bc) >> 3
2096
+ bc = bc | 56
2097
+ } else {
2098
+ while (bc <= 56 && ip < end) {
2099
+ bb = bb | (toU64(uncheckedGet(src, ip)) << toU64(bc))
2100
+ ip += 1
2101
+ bc += 8
2102
+ }
2103
+ }
2104
+ this.bitBuf = bb
2105
+ this.bitCount = bc
2106
+ this.inPos = ip
2107
+ }
2108
+
2109
+ /** The low `n` bits of the bit buffer, consumed; the caller has checked that `n` are there. */
2110
+ take(n: i32): i32 {
2111
+ const v: i32 = toI32(this.bitBuf & ((toU64(1) << toU64(n)) - toU64(1)))
2112
+ this.bitBuf = this.bitBuf >> toU64(n)
2113
+ this.bitCount = this.bitCount - n
2114
+ return v
2115
+ }
2116
+
2117
+ /**
2118
+ * Gives back the whole bytes of the bit buffer to the input, after dropping
2119
+ * the bits to the next byte boundary: where a stored block's `LEN`, or the
2120
+ * framing after the final block, begins.
2121
+ */
2122
+ unread(): void {
2123
+ const drop: i32 = this.bitCount & 7
2124
+ this.bitBuf = this.bitBuf >> toU64(drop)
2125
+ this.bitCount = this.bitCount - drop
2126
+ this.inPos = this.inPos - (this.bitCount >> 3)
2127
+ this.bitBuf = 0
2128
+ this.bitCount = 0
2129
+ }
2130
+
2131
+ /**
2132
+ * Reads a dynamic block's header (§3.2.7) from the bit buffer and `src`,
2133
+ * and builds its tables. Answers 0, `INFLATE_NEED_INPUT` when the input ran
2134
+ * out first (nothing is consumed then: the caller rewinds), or an error.
2135
+ */
2136
+ readDynamic(src: u8[], end: i32): i32 {
2137
+ // The bit buffer in locals: the lengths are stored into an `i32[]`,
2138
+ // which the fields could alias, and every symbol would reload them.
2139
+ let bb: u64 = this.bitBuf
2140
+ let bc: i32 = this.bitCount
2141
+ let ip: i32 = this.inPos
2142
+ if (ip < 0 || end > toI32(src.length)) {
2143
+ panic("Inflater.readDynamic: a window outside its input")
2144
+ }
2145
+ if (ip <= end - 8) {
2146
+ const at: integer<0, 2147483639> = ip
2147
+ bb = bb | (deflateLoad64(src, at) << toU64(bc))
2148
+ ip += (63 - bc) >> 3
2149
+ bc = bc | 56
2150
+ } else {
2151
+ while (bc <= 56 && ip < end) {
2152
+ bb = bb | (toU64(uncheckedGet(src, ip)) << toU64(bc))
2153
+ ip += 1
2154
+ bc += 8
2155
+ }
2156
+ }
2157
+ if (bc < 14) {
2158
+ return INFLATE_NEED_INPUT
2159
+ }
2160
+ const hlit: i32 = toI32(bb & toU64(31)) + 257
2161
+ const hdist: i32 = toI32((bb >> toU64(5)) & toU64(31)) + 1
2162
+ const hclen: i32 = toI32((bb >> toU64(10)) & toU64(15)) + 4
2163
+ bb = bb >> toU64(14)
2164
+ bc -= 14
2165
+ if (hlit > 286 || hdist > 30) {
2166
+ return DEFLATE_ERR_HUFFMAN
2167
+ }
2168
+ const cl: i32[] = this.clLens
2169
+ for (let i: i32 = 0; i < 19; i += 1) {
2170
+ cl[deflateClOrder(i)] = 0
2171
+ }
2172
+ for (let i: i32 = 0; i < hclen; i += 1) {
2173
+ if (bc < 3) {
2174
+ if (ip >= 0 && ip <= end - 8 && ip <= 2147483639) {
2175
+ const at: integer<0, 2147483639> = ip
2176
+ bb = bb | (deflateLoad64(src, at) << toU64(bc))
2177
+ ip += (63 - bc) >> 3
2178
+ bc = bc | 56
2179
+ } else {
2180
+ while (bc <= 56 && ip < end) {
2181
+ bb = bb | (toU64(uncheckedGet(src, ip)) << toU64(bc))
2182
+ ip += 1
2183
+ bc += 8
2184
+ }
2185
+ }
2186
+ if (bc < 3) {
2187
+ return INFLATE_NEED_INPUT
2188
+ }
2189
+ }
2190
+ cl[deflateClOrder(i)] = toI32(bb & toU64(7))
2191
+ bb = bb >> toU64(3)
2192
+ bc -= 3
2193
+ }
2194
+ const r: i32 = this.build(this.codeLengths, cl, toI32(0), toI32(19), INF_TABLE_CODELEN)
2195
+ if (r !== 0) {
2196
+ return r
2197
+ }
2198
+ const lens: i32[] = this.lens
2199
+ const entries: i32[] = this.codeLengths.entries
2200
+ if (toI32(entries.length) < 128) {
2201
+ panic("Inflater.readDynamic: the code-length table is not its size")
2202
+ }
2203
+ const total: i32 = hlit + hdist
2204
+ let i: i32 = 0
2205
+ while (i < total) {
2206
+ // A code-length code is at most 7 bits and its repeat count at most 7.
2207
+ if (bc < 14) {
2208
+ if (ip >= 0 && ip <= end - 8 && ip <= 2147483639) {
2209
+ const at: integer<0, 2147483639> = ip
2210
+ bb = bb | (deflateLoad64(src, at) << toU64(bc))
2211
+ ip += (63 - bc) >> 3
2212
+ bc = bc | 56
2213
+ } else {
2214
+ while (bc <= 56 && ip < end) {
2215
+ bb = bb | (toU64(uncheckedGet(src, ip)) << toU64(bc))
2216
+ ip += 1
2217
+ bc += 8
2218
+ }
2219
+ }
2220
+ }
2221
+ const e: i32 = uncheckedGet(entries, toI32(bb & toU64(127)))
2222
+ if (((e >> 8) & 7) === INF_SLOW) {
2223
+ // Only an incomplete code-length code leaves a prefix unfilled.
2224
+ return bc >= 7 ? DEFLATE_ERR_SYMBOL : INFLATE_NEED_INPUT
2225
+ }
2226
+ const l: i32 = e & 15
2227
+ if (l > bc) {
2228
+ return INFLATE_NEED_INPUT
2229
+ }
2230
+ bb = bb >> toU64(l)
2231
+ bc -= l
2232
+ const sym: i32 = e >> 16
2233
+ if (sym < 16) {
2234
+ if (i < 0 || i >= toI32(lens.length)) {
2235
+ return DEFLATE_ERR_HUFFMAN
2236
+ }
2237
+ lens[i] = sym
2238
+ i += 1
2239
+ } else {
2240
+ let rep: i32 = 0
2241
+ let value: i32 = 0
2242
+ let x: i32 = 0
2243
+ if (sym === 16) {
2244
+ if (i === 0) {
2245
+ return DEFLATE_ERR_HUFFMAN
2246
+ }
2247
+ value = lens[i - 1]
2248
+ x = 2
2249
+ rep = 3
2250
+ } else if (sym === 17) {
2251
+ x = 3
2252
+ rep = 3
2253
+ } else {
2254
+ x = 7
2255
+ rep = 11
2256
+ }
2257
+ if (bc < x) {
2258
+ return INFLATE_NEED_INPUT
2259
+ }
2260
+ rep += toI32(bb & ((toU64(1) << toU64(x)) - toU64(1)))
2261
+ bb = bb >> toU64(x)
2262
+ bc -= x
2263
+ if (i + rep > total) {
2264
+ return DEFLATE_ERR_HUFFMAN
2265
+ }
2266
+ for (let k: i32 = 0; k < rep && i < toI32(lens.length); k += 1) {
2267
+ lens[i] = value
2268
+ i += 1
2269
+ }
2270
+ }
2271
+ }
2272
+ if (lens[256] === 0) {
2273
+ return DEFLATE_ERR_HUFFMAN
2274
+ }
2275
+ const rl: i32 = this.build(this.lit, lens, toI32(0), hlit, INF_TABLE_LITLEN)
2276
+ if (rl !== 0) {
2277
+ return rl
2278
+ }
2279
+ const rd: i32 = this.build(this.dist, lens, hlit, hdist, INF_TABLE_DIST)
2280
+ if (rd !== 0) {
2281
+ return rd
2282
+ }
2283
+ this.bitBuf = bb
2284
+ this.bitCount = bc
2285
+ this.inPos = ip
2286
+ return 0
2287
+ }
2288
+
2289
+ /**
2290
+ * Decodes from `src[ip .. inEnd)` into `out[op .. outEnd)`, resuming where
2291
+ * the last call stopped; a match may reach back to `histStart`. `more`
2292
+ * says whether input may follow `inEnd`: with it, running out is
2293
+ * `INFLATE_NEED_INPUT` (every byte up to `inPos` is used, and the bit
2294
+ * buffer keeps what it read ahead), without it `DEFLATE_ERR_TRUNCATED`.
2295
+ * Answers `INFLATE_DONE` once the final block has ended, with `inPos` the
2296
+ * first byte after it; `INFLATE_NEED_OUTPUT` when the next symbol does not
2297
+ * fit; or a negative `DEFLATE_ERR_*`. `inPos` and `outPos` say where it
2298
+ * stopped. Windows outside their arrays panic.
2299
+ */
2300
+ inflate(
2301
+ src: u8[],
2302
+ ip: i32,
2303
+ inEnd: i32,
2304
+ more: boolean,
2305
+ out: u8[],
2306
+ op: i32,
2307
+ outEnd: i32,
2308
+ histStart: i32
2309
+ ): i32 {
2310
+ if (ip < 0 || ip > inEnd || inEnd > toI32(src.length)) {
2311
+ panic("Inflater.inflate: an input window outside its array")
2312
+ }
2313
+ if (histStart < 0 || histStart > op || op > outEnd || outEnd > toI32(out.length)) {
2314
+ panic("Inflater.inflate: an output window outside its array")
2315
+ }
2316
+ this.inPos = ip
2317
+ this.outPos = op
2318
+ const r: i32 = this.step(src, inEnd, more, out, outEnd, histStart)
2319
+ // Whole bytes the bit buffer read ahead go back to the input, so that a
2320
+ // caller may drop everything before `inPos`.
2321
+ const back: i32 = this.bitCount >> 3
2322
+ this.inPos = this.inPos - back
2323
+ this.bitCount = this.bitCount - 8 * back
2324
+ this.bitBuf = this.bitBuf & ((toU64(1) << toU64(this.bitCount)) - toU64(1))
2325
+ return r
2326
+ }
2327
+
2328
+ /** `inflate`'s state machine, once its windows are checked. */
2329
+ step(src: u8[], inEnd: i32, more: boolean, out: u8[], outEnd: i32, histStart: i32): i32 {
2330
+ while (true) {
2331
+ const s: i32 = this.state
2332
+ if (s === INF_S_DONE) {
2333
+ return INFLATE_DONE
2334
+ }
2335
+ if (s === INF_S_BLOCK) {
2336
+ if (this.last) {
2337
+ this.unread()
2338
+ this.state = INF_S_DONE
2339
+ return INFLATE_DONE
2340
+ }
2341
+ const saveBuf: u64 = this.bitBuf
2342
+ const saveCount: i32 = this.bitCount
2343
+ const savePos: i32 = this.inPos
2344
+ this.fill(src, inEnd)
2345
+ if (this.bitCount < 3) {
2346
+ this.bitBuf = saveBuf
2347
+ this.bitCount = saveCount
2348
+ this.inPos = savePos
2349
+ return more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2350
+ }
2351
+ const header: i32 = this.take(toI32(3))
2352
+ const type: i32 = header >> 1
2353
+ if (type === 0) {
2354
+ this.unread()
2355
+ if (inEnd - this.inPos < 4) {
2356
+ this.bitBuf = saveBuf
2357
+ this.bitCount = saveCount
2358
+ this.inPos = savePos
2359
+ return more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2360
+ }
2361
+ const at: i32 = this.inPos
2362
+ const len: i32 = toI32(uncheckedGet(src, at)) | (toI32(uncheckedGet(src, at + 1)) << 8)
2363
+ const nlen: i32 = toI32(uncheckedGet(src, at + 2)) | (toI32(uncheckedGet(src, at + 3)) << 8)
2364
+ if ((len ^ 0xffff) !== nlen) {
2365
+ return DEFLATE_ERR_STORED_LENGTH
2366
+ }
2367
+ this.inPos = at + 4
2368
+ this.storedLeft = len
2369
+ this.last = (header & 1) !== 0
2370
+ this.state = INF_S_STORED
2371
+ } else if (type === 1) {
2372
+ this.last = (header & 1) !== 0
2373
+ this.fixed = true
2374
+ this.state = INF_S_HUFF
2375
+ } else if (type === 2) {
2376
+ const r: i32 = this.readDynamic(src, inEnd)
2377
+ if (r === INFLATE_NEED_INPUT) {
2378
+ this.bitBuf = saveBuf
2379
+ this.bitCount = saveCount
2380
+ this.inPos = savePos
2381
+ return more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2382
+ }
2383
+ if (r !== 0) {
2384
+ return r
2385
+ }
2386
+ this.last = (header & 1) !== 0
2387
+ this.fixed = false
2388
+ this.state = INF_S_HUFF
2389
+ } else {
2390
+ return DEFLATE_ERR_BLOCK_TYPE
2391
+ }
2392
+ } else if (s === INF_S_STORED) {
2393
+ let n: i32 = this.storedLeft
2394
+ const inAvail: i32 = inEnd - this.inPos
2395
+ const outAvail: i32 = outEnd - this.outPos
2396
+ if (n > inAvail) {
2397
+ n = inAvail
2398
+ }
2399
+ if (n > outAvail) {
2400
+ n = outAvail
2401
+ }
2402
+ copyBytes(out, this.outPos, src, this.inPos, n)
2403
+ this.inPos += n
2404
+ this.outPos += n
2405
+ this.storedLeft -= n
2406
+ if (this.storedLeft > 0) {
2407
+ if (this.outPos === outEnd) {
2408
+ return INFLATE_NEED_OUTPUT
2409
+ }
2410
+ return more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2411
+ }
2412
+ this.state = INF_S_BLOCK
2413
+ } else {
2414
+ const r: i32 = this.huffman(src, inEnd, more, out, outEnd, histStart)
2415
+ if (r !== 0) {
2416
+ return r
2417
+ }
2418
+ }
2419
+ }
2420
+ }
2421
+
2422
+ /**
2423
+ * The Huffman block loop: decodes symbols until the end of the block
2424
+ * (answers 0, the state back at a block header), or until the input or
2425
+ * the output runs short or the stream is malformed (answers that code).
2426
+ */
2427
+ huffman(src: u8[], inEnd: i32, more: boolean, out: u8[], outEnd: i32, histStart: i32): i32 {
2428
+ const lt: InflateTable = this.fixed ? this.fixedLit : this.lit
2429
+ const dt: InflateTable = this.fixed ? this.fixedDist : this.dist
2430
+ const le: i32[] = lt.entries
2431
+ const de: i32[] = dt.entries
2432
+ if (toI32(le.length) !== INF_LIT_ENOUGH || toI32(de.length) !== INF_DIST_ENOUGH) {
2433
+ panic("Inflater.huffman: a table is not its size")
2434
+ }
2435
+ const litMask: u64 = toU64((1 << INF_LIT_BITS) - 1)
2436
+ const distMask: u64 = toU64((1 << INF_DIST_BITS) - 1)
2437
+ // The fast loop runs while eight bytes of input can be loaded and the
2438
+ // longest match, with sixteen bytes of copy slack, fits the output.
2439
+ const inFast: i32 = inEnd - 8
2440
+ const outFast: i32 = outEnd - INF_FAST_ROOM
2441
+ let bb: u64 = this.bitBuf
2442
+ let bc: i32 = this.bitCount
2443
+ let ip: i32 = this.inPos
2444
+ let op: i32 = this.outPos
2445
+ let status: i32 = 0
2446
+ let ended: boolean = false
2447
+ while (true) {
2448
+ // The fast loop: after a refill the buffer holds 64 bits of input, of
2449
+ // which it counts the whole bytes (56 to 63), and a length, its extra
2450
+ // bits, a distance and its extra bits take at most 48. So no symbol is
2451
+ // checked for running short, every symbol is decoded here (the end of
2452
+ // the block and errors included), and the next symbol's entry is
2453
+ // looked up before the refill rather than after it, from the 16 or
2454
+ // more bits still in hand, which takes the refill off the chain of
2455
+ // lookups. The careful step below takes over where the input or the
2456
+ // output runs short.
2457
+ //
2458
+ // The bit count may carry borrows above its low byte, which alone is
2459
+ // the count: subtracting a whole entry, whose low byte is its length,
2460
+ // costs no mask, and every shift reads the low six bits only. It is
2461
+ // masked again when the loop ends.
2462
+ if (ip >= 0 && ip <= inFast && ip <= 2147483639 && op <= outFast) {
2463
+ const first: integer<0, 2147483639> = ip
2464
+ bb = bb | (deflateLoad64(src, first) << toU64(bc))
2465
+ ip = wrappingAdd(ip, toI32(7) - ((bc >> 3) & 7))
2466
+ bc = bc | 56
2467
+ let e: i32 = uncheckedGet(le, toI32(bb & litMask))
2468
+ while (true) {
2469
+ if ((e & 0x700) === 0) {
2470
+ // A literal of at most eleven bits; with 45 or more bits left,
2471
+ // so may the next two be.
2472
+ bb = bb >> toU64(e)
2473
+ bc = wrappingSub(bc, e)
2474
+ uncheckedSet(out, op, toU8(e >> 16))
2475
+ op = wrappingAdd(op, 1)
2476
+ e = uncheckedGet(le, toI32(bb & litMask))
2477
+ if ((e & 0x700) === 0) {
2478
+ bb = bb >> toU64(e)
2479
+ bc = wrappingSub(bc, e)
2480
+ uncheckedSet(out, op, toU8(e >> 16))
2481
+ op = wrappingAdd(op, 1)
2482
+ e = uncheckedGet(le, toI32(bb & litMask))
2483
+ if ((e & 0x700) === 0) {
2484
+ bb = bb >> toU64(e)
2485
+ bc = wrappingSub(bc, e)
2486
+ uncheckedSet(out, op, toU8(e >> 16))
2487
+ op = wrappingAdd(op, 1)
2488
+ e = uncheckedGet(le, toI32(bb & litMask))
2489
+ }
2490
+ }
2491
+ } else {
2492
+ if ((e & 0x700) === INF_SUB << 8) {
2493
+ // A code longer than the table: its last bits index a subtable.
2494
+ bb = bb >> toU64(e)
2495
+ bc = wrappingSub(bc, e)
2496
+ e = uncheckedGet(le, (e >> 16) + toI32(bb & toU64((toI32(1) << ((e >> 11) & 15)) - 1)))
2497
+ } else if ((e & 0x700) === INF_SLOW << 8) {
2498
+ // Only a table built for an incomplete code (none at all, or
2499
+ // one one-bit code) has these, and every code it does have
2500
+ // is in the table: with all the bits in hand, no code matches.
2501
+ status = DEFLATE_ERR_SYMBOL
2502
+ break
2503
+ }
2504
+ bb = bb >> toU64(e)
2505
+ bc = wrappingSub(bc, e)
2506
+ if ((e & 0x700) !== INF_LENGTH << 8) {
2507
+ if ((e & 0x700) === INF_LITERAL << 8) {
2508
+ uncheckedSet(out, op, toU8(e >> 16))
2509
+ op = wrappingAdd(op, 1)
2510
+ e = uncheckedGet(le, toI32(bb & litMask))
2511
+ } else {
2512
+ if ((e & 0x700) === INF_END << 8) {
2513
+ this.state = INF_S_BLOCK
2514
+ } else {
2515
+ status = DEFLATE_ERR_SYMBOL
2516
+ }
2517
+ ended = true
2518
+ break
2519
+ }
2520
+ } else {
2521
+ const lx: i32 = (e >> 11) & 15
2522
+ const len: i32 = (e >> 16) + toI32(bb & ((toU64(1) << toU64(lx)) - toU64(1)))
2523
+ bb = bb >> toU64(lx)
2524
+ bc = wrappingSub(bc, lx)
2525
+ let d: i32 = uncheckedGet(de, toI32(bb & distMask))
2526
+ if ((d & 0x700) === INF_SUB << 8) {
2527
+ bb = bb >> toU64(d)
2528
+ bc = wrappingSub(bc, d)
2529
+ d = uncheckedGet(de, (d >> 16) + toI32(bb & toU64((toI32(1) << ((d >> 11) & 15)) - 1)))
2530
+ }
2531
+ if ((d & 0x700) !== 0) {
2532
+ // A slow entry, as for the literal/length table, or one of
2533
+ // the two distance codes that decode as errors.
2534
+ status = DEFLATE_ERR_SYMBOL
2535
+ break
2536
+ }
2537
+ bb = bb >> toU64(d)
2538
+ bc = wrappingSub(bc, d)
2539
+ const dx: i32 = (d >> 11) & 15
2540
+ const dist: i32 = (d >> 16) + toI32(bb & ((toU64(1) << toU64(dx)) - toU64(1)))
2541
+ bb = bb >> toU64(dx)
2542
+ bc = wrappingSub(bc, dx)
2543
+ if (dist > op - histStart) {
2544
+ status = DEFLATE_ERR_DISTANCE
2545
+ break
2546
+ }
2547
+ // The next entry, before the copy, so that its lookup and the
2548
+ // copy overlap.
2549
+ e = uncheckedGet(le, toI32(bb & litMask))
2550
+ const stop: i32 = wrappingAdd(op, len)
2551
+ if (dist >= 8) {
2552
+ // Sixteen bytes at a time: a copy runs at most fifteen bytes
2553
+ // past `stop`, inside `outEnd`, and the next symbol
2554
+ // overwrites them. `op` and `op - dist` lie in
2555
+ // [histStart, outEnd - 290], so the bounds in the condition
2556
+ // always hold; they are what lets the positions enter the
2557
+ // copy's range without a check, and the bytes loop after is
2558
+ // what would finish a copy they ever stopped.
2559
+ let to: i32 = op
2560
+ let from: i32 = op - dist
2561
+ while (to < stop && to >= 0 && to <= 2147483631 && from >= 0 && from <= 2147483631) {
2562
+ inflateCopy16(out, to, from)
2563
+ to = wrappingAdd(to, 16)
2564
+ from = wrappingAdd(from, 16)
2565
+ }
2566
+ while (to < stop) {
2567
+ uncheckedSet(out, to, uncheckedGet(out, from))
2568
+ to = wrappingAdd(to, 1)
2569
+ from = wrappingAdd(from, 1)
2570
+ }
2571
+ } else if (dist === 1) {
2572
+ // A run of one byte, sixteen at a time, bounded as above.
2573
+ const four: u64 = toU64(uncheckedGet(out, op - 1)) * toU64(0x01010101)
2574
+ const w: u64 = four | (four << toU64(32))
2575
+ let to: i32 = op
2576
+ while (to < stop && to >= 0 && to <= 2147483631) {
2577
+ inflateFill16(out, to, w)
2578
+ to = wrappingAdd(to, 16)
2579
+ }
2580
+ while (to < stop) {
2581
+ uncheckedSet(out, to, toU8(w))
2582
+ to = wrappingAdd(to, 1)
2583
+ }
2584
+ } else {
2585
+ let from: i32 = op - dist
2586
+ let to: i32 = op
2587
+ while (to < stop) {
2588
+ uncheckedSet(out, to, uncheckedGet(out, from))
2589
+ to = wrappingAdd(to, 1)
2590
+ from = wrappingAdd(from, 1)
2591
+ }
2592
+ }
2593
+ op = stop
2594
+ }
2595
+ }
2596
+ if (ip < 0 || ip > inFast || ip > 2147483639 || op > outFast) {
2597
+ break
2598
+ }
2599
+ const at: integer<0, 2147483639> = ip
2600
+ bb = bb | (deflateLoad64(src, at) << toU64(bc))
2601
+ ip = wrappingAdd(ip, toI32(7) - ((bc >> 3) & 7))
2602
+ bc = bc | 56
2603
+ }
2604
+ }
2605
+ bc = bc & 63
2606
+ if (status !== 0 || ended) {
2607
+ break
2608
+ }
2609
+ const sBb: u64 = bb
2610
+ const sBc: i32 = bc
2611
+ const sIp: i32 = ip
2612
+ // Refill to at least 56 bits where eight bytes remain, else as many
2613
+ // as there are: a symbol is decoded only once all its bits are here.
2614
+ if (ip >= 0 && ip <= inFast) {
2615
+ bb = bb | (deflateLoad64(src, ip) << toU64(bc))
2616
+ ip += (63 - bc) >> 3
2617
+ bc = bc | 56
2618
+ } else {
2619
+ while (bc <= 56 && ip < inEnd) {
2620
+ bb = bb | (toU64(uncheckedGet(src, ip)) << toU64(bc))
2621
+ ip += 1
2622
+ bc += 8
2623
+ }
2624
+ }
2625
+ const e: i32 = this.lookup(lt, INF_TABLE_LITLEN, le, bb, bc)
2626
+ if (e === -1) {
2627
+ status = INFLATE_NEED_INPUT
2628
+ } else if (e < 0) {
2629
+ status = DEFLATE_ERR_SYMBOL
2630
+ }
2631
+ if (status !== 0) {
2632
+ if (status === INFLATE_NEED_INPUT) {
2633
+ bb = sBb
2634
+ bc = sBc
2635
+ ip = sIp
2636
+ if (!more) {
2637
+ status = DEFLATE_ERR_TRUNCATED
2638
+ }
2639
+ }
2640
+ break
2641
+ }
2642
+ const kind: i32 = (e >> 8) & 7
2643
+ const n: i32 = e & 15
2644
+ bb = bb >> toU64(n)
2645
+ bc -= n
2646
+ if (kind === INF_LITERAL) {
2647
+ if (op >= outEnd) {
2648
+ bb = sBb
2649
+ bc = sBc
2650
+ ip = sIp
2651
+ status = INFLATE_NEED_OUTPUT
2652
+ break
2653
+ }
2654
+ uncheckedSet(out, op, toU8(e >> 16))
2655
+ op += 1
2656
+ } else if (kind === INF_LENGTH) {
2657
+ const lx: i32 = (e >> 11) & 15
2658
+ if (lx > bc) {
2659
+ bb = sBb
2660
+ bc = sBc
2661
+ ip = sIp
2662
+ status = more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2663
+ break
2664
+ }
2665
+ const len: i32 = (e >> 16) + toI32(bb & ((toU64(1) << toU64(lx)) - toU64(1)))
2666
+ bb = bb >> toU64(lx)
2667
+ bc -= lx
2668
+ const d: i32 = this.lookup(dt, INF_TABLE_DIST, de, bb, bc)
2669
+ if (d === -1) {
2670
+ bb = sBb
2671
+ bc = sBc
2672
+ ip = sIp
2673
+ status = more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2674
+ break
2675
+ }
2676
+ if (d < 0 || ((d >> 8) & 7) === INF_INVALID) {
2677
+ status = DEFLATE_ERR_SYMBOL
2678
+ break
2679
+ }
2680
+ const dn: i32 = d & 15
2681
+ const dx: i32 = (d >> 11) & 15
2682
+ if (dn + dx > bc) {
2683
+ bb = sBb
2684
+ bc = sBc
2685
+ ip = sIp
2686
+ status = more ? INFLATE_NEED_INPUT : DEFLATE_ERR_TRUNCATED
2687
+ break
2688
+ }
2689
+ bb = bb >> toU64(dn)
2690
+ const dist: i32 = (d >> 16) + toI32(bb & ((toU64(1) << toU64(dx)) - toU64(1)))
2691
+ bb = bb >> toU64(dx)
2692
+ bc -= dn + dx
2693
+ if (dist > op - histStart) {
2694
+ status = DEFLATE_ERR_DISTANCE
2695
+ break
2696
+ }
2697
+ if (len > outEnd - op) {
2698
+ bb = sBb
2699
+ bc = sBc
2700
+ ip = sIp
2701
+ status = INFLATE_NEED_OUTPUT
2702
+ break
2703
+ }
2704
+ let from: i32 = op - dist
2705
+ const stop: i32 = op + len
2706
+ while (op < stop) {
2707
+ uncheckedSet(out, op, uncheckedGet(out, from))
2708
+ op += 1
2709
+ from += 1
2710
+ }
2711
+ } else if (kind === INF_END) {
2712
+ this.state = INF_S_BLOCK
2713
+ break
2714
+ } else {
2715
+ status = DEFLATE_ERR_SYMBOL
2716
+ break
2717
+ }
2718
+ }
2719
+ this.bitBuf = bb
2720
+ this.bitCount = bc
2721
+ this.inPos = ip
2722
+ this.outPos = op
2723
+ return status
2724
+ }
2725
+
2726
+ /**
2727
+ * The entry of the symbol at the bottom of `bb`, holding `bc` valid bits,
2728
+ * from `t` (whose entries are `entries`), with its whole code length in
2729
+ * the low four bits, through a subtable or the slow way as the table
2730
+ * says: -1 when the bits run out before the code ends, -2 when no code
2731
+ * matches. A code is decoded only once all its bits are here.
2732
+ */
2733
+ lookup(t: InflateTable, kind: i32, entries: i32[], bb: u64, bc: i32): i32 {
2734
+ const mask: u64 = toU64((1 << t.bits) - 1)
2735
+ let e: i32 = entries[toI32(bb & mask)]
2736
+ if (((e >> 8) & 7) === INF_SUB) {
2737
+ const root: i32 = e & 15
2738
+ const at: i32 = (e >> 16) + toI32((bb >> toU64(root)) & toU64((toI32(1) << ((e >> 11) & 15)) - 1))
2739
+ const sub: i32 = entries[at]
2740
+ e = (sub & ~15) | (root + (sub & 15))
2741
+ } else if (((e >> 8) & 7) === INF_SLOW) {
2742
+ return this.slowDecode(t, kind, bb, bc)
2743
+ }
2744
+ return (e & 15) > bc ? -1 : e
2745
+ }
2746
+
2747
+ /**
2748
+ * Decompresses the raw DEFLATE stream `src[off .. off + len)` into `out`
2749
+ * from `at`, writing at most `limit` bytes and never past `out`'s end, and
2750
+ * answers where the output ends; or `DEFLATE_ERR_OUTPUT_LIMIT` when the
2751
+ * stream holds more, `DEFLATE_ERR_TRAILING` when bytes follow its final
2752
+ * block, or another negative `DEFLATE_ERR_*` for a malformed stream. A
2753
+ * window outside its array, or a negative `limit`, panics. Allocates
2754
+ * nothing.
2755
+ */
2756
+ decompress(src: u8[], off: i32, len: i32, out: u8[], at: i32, limit: i32): i32 {
2757
+ deflateWindow("Inflater.decompress", src, off, len)
2758
+ deflateWindow("Inflater.decompress", out, at, 0)
2759
+ if (limit < 0) {
2760
+ panic("Inflater.decompress: a negative limit")
2761
+ }
2762
+ const room: i32 = toI32(out.length) - at
2763
+ const end: i32 = at + (limit < room ? limit : room)
2764
+ this.reset()
2765
+ const r: i32 = this.inflate(src, off, off + len, false, out, at, end, at)
2766
+ this.consumed = this.inPos - off
2767
+ if (r === INFLATE_NEED_OUTPUT) {
2768
+ return DEFLATE_ERR_OUTPUT_LIMIT
2769
+ }
2770
+ if (r !== INFLATE_DONE) {
2771
+ return r
2772
+ }
2773
+ if (this.inPos !== off + len) {
2774
+ return DEFLATE_ERR_TRAILING
2775
+ }
2776
+ return this.outPos
2777
+ }
2778
+ }
2779
+
2780
+ /**
2781
+ * `Deflater.compress` at `level`, building the compressor for this call
2782
+ * alone: 330 KB allocated and filled each time, so keep a `Deflater` for
2783
+ * anything repeated.
2784
+ */
2785
+ export const deflateCompress = (src: u8[], off: i32, len: i32, out: u8[], at: i32, level: i32): i32 =>
2786
+ new Deflater(level).compress(src, off, len, out, at)
2787
+
2788
+ /** `Inflater.decompress`, building the decompressor for this call alone. */
2789
+ export const deflateDecompress = (src: u8[], off: i32, len: i32, out: u8[], at: i32, limit: i32): i32 =>
2790
+ new Inflater().decompress(src, off, len, out, at, limit)