Coverage Report

Created: 2026-10-16 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/haproxy/src/slz.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2013-2015 Willy Tarreau <w@1wt.eu>
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining
5
 * a copy of this software and associated documentation files (the
6
 * "Software"), to deal in the Software without restriction, including
7
 * without limitation the rights to use, copy, modify, merge, publish,
8
 * distribute, sublicense, and/or sell copies of the Software, and to
9
 * permit persons to whom the Software is furnished to do so, subject to
10
 * the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be
13
 * included in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
 * OTHER DEALINGS IN THE SOFTWARE.
23
 */
24
25
#include <stdio.h>
26
#include <string.h>
27
#include "import/slz.h"
28
#include "import/slz-prv.h"
29
#include "import/slz-tables.h"
30
31
/* if PRECOMPUTE_TABLES not set, then tables.h does not provide fh_dist_table
32
 * table as we need to recompute it.
33
 */
34
#ifndef PRECOMPUTE_TABLES
35
static uint32_t fh_dist_table[32768];
36
#endif // ifndef PRECOMPUTE_TABLES
37
38
/* First, RFC1951-specific declarations and extracts from the RFC.
39
 *
40
 * RFC1951 - deflate stream format
41
42
43
             * Data elements are packed into bytes in order of
44
               increasing bit number within the byte, i.e., starting
45
               with the least-significant bit of the byte.
46
             * Data elements other than Huffman codes are packed
47
               starting with the least-significant bit of the data
48
               element.
49
             * Huffman codes are packed starting with the most-
50
               significant bit of the code.
51
52
      3.2.3. Details of block format
53
54
         Each block of compressed data begins with 3 header bits
55
         containing the following data:
56
57
            first bit       BFINAL
58
            next 2 bits     BTYPE
59
60
         Note that the header bits do not necessarily begin on a byte
61
         boundary, since a block does not necessarily occupy an integral
62
         number of bytes.
63
64
         BFINAL is set if and only if this is the last block of the data
65
         set.
66
67
         BTYPE specifies how the data are compressed, as follows:
68
69
            00 - no compression
70
            01 - compressed with fixed Huffman codes
71
            10 - compressed with dynamic Huffman codes
72
            11 - reserved (error)
73
74
      3.2.4. Non-compressed blocks (BTYPE=00)
75
76
         Any bits of input up to the next byte boundary are ignored.
77
         The rest of the block consists of the following information:
78
79
              0   1   2   3   4...
80
            +---+---+---+---+================================+
81
            |  LEN  | NLEN  |... LEN bytes of literal data...|
82
            +---+---+---+---+================================+
83
84
         LEN is the number of data bytes in the block.  NLEN is the
85
         one's complement of LEN.
86
87
      3.2.5. Compressed blocks (length and distance codes)
88
89
         As noted above, encoded data blocks in the "deflate" format
90
         consist of sequences of symbols drawn from three conceptually
91
         distinct alphabets: either literal bytes, from the alphabet of
92
         byte values (0..255), or <length, backward distance> pairs,
93
         where the length is drawn from (3..258) and the distance is
94
         drawn from (1..32,768).  In fact, the literal and length
95
         alphabets are merged into a single alphabet (0..285), where
96
         values 0..255 represent literal bytes, the value 256 indicates
97
         end-of-block, and values 257..285 represent length codes
98
         (possibly in conjunction with extra bits following the symbol
99
         code) as follows:
100
101
Length encoding :
102
                Extra               Extra               Extra
103
            Code Bits Length(s) Code Bits Lengths   Code Bits Length(s)
104
            ---- ---- ------     ---- ---- -------   ---- ---- -------
105
             257   0     3       267   1   15,16     277   4   67-82
106
             258   0     4       268   1   17,18     278   4   83-98
107
             259   0     5       269   2   19-22     279   4   99-114
108
             260   0     6       270   2   23-26     280   4  115-130
109
             261   0     7       271   2   27-30     281   5  131-162
110
             262   0     8       272   2   31-34     282   5  163-194
111
             263   0     9       273   3   35-42     283   5  195-226
112
             264   0    10       274   3   43-50     284   5  227-257
113
             265   1  11,12      275   3   51-58     285   0    258
114
             266   1  13,14      276   3   59-66
115
116
Distance encoding :
117
                  Extra           Extra               Extra
118
             Code Bits Dist  Code Bits   Dist     Code Bits Distance
119
             ---- ---- ----  ---- ----  ------    ---- ---- --------
120
               0   0    1     10   4     33-48    20    9   1025-1536
121
               1   0    2     11   4     49-64    21    9   1537-2048
122
               2   0    3     12   5     65-96    22   10   2049-3072
123
               3   0    4     13   5     97-128   23   10   3073-4096
124
               4   1   5,6    14   6    129-192   24   11   4097-6144
125
               5   1   7,8    15   6    193-256   25   11   6145-8192
126
               6   2   9-12   16   7    257-384   26   12  8193-12288
127
               7   2  13-16   17   7    385-512   27   12 12289-16384
128
               8   3  17-24   18   8    513-768   28   13 16385-24576
129
               9   3  25-32   19   8   769-1024   29   13 24577-32768
130
131
      3.2.6. Compression with fixed Huffman codes (BTYPE=01)
132
133
         The Huffman codes for the two alphabets are fixed, and are not
134
         represented explicitly in the data.  The Huffman code lengths
135
         for the literal/length alphabet are:
136
137
                   Lit Value    Bits        Codes
138
                   ---------    ----        -----
139
                     0 - 143     8          00110000 through
140
                                            10111111
141
                   144 - 255     9          110010000 through
142
                                            111111111
143
                   256 - 279     7          0000000 through
144
                                            0010111
145
                   280 - 287     8          11000000 through
146
                                            11000111
147
148
         The code lengths are sufficient to generate the actual codes,
149
         as described above; we show the codes in the table for added
150
         clarity.  Literal/length values 286-287 will never actually
151
         occur in the compressed data, but participate in the code
152
         construction.
153
154
         Distance codes 0-31 are represented by (fixed-length) 5-bit
155
         codes, with possible additional bits as shown in the table
156
         shown in Paragraph 3.2.5, above.  Note that distance codes 30-
157
         31 will never actually occur in the compressed data.
158
159
*/
160
161
/* back references, built in a way that is optimal for 32/64 bits */
162
/* format:
163
 * bit0..31  = word
164
 * bit32..63 = last position in buffer of similar content
165
 */
166
union ref {
167
  struct {
168
    uint32_t pos;
169
    uint32_t word;
170
  } by32;
171
  uint64_t by64;
172
};
173
174
#if defined(__SIZEOF_LONG__) && (__SIZEOF_LONG__ - 0 > 4) && defined(UNALIGNED_LE_OK)
175
176
/* enqueue code x of <xbits> bits (LSB aligned, at most 24) and copy complete
177
 * 32-bit words into output buffer. X must not contain non-zero bits above
178
 * xbits.
179
 */
180
static inline void enqueue24(struct slz_stream *strm, uint64_t x, uint32_t xbits)
181
0
{
182
0
  uint64_t queue = strm->queue + (x << strm->qbits);
183
0
  uint32_t qbits = strm->qbits + xbits;
184
185
0
  if (__builtin_expect(qbits >= 32, 1)) {
186
0
    *(uint32_t *)strm->outbuf = queue;
187
0
    queue >>= 32;
188
0
    qbits -= 32;
189
0
    strm->outbuf += 4;
190
0
  }
191
192
0
  strm->queue = queue;
193
0
  strm->qbits = qbits;
194
0
}
195
196
0
#define enqueue8 enqueue24
197
198
/* flush the queue and align to next byte */
199
static inline void flush_bits(struct slz_stream *strm)
200
0
{
201
0
  if (strm->qbits > 0)
202
0
    *strm->outbuf++ = strm->queue;
203
204
0
  if (strm->qbits > 8)
205
0
    *strm->outbuf++ = strm->queue >> 8;
206
207
0
  if (strm->qbits > 16)
208
0
    *strm->outbuf++ = strm->queue >> 16;
209
210
0
  if (strm->qbits > 24)
211
0
    *strm->outbuf++ = strm->queue >> 24;
212
213
0
  strm->queue = 0;
214
0
  strm->qbits = 0;
215
0
}
216
217
#else /* non-64 bit or aligned or big endian */
218
219
/* enqueue code x of <xbits> bits (LSB aligned, at most 24) and copy complete
220
 * bytes into out buf. X must not contain non-zero bits above xbits. Prefer
221
 * enqueue8() when xbits is known for being 8 or less.
222
 */
223
static void enqueue24(struct slz_stream *strm, uint32_t x, uint32_t xbits)
224
{
225
  uint32_t queue = strm->queue + (x << strm->qbits);
226
  uint32_t qbits = strm->qbits + xbits;
227
228
  if (qbits >= 16) {
229
#ifndef UNALIGNED_LE_OK
230
    strm->outbuf[0] = queue;
231
    strm->outbuf[1] = queue >> 8;
232
#else
233
    *(uint16_t *)strm->outbuf = queue;
234
#endif
235
    strm->outbuf += 2;
236
    queue >>= 16;
237
    qbits -= 16;
238
  }
239
240
  if (qbits >= 8) {
241
    qbits -= 8;
242
    *strm->outbuf++ = queue;
243
    queue >>= 8;
244
  }
245
  strm->qbits = qbits;
246
  strm->queue = queue;
247
  return;
248
}
249
250
/* enqueue code x of <xbits> bits (at most 8) and copy complete bytes into
251
 * out buf. X must not contain non-zero bits above xbits.
252
 */
253
static inline void enqueue8(struct slz_stream *strm, uint32_t x, uint32_t xbits)
254
{
255
  uint32_t queue = strm->queue + (x << strm->qbits);
256
  uint32_t qbits = strm->qbits + xbits;
257
258
  if (__builtin_expect((signed)(qbits - 8) >= 0, 1)) {
259
    qbits -= 8;
260
    *strm->outbuf++ = queue;
261
    queue >>= 8;
262
  }
263
264
  strm->qbits = qbits;
265
  strm->queue = queue;
266
}
267
268
/* align to next byte */
269
static inline void flush_bits(struct slz_stream *strm)
270
{
271
  if (strm->qbits > 0)
272
    *strm->outbuf++ = strm->queue;
273
274
  if (strm->qbits > 8)
275
    *strm->outbuf++ = strm->queue >> 8;
276
277
  strm->queue = 0;
278
  strm->qbits = 0;
279
}
280
#endif
281
282
283
/* only valid if buffer is already aligned */
284
static inline void copy_8b(struct slz_stream *strm, uint32_t x)
285
0
{
286
0
  *strm->outbuf++ = x;
287
0
}
288
289
/* only valid if buffer is already aligned */
290
static inline void copy_16b(struct slz_stream *strm, uint32_t x)
291
0
{
292
0
  strm->outbuf[0] = x;
293
0
  strm->outbuf[1] = x >> 8;
294
0
  strm->outbuf += 2;
295
0
}
296
297
/* only valid if buffer is already aligned */
298
static inline void copy_32b(struct slz_stream *strm, uint32_t x)
299
0
{
300
0
  strm->outbuf[0] = x;
301
0
  strm->outbuf[1] = x >> 8;
302
0
  strm->outbuf[2] = x >> 16;
303
0
  strm->outbuf[3] = x >> 24;
304
0
  strm->outbuf += 4;
305
0
}
306
307
/* Using long because faster on 64-bit (can save one shift) */
308
static inline void send_huff(struct slz_stream *strm, unsigned long code)
309
0
{
310
0
  uint32_t bits;
311
312
0
  code = fixed_huff[code];
313
0
  bits = code & 15;
314
0
  code >>= 4;
315
0
  enqueue24(strm, code, bits);
316
0
}
317
318
static inline void send_eob(struct slz_stream *strm)
319
0
{
320
0
  enqueue8(strm, 0, 7); // direct encoding of 256 = EOB (cf RFC1951)
321
0
}
322
323
/* copies <len> litterals from <buf>. <more> indicates that there are data past
324
 * buf + <len>. <len> must not be null.
325
 */
326
static void copy_lit(struct slz_stream *strm, const void *buf, uint32_t len, int more)
327
0
{
328
0
  uint32_t len2;
329
330
0
  do {
331
0
    len2 = len;
332
0
    if (__builtin_expect(len2 > 65535, 0))
333
0
      len2 = 65535;
334
335
0
    len -= len2;
336
337
0
    if (strm->state != SLZ_ST_EOB)
338
0
      send_eob(strm);
339
340
0
    strm->state = (more || len) ? SLZ_ST_EOB : SLZ_ST_DONE;
341
342
0
    enqueue8(strm, !(more || len), 3); // BFINAL = !more ; BTYPE = 00
343
0
    flush_bits(strm);
344
0
    copy_16b(strm, len2);  // len2
345
0
    copy_16b(strm, ~len2); // nlen2
346
0
    memcpy(strm->outbuf, buf, len2);
347
0
    buf += len2;
348
0
    strm->outbuf += len2;
349
0
  } while (len);
350
0
}
351
352
/* copies <len> litterals from <buf>. <more> indicates that there are data past
353
 * buf + <len>. <len> must not be null.
354
 */
355
static void copy_lit_huff(struct slz_stream *strm, const unsigned char *buf, uint32_t len, int more)
356
0
{
357
0
  uint32_t pos;
358
359
  /* This ugly construct limits the mount of tests and optimizes for the
360
   * most common case (more > 0).
361
   */
362
0
  if (strm->state == SLZ_ST_EOB) {
363
0
  eob:
364
0
    strm->state = more ? SLZ_ST_FIXED : SLZ_ST_LAST;
365
0
    enqueue8(strm, 2 + !more, 3); // BFINAL = !more ; BTYPE = 01
366
0
  }
367
0
  else if (!more) {
368
0
    send_eob(strm);
369
0
    goto eob;
370
0
  }
371
372
0
  pos = 0;
373
0
  do {
374
0
    send_huff(strm, buf[pos++]);
375
0
  } while (pos < len);
376
0
}
377
378
/* sets <count> BYTES to -32769 in <refs> so that any uninitialized entry will
379
 * verify (pos-last-1 >= 32768) and be ignored. <count> must be a multiple of
380
 * 128 bytes and <refs> must be at least one count in length. It's supposed to
381
 * be applied to 64-bit aligned data exclusively, which makes it slightly
382
 * faster than the regular memset() since no alignment check is performed.
383
 */
384
static void reset_refs(union ref *refs, long count)
385
0
{
386
  /* avoid a shift/mask by casting to void* */
387
0
  union ref *end = (void *)refs + count;
388
389
0
  do {
390
0
    refs[ 0].by64 = -32769;
391
0
    refs[ 1].by64 = -32769;
392
0
    refs[ 2].by64 = -32769;
393
0
    refs[ 3].by64 = -32769;
394
0
    refs[ 4].by64 = -32769;
395
0
    refs[ 5].by64 = -32769;
396
0
    refs[ 6].by64 = -32769;
397
0
    refs[ 7].by64 = -32769;
398
0
    refs[ 8].by64 = -32769;
399
0
    refs[ 9].by64 = -32769;
400
0
    refs[10].by64 = -32769;
401
0
    refs[11].by64 = -32769;
402
0
    refs[12].by64 = -32769;
403
0
    refs[13].by64 = -32769;
404
0
    refs[14].by64 = -32769;
405
0
    refs[15].by64 = -32769;
406
0
    refs += 16;
407
0
  } while (refs < end);
408
0
}
409
410
/* Number of bits wasted by the 9-bit literals above which it becomes
411
 * preferable to send the pending literals as a stored block. It corresponds to
412
 * the cost of leaving the fixed huffman encoding and coming back to it: EOB
413
 * (7 bits) + block type (3 bits) + alignment (up to 7 bits) + LEN and NLEN
414
 * (32 bits) + block type of the next block (3 bits), that is 52 bits. Two
415
 * cheaper variants are needed for the last literals of a block: nothing
416
 * follows the stored block while the huffman encoding still has to send an EOB
417
 * (10 bits less), and if the stream is still in EOB state, no EOB has to be
418
 * sent and the block type is needed in both cases (10 more bits less). Using a
419
 * larger value than these would leave the output larger than the same data
420
 * sent as stored blocks, in violation of the promise made above.
421
 */
422
0
#define SLZ_SWITCH_COST      52
423
0
#define SLZ_LAST_COST        42
424
0
#define SLZ_LAST_COST_EOB    32
425
426
/* Maximum number of bits the fixed huffman encoding is allowed to be behind
427
 * the equivalent stored blocks before the encoder stops trusting the local
428
 * decisions above and falls back to stored blocks only (see <debt> in
429
 * slz_rfc1951_encode_blk()). This bounds by 25 bytes the amount by which a
430
 * stream may exceed the size of the same data sent as stored blocks. It must
431
 * be large enough not to trigger on regular data, where the debt oscillates
432
 * around zero: measured on the 212 MB silesia.tar, no value from 196 up
433
 * changes the output by a single byte, while 52 costs 2331 bytes and 192
434
 * costs 615. It must also leave room for one last group of literals in the
435
 * 8-bit counter that holds the debt, which is why it may not exceed
436
 * 255 - (SLZ_SWITCH_COST - 1) = 204.
437
 */
438
0
#define SLZ_MAX_DEBT        200
439
440
/* Compresses <ilen> bytes from <in> into <out> according to RFC1951. The
441
 * output result may be up to 5 bytes larger than the input for each 65535
442
 * nput bytes, to which 2 extra bytes may be added to send the last chunk due
443
 * to BFINAL+EOB encoding (10 bits) when <more> is not set. This is a property
444
 * of the whole stream, not of each call: since up to 31 bits are retained in
445
 * the queue from one call to the next, a single call may emit up to 5 bytes
446
 * more than its own share, which the following ones will not emit. The caller
447
 * is responsible for ensuring there is enough room in the output buffer for
448
 * this. The amount of output bytes is returned, and no CRC is computed.
449
 */
450
long slz_rfc1951_encode(struct slz_stream *strm, unsigned char *out, const unsigned char *in, long ilen, int more)
451
0
{
452
0
  long rem = ilen;
453
0
  unsigned long pos = 0;
454
0
  unsigned long last;
455
0
  uint32_t word = 0;
456
0
  long mlen;
457
0
  uint32_t h;
458
0
  uint64_t ent;
459
460
0
  uint32_t plit = 0;
461
0
  uint32_t bit9 = 0;
462
0
  uint32_t dist, code;
463
0
  union ref refs[1 << HASH_BITS];
464
465
0
  if (!strm->level) {
466
    /* force to send as literals (eg to preserve CPU) */
467
0
    strm->outbuf = out;
468
0
    plit = pos = ilen;
469
0
    bit9 = 52; /* force literal dump */
470
0
    goto final_lit_dump;
471
0
  }
472
473
0
  reset_refs(refs, sizeof(refs));
474
475
0
  strm->outbuf = out;
476
477
#ifndef UNALIGNED_FASTER
478
  if (rem >= 4)  // <word> is only used inside the loop below, hence the test for >= 4
479
    word = ((uint32_t)(unsigned char)in[pos] << 8) + ((uint32_t)(unsigned char)in[pos + 1] << 16) + ((uint32_t)(unsigned char)in[pos + 2] << 24);
480
#endif
481
0
  while (rem >= 4) {
482
#ifndef UNALIGNED_FASTER
483
    word = ((uint32_t)(unsigned char)in[pos + 3] << 24) + (word >> 8);
484
#else
485
0
    word = *(uint32_t *)&in[pos];
486
0
#endif
487
0
    h = slz_hash(word);
488
0
    asm volatile ("" ::); // prevent gcc from trying to be smart with the prefetch
489
490
0
    if (sizeof(long) >= 8) {
491
0
      ent = refs[h].by64;
492
0
      last = (uint32_t)ent;
493
0
      ent >>= 32;
494
0
      refs[h].by64 = ((uint64_t)pos) + ((uint64_t)word << 32);
495
0
    } else {
496
0
      ent  = refs[h].by32.word;
497
0
      last = refs[h].by32.pos;
498
0
      refs[h].by32.pos = pos;
499
0
      refs[h].by32.word = word;
500
0
    }
501
502
#ifdef FIND_OPTIMAL_MATCH
503
    /* Experimental code to see what could be saved with an ideal
504
     * longest match lookup algorithm. This one is very slow but
505
     * scans the whole window. In short, here are the savings :
506
     *   file        orig     fast(ratio)  optimal(ratio)
507
     *  README       5185    3419 (65.9%)    3165 (61.0%)  -7.5%
508
     *  index.html  76799   35662 (46.4%)   29875 (38.9%) -16.3%
509
     *  rfc1952.c   29383   13442 (45.7%)   11793 (40.1%) -12.3%
510
     *
511
     * Thus the savings to expect for large files is at best 16%.
512
     *
513
     * A non-colliding hash gives 33025 instead of 35662 (-7.4%),
514
     * and keeping the last two entries gives 31724 (-11.0%).
515
     */
516
    unsigned long scan;
517
    int saved = 0;
518
    int bestpos = 0;
519
    int bestlen = 0;
520
    int firstlen = 0;
521
    int max_lookup = 2; // 0 = no limit
522
523
    for (scan = pos - 1; scan < pos && (unsigned long)(pos - scan - 1) < 32768; scan--) {
524
      int len;
525
526
      if (*(uint32_t *)(in + scan) != word)
527
        continue;
528
529
      len = memmatch(in + pos, in + scan, rem);
530
      if (!bestlen)
531
        firstlen = len;
532
533
      if (len > bestlen) {
534
        bestlen = len;
535
        bestpos = scan;
536
      }
537
      if (!--max_lookup)
538
        break;
539
    }
540
    if (bestlen) {
541
      //printf("pos=%d last=%d bestpos=%d word=%08x ent=%08x len=%d\n",
542
      //       (int)pos, (int)last, (int)bestpos, (int)word, (int)ent, bestlen);
543
      last = bestpos;
544
      ent  = word;
545
      saved += bestlen - firstlen;
546
    }
547
    //fprintf(stderr, "first=%d best=%d saved_total=%d\n", firstlen, bestlen, saved);
548
#endif
549
550
0
    if ((uint32_t)ent != word) {
551
0
    send_as_lit:
552
0
      rem--;
553
0
      plit++;
554
0
      bit9 += ((unsigned char)word >= 144);
555
0
      pos++;
556
0
      continue;
557
0
    }
558
559
    /* We reject pos = last and pos > last+32768 */
560
0
    if ((unsigned long)(pos - last - 1) >= 32768)
561
0
      goto send_as_lit;
562
563
    /* Note: cannot encode a length larger than 258 bytes */
564
0
    mlen = memmatch(in + pos + 4, in + last + 4, (rem > 258 ? 258 : rem) - 4) + 4;
565
566
    /* found a matching entry */
567
568
0
    if (bit9 >= 52 && mlen < 6)
569
0
      goto send_as_lit;
570
571
    /* compute the output code, its size and the length's size in
572
     * bits to know if the reference is cheaper than literals.
573
     */
574
0
    code = len_fh[mlen];
575
576
    /* direct mapping of dist->huffman code */
577
0
    dist = fh_dist_table[pos - last - 1];
578
579
    /* If encoding the dist+length is more expensive than sending
580
     * the equivalent as bytes, lets keep the literals. This is
581
     * important for the compression ratio and also for standing by
582
     * our promise that the output is no longer than input + 5 bytes
583
     * every 65535. The explanation is that a valid stream starts in
584
     * EOB and ends in EOB, which is the state where we can grow by
585
     * up to 5 bytes (1 byte for BT, 2 for LEN, 2 for NLEN, then
586
     * literal data). Sending compressed Huffman data (reference or
587
     * fixed encoding) may only be accepted if it is guaranteed that
588
     * it will not represent more bytes in the worst case. Switching
589
     * from EOB to FIXED requires 3 bits of BT. Then either fixed
590
     * data (8 or 9 bits) or references (15-33 bits). Switching back
591
     * to EOB requires EOB (7 bits), and in order to get back to the
592
     * situation where bytes can be added with no overhead, the BT,
593
     * align, LEN and NLEN have to be sent as well:
594
     *
595
     * Before switching:
596
     *          [BT] [ALIGN] [LEN] [NLEN] [PLIT]
597
     *   bits:    3     7     16     16   8*plit
598
     *
599
     * In case of sending mlen bytes as literals:
600
     *          [BT] [ALIGN] [LEN] [NLEN] [PLIT] [MLEN]
601
     *   bits:    3     7     16     16   8*plit 8*mlen
602
     *
603
     * In case of sending mlen bytes as literals, we add:
604
     *       [MLEN]
605
     * bits: 8*mlen
606
     *
607
     * In case of sending reference, we add in the worst case:
608
     *       [BT] [CODE] [DIST] [EOB] [BT] [ALIGN] [LEN] [NLEN]
609
     * bits:  3    clen   dlen    7    3      7      16    16
610
     *
611
     * Thus for literals we add 8*mlen bits, and for reference we
612
     * add clen+dlen+52 bits. If the reference encoding + 52 bits
613
     * is shorter. Of course there are plenty of opportunities to
614
     * be much shorter once we switch to FIXED, and a stricter
615
     * tracking could allow to send references more often. But here
616
     * we at least guarantee that if data fit as literals, they also
617
     * fit using a temporary switch to FIXED.
618
     *
619
     * Regarding encoding size, clen is 7 for mlen 3..10, to 12 for
620
     * mlen 131..257. dlen is 8 for distances 1..4, to 21 for
621
     * distances 16385..32768. Thus mlen <= 130 produces clen+dlen
622
     * <= 32 bits. This means that for mlen 4 or above, the encoded
623
     * reference is always smaller than the data it references. This
624
     * is what guarantees that once switched to FIXED we can stay
625
     * in it for as long as needed.
626
     */
627
0
    if ((strm->state == SLZ_ST_EOB || strm->debt >= SLZ_MAX_DEBT) &&
628
0
        (dist & 0x1f) + (code >> 16) + SLZ_SWITCH_COST > 8 * mlen)
629
0
      goto send_as_lit;
630
631
    /* first, copy pending literals */
632
0
    if (plit) {
633
      /* Huffman encoding requires 9 bits for octets 144..255, so this
634
       * is a waste of space for binary data. Switching between Huffman
635
       * and no-comp then huffman consumes 52 bits (7 for EOB + 3 for
636
       * block type + 7 for alignment + 32 for LEN+NLEN + 3 for next
637
       * block. Only use plain literals if there are more than 52 bits
638
       * to save then, or if we're already too much in debt, in which
639
       * case only stored blocks may be emitted, see <debt> below.
640
       * Literals sent in a stored block do not cost anything extra,
641
       * only those sent in huffman mode add to the debt.
642
       */
643
0
      if (bit9 >= SLZ_SWITCH_COST || strm->debt >= SLZ_MAX_DEBT)
644
0
        copy_lit(strm, in + pos - plit, plit, 1);
645
0
      else {
646
0
        copy_lit_huff(strm, in + pos - plit, plit, 1);
647
0
        strm->debt += bit9;
648
0
      }
649
650
0
      plit = 0;
651
0
    }
652
653
    /* use mode 01 - fixed huffman */
654
0
    if (strm->state == SLZ_ST_EOB) {
655
0
      strm->state = SLZ_ST_FIXED;
656
0
      enqueue8(strm, 0x02, 3); // BTYPE = 01, BFINAL = 0
657
0
    }
658
659
    /* copy the length first */
660
0
    enqueue24(strm, code & 0xFFFF, code >> 16);
661
662
    /* in fixed huffman mode, dist is fixed 5 bits */
663
0
    enqueue24(strm, dist >> 5, dist & 0x1f);
664
665
    /* <bit9> only measures the current group of literals, which is
666
     * what the decisions above compare against, and it restarts
667
     * from zero after each reference. <debt> accumulates how much
668
     * the literals already emitted in fixed huffman mode are still
669
     * costing us compared to the same bytes sent as stored blocks,
670
     * and is what bounds the growth of the output: the reference
671
     * just used (code>>16)+(dist&0x1f) bits in place of the 8*mlen
672
     * bits these bytes would have taken as literals, so it repays
673
     * that much of the debt. Without this, a stream made of series
674
     * of 9-bit literals interleaved with cheap references would
675
     * never reach the threshold above and would keep inflating. The
676
     * debt is saturated at zero since we're not interested in
677
     * accumulating credits. The update is unconditional because a
678
     * test on a debt that is often null but not always turns into
679
     * a mispredicted branch on binary data.
680
     */
681
0
    code = strm->debt + (code >> 16) + (dist & 0x1f);
682
0
    strm->debt = (code > 8 * (uint32_t)mlen) ? code - 8 * (uint32_t)mlen : 0;
683
684
0
    bit9 = 0;
685
0
    rem -= mlen;
686
0
    pos += mlen;
687
688
#ifndef UNALIGNED_FASTER
689
    /* same as before the loop, this is only used when continuing
690
     * in the loop, so let's use the same condition (rem>=4).
691
     */
692
    if (rem >= 4) {
693
#ifdef UNALIGNED_LE_OK
694
      word = *(uint32_t *)&in[pos - 1];
695
#else
696
      word = ((uint32_t)(unsigned char)in[pos] << 8) + ((uint32_t)(unsigned char)in[pos + 1] << 16) + ((uint32_t)(unsigned char)in[pos + 2] << 24);
697
#endif
698
    }
699
#endif
700
0
  }
701
702
0
  if (__builtin_expect(rem, 0)) {
703
    /* we're reading the 1..3 last bytes */
704
0
    plit += rem;
705
0
    do {
706
0
      bit9 += ((unsigned char)in[pos++] >= 144);
707
0
    } while (--rem);
708
0
  }
709
710
0
 final_lit_dump:
711
  /* Now copy remaining literals or mark the end. The cost of switching to
712
   * a stored block depends on the current state and on the presence of
713
   * data after these literals, see the SLZ_*_COST definitions above.
714
   */
715
0
  if (plit) {
716
0
    uint32_t cost;
717
718
0
    if (more)
719
0
      cost = SLZ_SWITCH_COST;
720
0
    else
721
0
      cost = (strm->state == SLZ_ST_EOB) ? SLZ_LAST_COST_EOB : SLZ_LAST_COST;
722
723
0
    if (bit9 >= cost || strm->debt >= SLZ_MAX_DEBT)
724
0
      copy_lit(strm, in + pos - plit, plit, more);
725
0
    else
726
0
      copy_lit_huff(strm, in + pos - plit, plit, more);
727
728
0
    plit = 0;
729
0
  }
730
731
0
  strm->ilen += ilen;
732
0
  return strm->outbuf - out;
733
0
}
734
735
/* Initializes stream <strm> for use with raw deflate (rfc1951). The CRC is
736
 * unused but set to zero. The compression level passed in <level> is set. This
737
 * value can only be 0 (no compression) or 1 (compression) and other values
738
 * will lead to unpredictable behaviour. The function always returns 0.
739
 */
740
int slz_rfc1951_init(struct slz_stream *strm, int level)
741
0
{
742
0
  strm->state = SLZ_ST_EOB; // no header
743
0
  strm->level = level;
744
0
  strm->format = SLZ_FMT_DEFLATE;
745
0
  strm->crc32 = 0;
746
0
  strm->ilen  = 0;
747
0
  strm->qbits = 0;
748
0
  strm->queue = 0;
749
0
  strm->debt  = 0;
750
0
  return 0;
751
0
}
752
753
/* Flushes any pending data for stream <strm> into buffer <buf>, then emits an
754
 * empty literal block to byte-align the output, allowing to completely flush
755
 * the queue. This requires that the output buffer still has the size of the
756
 * queue (up to 31 bits when using the 64-bit queue), plus a possible EOB (7
757
 * bits), plus (BFINAL,BTYPE) (3 bits), which once rounded up to the next byte
758
 * make 6 bytes, plus 4 bytes for LEN+NLEN, or a total of 10 bytes in the worst
759
 * case. If the stream was already completed by a previous call to encode()
760
 * with <more> cleared, the last block is simply terminated and the output
761
 * aligned, since nothing may be appended to a finished stream. The number of
762
 * bytes emitted is returned. It is guaranteed that the queue is empty on
763
 * return. This may cause some overhead by adding needless 5-byte blocks if
764
 * called to often.
765
 */
766
int slz_rfc1951_flush(struct slz_stream *strm, unsigned char *buf)
767
0
{
768
0
  strm->outbuf = buf;
769
770
  /* The queue is always empty on INIT, DONE, and END */
771
0
  if (!strm->qbits)
772
0
    return 0;
773
774
  /* we may need to terminate a huffman output. Lit is always in EOB state */
775
0
  if (strm->state != SLZ_ST_EOB) {
776
0
    strm->state = (strm->state == SLZ_ST_LAST) ? SLZ_ST_DONE : SLZ_ST_EOB;
777
0
    send_eob(strm);
778
0
  }
779
780
0
  if (strm->state == SLZ_ST_DONE) {
781
    /* The block we've just terminated was already marked final, so
782
     * the deflate stream is complete and nothing may be appended to
783
     * it: an extra block here would be located past the end of the
784
     * stream and would shift the gzip or zlib trailer that the
785
     * caller is about to emit. Aligning the output is all we have
786
     * to do, and it's all that's left to do for finish() as well.
787
     */
788
0
    flush_bits(strm);
789
0
    return strm->outbuf - buf;
790
0
  }
791
792
  /* send BFINAL=0 and BTYPE=00 (lit) */
793
0
  enqueue8(strm, 0, 3);
794
0
  flush_bits(strm);             // emit pending bits
795
0
  copy_32b(strm, 0xFFFF0000U);  // len=0, nlen=~0
796
797
  /* Now the queue is empty, EOB was sent, and a zero-byte block was sent
798
   * to byte-align the output. The last state reflects all this. Let's
799
   * just return the number of bytes added to the output buffer.
800
   */
801
0
  return strm->outbuf - buf;
802
0
}
803
804
/* Flushes any pending for stream <strm> into buffer <buf>, then sends BTYPE=1
805
 * and BFINAL=1 if needed. The stream ends in SLZ_ST_DONE. It returns the number
806
 * of bytes emitted. The trailer consists in flushing the possibly pending bits
807
 * from the queue (up to 31 bits when using the 64-bit queue), then possibly
808
 * EOB (7 bits), then 3 bits, EOB, a rounding to the next byte, which amounts
809
 * to a total of 6 bytes max, that the caller must ensure are available before
810
 * calling the function.
811
 */
812
int slz_rfc1951_finish(struct slz_stream *strm, unsigned char *buf)
813
0
{
814
0
  strm->outbuf = buf;
815
816
0
  if (strm->state == SLZ_ST_FIXED || strm->state == SLZ_ST_LAST) {
817
0
    strm->state = (strm->state == SLZ_ST_LAST) ? SLZ_ST_DONE : SLZ_ST_EOB;
818
0
    send_eob(strm);
819
0
  }
820
821
0
  if (strm->state != SLZ_ST_DONE) {
822
    /* send BTYPE=1, BFINAL=1 */
823
0
    enqueue8(strm, 3, 3);
824
0
    send_eob(strm);
825
0
    strm->state = SLZ_ST_DONE;
826
0
  }
827
828
0
  flush_bits(strm);
829
0
  return strm->outbuf - buf;
830
0
}
831
832
/* Now RFC1952-specific declarations and extracts from RFC.
833
 * From RFC1952 about the GZIP file format :
834
835
A gzip file consists of a series of "members" ...
836
837
2.3. Member format
838
839
      Each member has the following structure:
840
841
         +---+---+---+---+---+---+---+---+---+---+
842
         |ID1|ID2|CM |FLG|     MTIME     |XFL|OS | (more-->)
843
         +---+---+---+---+---+---+---+---+---+---+
844
845
      (if FLG.FEXTRA set)
846
847
         +---+---+=================================+
848
         | XLEN  |...XLEN bytes of "extra field"...| (more-->)
849
         +---+---+=================================+
850
851
      (if FLG.FNAME set)
852
853
         +=========================================+
854
         |...original file name, zero-terminated...| (more-->)
855
         +=========================================+
856
857
      (if FLG.FCOMMENT set)
858
859
         +===================================+
860
         |...file comment, zero-terminated...| (more-->)
861
         +===================================+
862
863
      (if FLG.FHCRC set)
864
865
         +---+---+
866
         | CRC16 |
867
         +---+---+
868
869
         +=======================+
870
         |...compressed blocks...| (more-->)
871
         +=======================+
872
873
           0   1   2   3   4   5   6   7
874
         +---+---+---+---+---+---+---+---+
875
         |     CRC32     |     ISIZE     |
876
         +---+---+---+---+---+---+---+---+
877
878
879
2.3.1. Member header and trailer
880
881
         ID1 (IDentification 1)
882
         ID2 (IDentification 2)
883
            These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139
884
            (0x8b, \213), to identify the file as being in gzip format.
885
886
         CM (Compression Method)
887
            This identifies the compression method used in the file.  CM
888
            = 0-7 are reserved.  CM = 8 denotes the "deflate"
889
            compression method, which is the one customarily used by
890
            gzip and which is documented elsewhere.
891
892
         FLG (FLaGs)
893
            This flag byte is divided into individual bits as follows:
894
895
               bit 0   FTEXT
896
               bit 1   FHCRC
897
               bit 2   FEXTRA
898
               bit 3   FNAME
899
               bit 4   FCOMMENT
900
               bit 5   reserved
901
               bit 6   reserved
902
               bit 7   reserved
903
904
            Reserved FLG bits must be zero.
905
906
         MTIME (Modification TIME)
907
            This gives the most recent modification time of the original
908
            file being compressed.  The time is in Unix format, i.e.,
909
            seconds since 00:00:00 GMT, Jan.  1, 1970.  (Note that this
910
            may cause problems for MS-DOS and other systems that use
911
            local rather than Universal time.)  If the compressed data
912
            did not come from a file, MTIME is set to the time at which
913
            compression started.  MTIME = 0 means no time stamp is
914
            available.
915
916
         XFL (eXtra FLags)
917
            These flags are available for use by specific compression
918
            methods.  The "deflate" method (CM = 8) sets these flags as
919
            follows:
920
921
               XFL = 2 - compressor used maximum compression,
922
                         slowest algorithm
923
               XFL = 4 - compressor used fastest algorithm
924
925
         OS (Operating System)
926
            This identifies the type of file system on which compression
927
            took place.  This may be useful in determining end-of-line
928
            convention for text files.  The currently defined values are
929
            as follows:
930
931
                 0 - FAT filesystem (MS-DOS, OS/2, NT/Win32)
932
                 1 - Amiga
933
                 2 - VMS (or OpenVMS)
934
                 3 - Unix
935
                 4 - VM/CMS
936
                 5 - Atari TOS
937
                 6 - HPFS filesystem (OS/2, NT)
938
                 7 - Macintosh
939
                 8 - Z-System
940
                 9 - CP/M
941
                10 - TOPS-20
942
                11 - NTFS filesystem (NT)
943
                12 - QDOS
944
                13 - Acorn RISCOS
945
               255 - unknown
946
947
 ==> A file compressed using "gzip -1" on Unix-like systems can be :
948
949
        1F 8B 08 00  00 00 00 00  04 03
950
        <deflate-compressed stream>
951
        crc32 size32
952
*/
953
954
static const unsigned char gzip_hdr[] = { 0x1F, 0x8B,   // ID1, ID2
955
                                          0x08, 0x00,   // Deflate, flags (none)
956
                                          0x00, 0x00, 0x00, 0x00, // mtime: none
957
                                          0x04, 0x03 }; // fastest comp, OS=Unix
958
959
/* Sends the gzip header for stream <strm> into buffer <buf>. When it's done,
960
 * the stream state is updated to SLZ_ST_EOB. It returns the number of bytes
961
 * emitted which is always 10. The caller is responsible for ensuring there's
962
 * always enough room in the buffer.
963
 */
964
int slz_rfc1952_send_header(struct slz_stream *strm, unsigned char *buf)
965
0
{
966
0
  memcpy(buf, gzip_hdr, sizeof(gzip_hdr));
967
0
  strm->state = SLZ_ST_EOB;
968
0
  return sizeof(gzip_hdr);
969
0
}
970
971
/* Encodes the block according to rfc1952. This means that the CRC of the input
972
 * block is computed according to the CRC32 algorithm. If the header was never
973
 * sent, it may be sent first. The number of output bytes is returned.
974
 */
975
long slz_rfc1952_encode(struct slz_stream *strm, unsigned char *out, const unsigned char *in, long ilen, int more)
976
0
{
977
0
  long ret = 0;
978
979
0
  if (__builtin_expect(strm->state == SLZ_ST_INIT, 0))
980
0
    ret += slz_rfc1952_send_header(strm, out);
981
982
0
  strm->crc32 = update_crc(strm->crc32, in, ilen);
983
0
  ret += slz_rfc1951_encode(strm, out + ret, in, ilen, more);
984
0
  return ret;
985
0
}
986
987
/* Initializes stream <strm> for use with the gzip format (rfc1952). The
988
 * compression level passed in <level> is set. This value can only be 0 (no
989
 * compression) or 1 (compression) and other values will lead to unpredictable
990
 * behaviour. The function always returns 0.
991
 */
992
int slz_rfc1952_init(struct slz_stream *strm, int level)
993
0
{
994
0
  strm->state  = SLZ_ST_INIT;
995
0
  strm->level  = level;
996
0
  strm->format = SLZ_FMT_GZIP;
997
0
  strm->crc32  = 0;
998
0
  strm->ilen   = 0;
999
0
  strm->qbits  = 0;
1000
0
  strm->queue  = 0;
1001
0
  strm->debt   = 0;
1002
0
  return 0;
1003
0
}
1004
1005
/* Flushes any pending data for stream <strm> into buffer <buf>, then emits an
1006
 * empty literal block to byte-align the output, allowing to completely flush
1007
 * the queue. Note that if the initial header was never sent, it will be sent
1008
 * first as well (10 extra bytes). This requires that the output buffer still
1009
 * has this plus the 6 bytes needed to flush the queue, the possible EOB and
1010
 * the (BFINAL,BTYPE) bits, plus 4 bytes for LEN+NLEN, or a total of 20 bytes
1011
 * in the worst case. The number of bytes emitted is returned. It is guaranteed
1012
 * that the queue is empty on return. This may cause some overhead by adding
1013
 * needless 5-byte blocks if called to often.
1014
 */
1015
int slz_rfc1952_flush(struct slz_stream *strm, unsigned char *buf)
1016
0
{
1017
0
  int sent = 0;
1018
1019
0
  if (__builtin_expect(strm->state == SLZ_ST_INIT, 0))
1020
0
    sent = slz_rfc1952_send_header(strm, buf);
1021
1022
0
  sent += slz_rfc1951_flush(strm, buf + sent);
1023
0
  return sent;
1024
0
}
1025
1026
/* Flushes pending bits and sends the gzip trailer for stream <strm> into
1027
 * buffer <buf>. When it's done, the stream state is updated to SLZ_ST_END. It
1028
 * returns the number of bytes emitted. The trailer consists in flushing the
1029
 * possibly pending bits from the queue, the possible EOB and the final empty
1030
 * block, rounding to the next byte, then 4 bytes for the CRC and another 4
1031
 * bytes for the input length. That may amount to 6+4+4 = 14 bytes, that the
1032
 * caller must ensure are available before calling the function. Note that if
1033
 * the initial header was never sent, it will be sent first as well (10 extra
1034
 * bytes).
1035
 */
1036
int slz_rfc1952_finish(struct slz_stream *strm, unsigned char *buf)
1037
0
{
1038
0
  strm->outbuf = buf;
1039
1040
0
  if (__builtin_expect(strm->state == SLZ_ST_INIT, 0))
1041
0
    strm->outbuf += slz_rfc1952_send_header(strm, strm->outbuf);
1042
1043
0
  slz_rfc1951_finish(strm, strm->outbuf);
1044
0
  copy_32b(strm, strm->crc32);
1045
0
  copy_32b(strm, strm->ilen);
1046
0
  strm->state = SLZ_ST_END;
1047
1048
0
  return strm->outbuf - buf;
1049
0
}
1050
1051
1052
/* RFC1950-specific stuff. This is for the Zlib stream format.
1053
 * From RFC1950 (zlib) :
1054
 *
1055
1056
   2.2. Data format
1057
1058
      A zlib stream has the following structure:
1059
1060
           0   1
1061
         +---+---+
1062
         |CMF|FLG|   (more-->)
1063
         +---+---+
1064
1065
1066
      (if FLG.FDICT set)
1067
1068
           0   1   2   3
1069
         +---+---+---+---+
1070
         |     DICTID    |   (more-->)
1071
         +---+---+---+---+
1072
1073
         +=====================+---+---+---+---+
1074
         |...compressed data...|    ADLER32    |
1075
         +=====================+---+---+---+---+
1076
1077
      Any data which may appear after ADLER32 are not part of the zlib
1078
      stream.
1079
1080
      CMF (Compression Method and flags)
1081
         This byte is divided into a 4-bit compression method and a 4-
1082
         bit information field depending on the compression method.
1083
1084
            bits 0 to 3  CM     Compression method
1085
            bits 4 to 7  CINFO  Compression info
1086
1087
      CM (Compression method)
1088
         This identifies the compression method used in the file. CM = 8
1089
         denotes the "deflate" compression method with a window size up
1090
         to 32K.  This is the method used by gzip and PNG (see
1091
         references [1] and [2] in Chapter 3, below, for the reference
1092
         documents).  CM = 15 is reserved.  It might be used in a future
1093
         version of this specification to indicate the presence of an
1094
         extra field before the compressed data.
1095
1096
      CINFO (Compression info)
1097
         For CM = 8, CINFO is the base-2 logarithm of the LZ77 window
1098
         size, minus eight (CINFO=7 indicates a 32K window size). Values
1099
         of CINFO above 7 are not allowed in this version of the
1100
         specification.  CINFO is not defined in this specification for
1101
         CM not equal to 8.
1102
1103
      FLG (FLaGs)
1104
         This flag byte is divided as follows:
1105
1106
            bits 0 to 4  FCHECK  (check bits for CMF and FLG)
1107
            bit  5       FDICT   (preset dictionary)
1108
            bits 6 to 7  FLEVEL  (compression level)
1109
1110
         The FCHECK value must be such that CMF and FLG, when viewed as
1111
         a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG),
1112
         is a multiple of 31.
1113
1114
1115
      FDICT (Preset dictionary)
1116
         If FDICT is set, a DICT dictionary identifier is present
1117
         immediately after the FLG byte. The dictionary is a sequence of
1118
         bytes which are initially fed to the compressor without
1119
         producing any compressed output. DICT is the Adler-32 checksum
1120
         of this sequence of bytes (see the definition of ADLER32
1121
         below).  The decompressor can use this identifier to determine
1122
         which dictionary has been used by the compressor.
1123
1124
      FLEVEL (Compression level)
1125
         These flags are available for use by specific compression
1126
         methods.  The "deflate" method (CM = 8) sets these flags as
1127
         follows:
1128
1129
            0 - compressor used fastest algorithm
1130
            1 - compressor used fast algorithm
1131
            2 - compressor used default algorithm
1132
            3 - compressor used maximum compression, slowest algorithm
1133
1134
         The information in FLEVEL is not needed for decompression; it
1135
         is there to indicate if recompression might be worthwhile.
1136
1137
      compressed data
1138
         For compression method 8, the compressed data is stored in the
1139
         deflate compressed data format as described in the document
1140
         "DEFLATE Compressed Data Format Specification" by L. Peter
1141
         Deutsch. (See reference [3] in Chapter 3, below)
1142
1143
         Other compressed data formats are not specified in this version
1144
         of the zlib specification.
1145
1146
      ADLER32 (Adler-32 checksum)
1147
         This contains a checksum value of the uncompressed data
1148
         (excluding any dictionary data) computed according to Adler-32
1149
         algorithm. This algorithm is a 32-bit extension and improvement
1150
         of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073
1151
         standard. See references [4] and [5] in Chapter 3, below)
1152
1153
         Adler-32 is composed of two sums accumulated per byte: s1 is
1154
         the sum of all bytes, s2 is the sum of all s1 values. Both sums
1155
         are done modulo 65521. s1 is initialized to 1, s2 to zero.  The
1156
         Adler-32 checksum is stored as s2*65536 + s1 in most-
1157
         significant-byte first (network) order.
1158
1159
  ==> The stream can start with only 2 bytes :
1160
        - CM  = 0x78 : CMINFO=7 (32kB window),  CM=8 (deflate)
1161
        - FLG = 0x01 : FLEVEL = 0 (fastest), FDICT=0 (no dict), FCHECK=1 so
1162
          that 0x7801 is a multiple of 31 (30721 = 991 * 31).
1163
1164
  ==> and it ends with only 4 bytes, the Adler-32 checksum in big-endian format.
1165
1166
 */
1167
1168
static const unsigned char zlib_hdr[] = { 0x78, 0x01 };   // 32k win, deflate, chk=1
1169
1170
/* Sends the zlib header for stream <strm> into buffer <buf>. When it's done,
1171
 * the stream state is updated to SLZ_ST_EOB. It returns the number of bytes
1172
 * emitted which is always 2. The caller is responsible for ensuring there's
1173
 * always enough room in the buffer.
1174
 */
1175
int slz_rfc1950_send_header(struct slz_stream *strm, unsigned char *buf)
1176
0
{
1177
0
  memcpy(buf, zlib_hdr, sizeof(zlib_hdr));
1178
0
  strm->state = SLZ_ST_EOB;
1179
0
  return sizeof(zlib_hdr);
1180
0
}
1181
1182
/* Encodes the block according to rfc1950. This means that the CRC of the input
1183
 * block is computed according to the ADLER32 algorithm. If the header was never
1184
 * sent, it may be sent first. The number of output bytes is returned.
1185
 */
1186
long slz_rfc1950_encode(struct slz_stream *strm, unsigned char *out, const unsigned char *in, long ilen, int more)
1187
0
{
1188
0
  long ret = 0;
1189
1190
0
  if (__builtin_expect(strm->state == SLZ_ST_INIT, 0))
1191
0
    ret += slz_rfc1950_send_header(strm, out);
1192
1193
0
  strm->crc32 = slz_adler32_block(strm->crc32, in, ilen);
1194
0
  ret += slz_rfc1951_encode(strm, out + ret, in, ilen, more);
1195
0
  return ret;
1196
0
}
1197
1198
/* Initializes stream <strm> for use with the zlib format (rfc1950). The
1199
 * compression level passed in <level> is set. This value can only be 0 (no
1200
 * compression) or 1 (compression) and other values will lead to unpredictable
1201
 * behaviour. The function always returns 0.
1202
 */
1203
int slz_rfc1950_init(struct slz_stream *strm, int level)
1204
0
{
1205
0
  strm->state  = SLZ_ST_INIT;
1206
0
  strm->level  = level;
1207
0
  strm->format = SLZ_FMT_ZLIB;
1208
0
  strm->crc32  = 1; // rfc1950/zlib starts with initial crc=1
1209
0
  strm->ilen   = 0;
1210
0
  strm->qbits  = 0;
1211
0
  strm->queue  = 0;
1212
0
  strm->debt   = 0;
1213
0
  return 0;
1214
0
}
1215
1216
/* Flushes any pending data for stream <strm> into buffer <buf>, then emits an
1217
 * empty literal block to byte-align the output, allowing to completely flush
1218
 * the queue. Note that if the initial header was never sent, it will be sent
1219
 * first as well (2 extra bytes). This requires that the output buffer still
1220
 * has this plus the 6 bytes needed to flush the queue, the possible EOB and
1221
 * the (BFINAL,BTYPE) bits, plus 4 bytes for LEN+NLEN, or a total of 12 bytes
1222
 * in the worst case. The number of bytes emitted is returned. It is guaranteed
1223
 * that the queue is empty on return. This may cause some overhead by adding
1224
 * needless 5-byte blocks if called to often.
1225
 */
1226
int slz_rfc1950_flush(struct slz_stream *strm, unsigned char *buf)
1227
0
{
1228
0
  int sent = 0;
1229
1230
0
  if (__builtin_expect(strm->state == SLZ_ST_INIT, 0))
1231
0
    sent = slz_rfc1950_send_header(strm, buf);
1232
1233
0
  sent += slz_rfc1951_flush(strm, buf + sent);
1234
0
  return sent;
1235
0
}
1236
1237
/* Flushes pending bits and sends the gzip trailer for stream <strm> into
1238
 * buffer <buf>. When it's done, the stream state is updated to SLZ_ST_END. It
1239
 * returns the number of bytes emitted. The trailer consists in flushing the
1240
 * possibly pending bits from the queue, the possible EOB and the final empty
1241
 * block, rounding to the next byte, then 4 bytes for the CRC. That may amount
1242
 * to 6+4 = 10 bytes, that the caller must ensure are available before calling
1243
 * the function. Note that if the initial header was never sent, it will be
1244
 * sent first as well (2 extra bytes).
1245
 */
1246
int slz_rfc1950_finish(struct slz_stream *strm, unsigned char *buf)
1247
0
{
1248
0
  strm->outbuf = buf;
1249
1250
0
  if (__builtin_expect(strm->state == SLZ_ST_INIT, 0))
1251
0
    strm->outbuf += slz_rfc1950_send_header(strm, strm->outbuf);
1252
1253
0
  slz_rfc1951_finish(strm, strm->outbuf);
1254
0
  copy_8b(strm, (strm->crc32 >> 24) & 0xff);
1255
0
  copy_8b(strm, (strm->crc32 >> 16) & 0xff);
1256
0
  copy_8b(strm, (strm->crc32 >>  8) & 0xff);
1257
0
  copy_8b(strm, (strm->crc32 >>  0) & 0xff);
1258
0
  strm->state = SLZ_ST_END;
1259
0
  return strm->outbuf - buf;
1260
0
}
1261
1262
/* Returns code for lengths 1 to 32768. The bit size for the next value can be
1263
 * found this way :
1264
 *
1265
 *  bits = code >> 1;
1266
 *  if (bits)
1267
 *    bits--;
1268
 *
1269
 */
1270
static inline uint32_t dist_to_code(uint32_t l)
1271
65.5k
{
1272
65.5k
  uint32_t code;
1273
1274
65.5k
  code = 0;
1275
65.5k
  switch (l) {
1276
16.3k
  case 24577 ... 32768: code++; __fallthrough;
1277
32.7k
  case 16385 ... 24576: code++; __fallthrough;
1278
40.9k
  case 12289 ... 16384: code++; __fallthrough;
1279
49.1k
  case  8193 ... 12288: code++; __fallthrough;
1280
53.2k
  case  6145 ...  8192: code++; __fallthrough;
1281
57.3k
  case  4097 ...  6144: code++; __fallthrough;
1282
59.3k
  case  3073 ...  4096: code++; __fallthrough;
1283
61.4k
  case  2049 ...  3072: code++; __fallthrough;
1284
62.4k
  case  1537 ...  2048: code++; __fallthrough;
1285
63.4k
  case  1025 ...  1536: code++; __fallthrough;
1286
64.0k
  case   769 ...  1024: code++; __fallthrough;
1287
64.5k
  case   513 ...   768: code++; __fallthrough;
1288
64.7k
  case   385 ...   512: code++; __fallthrough;
1289
65.0k
  case   257 ...   384: code++; __fallthrough;
1290
65.1k
  case   193 ...   256: code++; __fallthrough;
1291
65.2k
  case   129 ...   192: code++; __fallthrough;
1292
65.3k
  case    97 ...   128: code++; __fallthrough;
1293
65.4k
  case    65 ...    96: code++; __fallthrough;
1294
65.4k
  case    49 ...    64: code++; __fallthrough;
1295
65.4k
  case    33 ...    48: code++; __fallthrough;
1296
65.4k
  case    25 ...    32: code++; __fallthrough;
1297
65.5k
  case    17 ...    24: code++; __fallthrough;
1298
65.5k
  case    13 ...    16: code++; __fallthrough;
1299
65.5k
  case     9 ...    12: code++; __fallthrough;
1300
65.5k
  case     7 ...     8: code++; __fallthrough;
1301
65.5k
  case     5 ...     6: code++; __fallthrough;
1302
65.5k
  case     4          : code++; __fallthrough;
1303
65.5k
  case     3          : code++; __fallthrough;
1304
65.5k
  case     2          : code++;
1305
65.5k
  }
1306
1307
65.5k
  return code;
1308
65.5k
}
1309
1310
/* not thread-safe, must be called exactly once */
1311
static inline void __slz_prepare_dist_table()
1312
2
{
1313
2
#ifndef PRECOMPUTE_TABLES
1314
2
  uint32_t dist;
1315
2
  uint32_t code;
1316
2
  uint32_t bits;
1317
1318
65.5k
  for (dist = 0; dist < sizeof(fh_dist_table) / sizeof(*fh_dist_table); dist++) {
1319
65.5k
    code = dist_to_code(dist + 1);
1320
65.5k
    bits = code >> 1;
1321
65.5k
    if (bits)
1322
65.5k
      bits--;
1323
1324
    /* Distance codes are stored on 5 bits reversed. The RFC
1325
     * doesn't state that they are reversed, but it's the only
1326
     * way it works.
1327
     */
1328
65.5k
    code = ((code & 0x01) << 4) | ((code & 0x02) << 2) |
1329
65.5k
           (code & 0x04) |
1330
65.5k
           ((code & 0x08) >> 2) | ((code & 0x10) >> 4);
1331
1332
65.5k
    code += (dist & ((1 << bits) - 1)) << 5;
1333
65.5k
    fh_dist_table[dist] = (code << 5) + bits + 5;
1334
65.5k
  }
1335
2
#endif
1336
2
}
1337
1338
__attribute__((constructor))
1339
static void __slz_initialize(void)
1340
2
{
1341
2
  __slz_prepare_dist_table(); // used by slz_rfc1951_encode()
1342
2
}