Coverage Report

Created: 2026-06-30 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/duckdb/third_party/brotli/enc/compress_fragment.cpp
Line
Count
Source
1
/* Copyright 2015 Google Inc. All Rights Reserved.
2
3
   Distributed under MIT license.
4
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5
*/
6
7
/* Function for fast encoding of an input fragment, independently from the input
8
   history. This function uses one-pass processing: when we find a backward
9
   match, we immediately emit the corresponding command and literal codes to
10
   the bit stream.
11
12
   Adapted from the CompressFragment() function in
13
   https://github.com/google/snappy/blob/master/snappy.cc */
14
15
#include "compress_fragment.h"
16
17
#include <string.h>  /* memcmp, memcpy, memset */
18
19
#include <brotli/types.h>
20
21
#include "../common/brotli_platform.h"
22
#include "brotli_bit_stream.h"
23
#include "entropy_encode.h"
24
#include "fast_log.h"
25
#include "find_match_length.h"
26
#include "write_bits.h"
27
28
using namespace duckdb_brotli;
29
30
0
#define MAX_DISTANCE (long)BROTLI_MAX_BACKWARD_LIMIT(18)
31
32
/* kHashMul32 multiplier has these properties:
33
   * The multiplier must be odd. Otherwise we may lose the highest bit.
34
   * No long streaks of ones or zeros.
35
   * There is no effort to ensure that it is a prime, the oddity is enough
36
     for this use.
37
   * The number has been tuned heuristically against compression benchmarks. */
38
static const uint32_t kHashMul32 = 0x1E35A7BD;
39
40
0
static BROTLI_INLINE uint32_t Hash(const uint8_t* p, size_t shift) {
41
0
  const uint64_t h = (BROTLI_UNALIGNED_LOAD64LE(p) << 24) * kHashMul32;
42
0
  return (uint32_t)(h >> shift);
43
0
}
44
45
static BROTLI_INLINE uint32_t HashBytesAtOffset(
46
0
    uint64_t v, int offset, size_t shift) {
47
0
  BROTLI_DCHECK(offset >= 0);
48
0
  BROTLI_DCHECK(offset <= 3);
49
0
  {
50
0
    const uint64_t h = ((v >> (8 * offset)) << 24) * kHashMul32;
51
0
    return (uint32_t)(h >> shift);
52
0
  }
53
0
}
54
55
0
static BROTLI_INLINE BROTLI_BOOL IsMatch(const uint8_t* p1, const uint8_t* p2) {
56
0
  return TO_BROTLI_BOOL(
57
0
      BrotliUnalignedRead32(p1) == BrotliUnalignedRead32(p2) &&
58
0
      p1[4] == p2[4]);
59
0
}
60
61
/* Builds a literal prefix code into "depths" and "bits" based on the statistics
62
   of the "input" string and stores it into the bit stream.
63
   Note that the prefix code here is built from the pre-LZ77 input, therefore
64
   we can only approximate the statistics of the actual literal stream.
65
   Moreover, for long inputs we build a histogram from a sample of the input
66
   and thus have to assign a non-zero depth for each literal.
67
   Returns estimated compression ratio millibytes/char for encoding given input
68
   with generated code. */
69
static size_t BuildAndStoreLiteralPrefixCode(BrotliOnePassArena* s,
70
                                             const uint8_t* input,
71
                                             const size_t input_size,
72
                                             uint8_t depths[256],
73
                                             uint16_t bits[256],
74
                                             size_t* storage_ix,
75
0
                                             uint8_t* storage) {
76
0
  uint32_t* BROTLI_RESTRICT const histogram = s->histogram;
77
0
  size_t histogram_total;
78
0
  size_t i;
79
0
  memset(histogram, 0, sizeof(s->histogram));
80
81
0
  if (input_size < (1 << 15)) {
82
0
    for (i = 0; i < input_size; ++i) {
83
0
      ++histogram[input[i]];
84
0
    }
85
0
    histogram_total = input_size;
86
0
    for (i = 0; i < 256; ++i) {
87
      /* We weigh the first 11 samples with weight 3 to account for the
88
         balancing effect of the LZ77 phase on the histogram. */
89
0
      const uint32_t adjust = 2 * BROTLI_MIN(uint32_t, histogram[i], 11u);
90
0
      histogram[i] += adjust;
91
0
      histogram_total += adjust;
92
0
    }
93
0
  } else {
94
0
    static const size_t kSampleRate = 29;
95
0
    for (i = 0; i < input_size; i += kSampleRate) {
96
0
      ++histogram[input[i]];
97
0
    }
98
0
    histogram_total = (input_size + kSampleRate - 1) / kSampleRate;
99
0
    for (i = 0; i < 256; ++i) {
100
      /* We add 1 to each population count to avoid 0 bit depths (since this is
101
         only a sample and we don't know if the symbol appears or not), and we
102
         weigh the first 11 samples with weight 3 to account for the balancing
103
         effect of the LZ77 phase on the histogram (more frequent symbols are
104
         more likely to be in backward references instead as literals). */
105
0
      const uint32_t adjust = 1 + 2 * BROTLI_MIN(uint32_t, histogram[i], 11u);
106
0
      histogram[i] += adjust;
107
0
      histogram_total += adjust;
108
0
    }
109
0
  }
110
0
  BrotliBuildAndStoreHuffmanTreeFast(s->tree, histogram, histogram_total,
111
0
                                     /* max_bits = */ 8,
112
0
                                     depths, bits, storage_ix, storage);
113
0
  {
114
0
    size_t literal_ratio = 0;
115
0
    for (i = 0; i < 256; ++i) {
116
0
      if (histogram[i]) literal_ratio += histogram[i] * depths[i];
117
0
    }
118
    /* Estimated encoding ratio, millibytes per symbol. */
119
0
    return (literal_ratio * 125) / histogram_total;
120
0
  }
121
0
}
122
123
/* Builds a command and distance prefix code (each 64 symbols) into "depth" and
124
   "bits" based on "histogram" and stores it into the bit stream. */
125
static void BuildAndStoreCommandPrefixCode(BrotliOnePassArena* s,
126
0
    size_t* storage_ix, uint8_t* storage) {
127
0
  const uint32_t* const histogram = s->cmd_histo;
128
0
  uint8_t* const depth = s->cmd_depth;
129
0
  uint16_t* const bits = s->cmd_bits;
130
0
  uint8_t* BROTLI_RESTRICT const tmp_depth = s->tmp_depth;
131
0
  uint16_t* BROTLI_RESTRICT const tmp_bits = s->tmp_bits;
132
  /* TODO(eustas): do only once on initialization. */
133
0
  memset(tmp_depth, 0, BROTLI_NUM_COMMAND_SYMBOLS);
134
135
0
  BrotliCreateHuffmanTree(histogram, 64, 15, s->tree, depth);
136
0
  BrotliCreateHuffmanTree(&histogram[64], 64, 14, s->tree, &depth[64]);
137
  /* We have to jump through a few hoops here in order to compute
138
     the command bits because the symbols are in a different order than in
139
     the full alphabet. This looks complicated, but having the symbols
140
     in this order in the command bits saves a few branches in the Emit*
141
     functions. */
142
0
  memcpy(tmp_depth, depth, 24);
143
0
  memcpy(tmp_depth + 24, depth + 40, 8);
144
0
  memcpy(tmp_depth + 32, depth + 24, 8);
145
0
  memcpy(tmp_depth + 40, depth + 48, 8);
146
0
  memcpy(tmp_depth + 48, depth + 32, 8);
147
0
  memcpy(tmp_depth + 56, depth + 56, 8);
148
0
  BrotliConvertBitDepthsToSymbols(tmp_depth, 64, tmp_bits);
149
0
  memcpy(bits, tmp_bits, 48);
150
0
  memcpy(bits + 24, tmp_bits + 32, 16);
151
0
  memcpy(bits + 32, tmp_bits + 48, 16);
152
0
  memcpy(bits + 40, tmp_bits + 24, 16);
153
0
  memcpy(bits + 48, tmp_bits + 40, 16);
154
0
  memcpy(bits + 56, tmp_bits + 56, 16);
155
0
  BrotliConvertBitDepthsToSymbols(&depth[64], 64, &bits[64]);
156
0
  {
157
    /* Create the bit length array for the full command alphabet. */
158
0
    size_t i;
159
0
    memset(tmp_depth, 0, 64);  /* only 64 first values were used */
160
0
    memcpy(tmp_depth, depth, 8);
161
0
    memcpy(tmp_depth + 64, depth + 8, 8);
162
0
    memcpy(tmp_depth + 128, depth + 16, 8);
163
0
    memcpy(tmp_depth + 192, depth + 24, 8);
164
0
    memcpy(tmp_depth + 384, depth + 32, 8);
165
0
    for (i = 0; i < 8; ++i) {
166
0
      tmp_depth[128 + 8 * i] = depth[40 + i];
167
0
      tmp_depth[256 + 8 * i] = depth[48 + i];
168
0
      tmp_depth[448 + 8 * i] = depth[56 + i];
169
0
    }
170
    /* TODO(eustas): could/should full-length machinery be avoided? */
171
0
    BrotliStoreHuffmanTree(
172
0
        tmp_depth, BROTLI_NUM_COMMAND_SYMBOLS, s->tree, storage_ix, storage);
173
0
  }
174
0
  BrotliStoreHuffmanTree(&depth[64], 64, s->tree, storage_ix, storage);
175
0
}
176
177
/* REQUIRES: insertlen < 6210 */
178
static BROTLI_INLINE void EmitInsertLen(size_t insertlen,
179
                                        const uint8_t depth[128],
180
                                        const uint16_t bits[128],
181
                                        uint32_t histo[128],
182
                                        size_t* storage_ix,
183
0
                                        uint8_t* storage) {
184
0
  if (insertlen < 6) {
185
0
    const size_t code = insertlen + 40;
186
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
187
0
    ++histo[code];
188
0
  } else if (insertlen < 130) {
189
0
    const size_t tail = insertlen - 2;
190
0
    const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
191
0
    const size_t prefix = tail >> nbits;
192
0
    const size_t inscode = (nbits << 1) + prefix + 42;
193
0
    BrotliWriteBits(depth[inscode], bits[inscode], storage_ix, storage);
194
0
    BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
195
0
    ++histo[inscode];
196
0
  } else if (insertlen < 2114) {
197
0
    const size_t tail = insertlen - 66;
198
0
    const uint32_t nbits = Log2FloorNonZero(tail);
199
0
    const size_t code = nbits + 50;
200
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
201
0
    BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
202
0
    ++histo[code];
203
0
  } else {
204
0
    BrotliWriteBits(depth[61], bits[61], storage_ix, storage);
205
0
    BrotliWriteBits(12, insertlen - 2114, storage_ix, storage);
206
0
    ++histo[61];
207
0
  }
208
0
}
209
210
static BROTLI_INLINE void EmitLongInsertLen(size_t insertlen,
211
                                            const uint8_t depth[128],
212
                                            const uint16_t bits[128],
213
                                            uint32_t histo[128],
214
                                            size_t* storage_ix,
215
0
                                            uint8_t* storage) {
216
0
  if (insertlen < 22594) {
217
0
    BrotliWriteBits(depth[62], bits[62], storage_ix, storage);
218
0
    BrotliWriteBits(14, insertlen - 6210, storage_ix, storage);
219
0
    ++histo[62];
220
0
  } else {
221
0
    BrotliWriteBits(depth[63], bits[63], storage_ix, storage);
222
0
    BrotliWriteBits(24, insertlen - 22594, storage_ix, storage);
223
0
    ++histo[63];
224
0
  }
225
0
}
226
227
static BROTLI_INLINE void EmitCopyLen(size_t copylen,
228
                                      const uint8_t depth[128],
229
                                      const uint16_t bits[128],
230
                                      uint32_t histo[128],
231
                                      size_t* storage_ix,
232
0
                                      uint8_t* storage) {
233
0
  if (copylen < 10) {
234
0
    BrotliWriteBits(
235
0
        depth[copylen + 14], bits[copylen + 14], storage_ix, storage);
236
0
    ++histo[copylen + 14];
237
0
  } else if (copylen < 134) {
238
0
    const size_t tail = copylen - 6;
239
0
    const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
240
0
    const size_t prefix = tail >> nbits;
241
0
    const size_t code = (nbits << 1) + prefix + 20;
242
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
243
0
    BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
244
0
    ++histo[code];
245
0
  } else if (copylen < 2118) {
246
0
    const size_t tail = copylen - 70;
247
0
    const uint32_t nbits = Log2FloorNonZero(tail);
248
0
    const size_t code = nbits + 28;
249
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
250
0
    BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
251
0
    ++histo[code];
252
0
  } else {
253
0
    BrotliWriteBits(depth[39], bits[39], storage_ix, storage);
254
0
    BrotliWriteBits(24, copylen - 2118, storage_ix, storage);
255
0
    ++histo[39];
256
0
  }
257
0
}
258
259
static BROTLI_INLINE void EmitCopyLenLastDistance(size_t copylen,
260
                                                  const uint8_t depth[128],
261
                                                  const uint16_t bits[128],
262
                                                  uint32_t histo[128],
263
                                                  size_t* storage_ix,
264
0
                                                  uint8_t* storage) {
265
0
  if (copylen < 12) {
266
0
    BrotliWriteBits(depth[copylen - 4], bits[copylen - 4], storage_ix, storage);
267
0
    ++histo[copylen - 4];
268
0
  } else if (copylen < 72) {
269
0
    const size_t tail = copylen - 8;
270
0
    const uint32_t nbits = Log2FloorNonZero(tail) - 1;
271
0
    const size_t prefix = tail >> nbits;
272
0
    const size_t code = (nbits << 1) + prefix + 4;
273
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
274
0
    BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
275
0
    ++histo[code];
276
0
  } else if (copylen < 136) {
277
0
    const size_t tail = copylen - 8;
278
0
    const size_t code = (tail >> 5) + 30;
279
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
280
0
    BrotliWriteBits(5, tail & 31, storage_ix, storage);
281
0
    BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
282
0
    ++histo[code];
283
0
    ++histo[64];
284
0
  } else if (copylen < 2120) {
285
0
    const size_t tail = copylen - 72;
286
0
    const uint32_t nbits = Log2FloorNonZero(tail);
287
0
    const size_t code = nbits + 28;
288
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
289
0
    BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
290
0
    BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
291
0
    ++histo[code];
292
0
    ++histo[64];
293
0
  } else {
294
0
    BrotliWriteBits(depth[39], bits[39], storage_ix, storage);
295
0
    BrotliWriteBits(24, copylen - 2120, storage_ix, storage);
296
0
    BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
297
0
    ++histo[39];
298
0
    ++histo[64];
299
0
  }
300
0
}
301
302
static BROTLI_INLINE void EmitDistance(size_t distance,
303
                                       const uint8_t depth[128],
304
                                       const uint16_t bits[128],
305
                                       uint32_t histo[128],
306
0
                                       size_t* storage_ix, uint8_t* storage) {
307
0
  const size_t d = distance + 3;
308
0
  const uint32_t nbits = Log2FloorNonZero(d) - 1u;
309
0
  const size_t prefix = (d >> nbits) & 1;
310
0
  const size_t offset = (2 + prefix) << nbits;
311
0
  const size_t distcode = 2 * (nbits - 1) + prefix + 80;
312
0
  BrotliWriteBits(depth[distcode], bits[distcode], storage_ix, storage);
313
0
  BrotliWriteBits(nbits, d - offset, storage_ix, storage);
314
0
  ++histo[distcode];
315
0
}
316
317
static BROTLI_INLINE void EmitLiterals(const uint8_t* input, const size_t len,
318
                                       const uint8_t depth[256],
319
                                       const uint16_t bits[256],
320
0
                                       size_t* storage_ix, uint8_t* storage) {
321
0
  size_t j;
322
0
  for (j = 0; j < len; j++) {
323
0
    const uint8_t lit = input[j];
324
0
    BrotliWriteBits(depth[lit], bits[lit], storage_ix, storage);
325
0
  }
326
0
}
327
328
/* REQUIRES: len <= 1 << 24. */
329
static void BrotliStoreMetaBlockHeader(
330
    size_t len, BROTLI_BOOL is_uncompressed, size_t* storage_ix,
331
0
    uint8_t* storage) {
332
0
  size_t nibbles = 6;
333
  /* ISLAST */
334
0
  BrotliWriteBits(1, 0, storage_ix, storage);
335
0
  if (len <= (1U << 16)) {
336
0
    nibbles = 4;
337
0
  } else if (len <= (1U << 20)) {
338
0
    nibbles = 5;
339
0
  }
340
0
  BrotliWriteBits(2, nibbles - 4, storage_ix, storage);
341
0
  BrotliWriteBits(nibbles * 4, len - 1, storage_ix, storage);
342
  /* ISUNCOMPRESSED */
343
0
  BrotliWriteBits(1, (uint64_t)is_uncompressed, storage_ix, storage);
344
0
}
345
346
static void UpdateBits(size_t n_bits, uint32_t bits, size_t pos,
347
0
    uint8_t* array) {
348
0
  while (n_bits > 0) {
349
0
    size_t byte_pos = pos >> 3;
350
0
    size_t n_unchanged_bits = pos & 7;
351
0
    size_t n_changed_bits = BROTLI_MIN(size_t, n_bits, 8 - n_unchanged_bits);
352
0
    size_t total_bits = n_unchanged_bits + n_changed_bits;
353
0
    uint32_t mask =
354
0
        (~((1u << total_bits) - 1u)) | ((1u << n_unchanged_bits) - 1u);
355
0
    uint32_t unchanged_bits = array[byte_pos] & mask;
356
0
    uint32_t changed_bits = bits & ((1u << n_changed_bits) - 1u);
357
0
    array[byte_pos] =
358
0
        (uint8_t)((changed_bits << n_unchanged_bits) | unchanged_bits);
359
0
    n_bits -= n_changed_bits;
360
0
    bits >>= n_changed_bits;
361
0
    pos += n_changed_bits;
362
0
  }
363
0
}
364
365
static void RewindBitPosition(const size_t new_storage_ix,
366
0
                              size_t* storage_ix, uint8_t* storage) {
367
0
  const size_t bitpos = new_storage_ix & 7;
368
0
  const size_t mask = (1u << bitpos) - 1;
369
0
  storage[new_storage_ix >> 3] &= (uint8_t)mask;
370
0
  *storage_ix = new_storage_ix;
371
0
}
372
373
static BROTLI_BOOL ShouldMergeBlock(BrotliOnePassArena* s,
374
0
    const uint8_t* data, size_t len, const uint8_t* depths) {
375
0
  uint32_t* BROTLI_RESTRICT const histo = s->histogram;
376
0
  static const size_t kSampleRate = 43;
377
0
  size_t i;
378
0
  memset(histo, 0, sizeof(s->histogram));
379
0
  for (i = 0; i < len; i += kSampleRate) {
380
0
    ++histo[data[i]];
381
0
  }
382
0
  {
383
0
    const size_t total = (len + kSampleRate - 1) / kSampleRate;
384
0
    double r = (FastLog2(total) + 0.5) * (double)total + 200;
385
0
    for (i = 0; i < 256; ++i) {
386
0
      r -= (double)histo[i] * (depths[i] + FastLog2(histo[i]));
387
0
    }
388
0
    return TO_BROTLI_BOOL(r >= 0.0);
389
0
  }
390
0
}
391
392
/* Acceptable loss for uncompressible speedup is 2% */
393
#define MIN_RATIO 980
394
395
static BROTLI_INLINE BROTLI_BOOL ShouldUseUncompressedMode(
396
    const uint8_t* metablock_start, const uint8_t* next_emit,
397
0
    const size_t insertlen, const size_t literal_ratio) {
398
0
  const size_t compressed = (size_t)(next_emit - metablock_start);
399
0
  if (compressed * 50 > insertlen) {
400
0
    return BROTLI_FALSE;
401
0
  } else {
402
0
    return TO_BROTLI_BOOL(literal_ratio > MIN_RATIO);
403
0
  }
404
0
}
405
406
static void EmitUncompressedMetaBlock(const uint8_t* begin, const uint8_t* end,
407
                                      const size_t storage_ix_start,
408
0
                                      size_t* storage_ix, uint8_t* storage) {
409
0
  const size_t len = (size_t)(end - begin);
410
0
  RewindBitPosition(storage_ix_start, storage_ix, storage);
411
0
  BrotliStoreMetaBlockHeader(len, 1, storage_ix, storage);
412
0
  *storage_ix = (*storage_ix + 7u) & ~7u;
413
0
  memcpy(&storage[*storage_ix >> 3], begin, len);
414
0
  *storage_ix += len << 3;
415
0
  storage[*storage_ix >> 3] = 0;
416
0
}
417
418
static uint32_t kCmdHistoSeed[128] = {
419
  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
420
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
421
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
422
  0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
423
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
424
  1, 1, 1, 1, 0, 0, 0, 0,
425
};
426
427
static BROTLI_INLINE void BrotliCompressFragmentFastImpl(
428
    BrotliOnePassArena* s, const uint8_t* input, size_t input_size,
429
    BROTLI_BOOL is_last, int* table, size_t table_bits,
430
0
    size_t* storage_ix, uint8_t* storage) {
431
0
  uint8_t* BROTLI_RESTRICT const cmd_depth = s->cmd_depth;
432
0
  uint16_t* BROTLI_RESTRICT const cmd_bits = s->cmd_bits;
433
0
  uint32_t* BROTLI_RESTRICT const cmd_histo = s->cmd_histo;
434
0
  uint8_t* BROTLI_RESTRICT const lit_depth = s->lit_depth;
435
0
  uint16_t* BROTLI_RESTRICT const lit_bits = s->lit_bits;
436
0
  const uint8_t* ip_end;
437
438
  /* "next_emit" is a pointer to the first byte that is not covered by a
439
     previous copy. Bytes between "next_emit" and the start of the next copy or
440
     the end of the input will be emitted as literal bytes. */
441
0
  const uint8_t* next_emit = input;
442
  /* Save the start of the first block for position and distance computations.
443
  */
444
0
  const uint8_t* base_ip = input;
445
446
0
  static const size_t kFirstBlockSize = 3 << 15;
447
0
  static const size_t kMergeBlockSize = 1 << 16;
448
449
0
  const size_t kInputMarginBytes = BROTLI_WINDOW_GAP;
450
0
  const size_t kMinMatchLen = 5;
451
452
0
  const uint8_t* metablock_start = input;
453
0
  size_t block_size = BROTLI_MIN(size_t, input_size, kFirstBlockSize);
454
0
  size_t total_block_size = block_size;
455
  /* Save the bit position of the MLEN field of the meta-block header, so that
456
     we can update it later if we decide to extend this meta-block. */
457
0
  size_t mlen_storage_ix = *storage_ix + 3;
458
459
0
  size_t literal_ratio;
460
461
0
  const uint8_t* ip;
462
0
  int last_distance;
463
464
0
  const size_t shift = 64u - table_bits;
465
466
0
  BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
467
  /* No block splits, no contexts. */
468
0
  BrotliWriteBits(13, 0, storage_ix, storage);
469
470
0
  literal_ratio = BuildAndStoreLiteralPrefixCode(
471
0
      s, input, block_size, s->lit_depth, s->lit_bits, storage_ix, storage);
472
473
0
  {
474
    /* Store the pre-compressed command and distance prefix codes. */
475
0
    size_t i;
476
0
    for (i = 0; i + 7 < s->cmd_code_numbits; i += 8) {
477
0
      BrotliWriteBits(8, s->cmd_code[i >> 3], storage_ix, storage);
478
0
    }
479
0
  }
480
0
  BrotliWriteBits(s->cmd_code_numbits & 7,
481
0
                  s->cmd_code[s->cmd_code_numbits >> 3], storage_ix, storage);
482
483
0
 emit_commands:
484
  /* Initialize the command and distance histograms. We will gather
485
     statistics of command and distance codes during the processing
486
     of this block and use it to update the command and distance
487
     prefix codes for the next block. */
488
0
  memcpy(s->cmd_histo, kCmdHistoSeed, sizeof(kCmdHistoSeed));
489
490
  /* "ip" is the input pointer. */
491
0
  ip = input;
492
0
  last_distance = -1;
493
0
  ip_end = input + block_size;
494
495
0
  if (BROTLI_PREDICT_TRUE(block_size >= kInputMarginBytes)) {
496
    /* For the last block, we need to keep a 16 bytes margin so that we can be
497
       sure that all distances are at most window size - 16.
498
       For all other blocks, we only need to keep a margin of 5 bytes so that
499
       we don't go over the block size with a copy. */
500
0
    const size_t len_limit = BROTLI_MIN(size_t, block_size - kMinMatchLen,
501
0
                                        input_size - kInputMarginBytes);
502
0
    const uint8_t* ip_limit = input + len_limit;
503
504
0
    uint32_t next_hash;
505
0
    for (next_hash = Hash(++ip, shift); ; ) {
506
      /* Step 1: Scan forward in the input looking for a 5-byte-long match.
507
         If we get close to exhausting the input then goto emit_remainder.
508
509
         Heuristic match skipping: If 32 bytes are scanned with no matches
510
         found, start looking only at every other byte. If 32 more bytes are
511
         scanned, look at every third byte, etc.. When a match is found,
512
         immediately go back to looking at every byte. This is a small loss
513
         (~5% performance, ~0.1% density) for compressible data due to more
514
         bookkeeping, but for non-compressible data (such as JPEG) it's a huge
515
         win since the compressor quickly "realizes" the data is incompressible
516
         and doesn't bother looking for matches everywhere.
517
518
         The "skip" variable keeps track of how many bytes there are since the
519
         last match; dividing it by 32 (i.e. right-shifting by five) gives the
520
         number of bytes to move ahead for each iteration. */
521
0
      uint32_t skip = 32;
522
523
0
      const uint8_t* next_ip = ip;
524
0
      const uint8_t* candidate;
525
0
      BROTLI_DCHECK(next_emit < ip);
526
0
trawl:
527
0
      do {
528
0
        uint32_t hash = next_hash;
529
0
        uint32_t bytes_between_hash_lookups = skip++ >> 5;
530
0
        BROTLI_DCHECK(hash == Hash(next_ip, shift));
531
0
        ip = next_ip;
532
0
        next_ip = ip + bytes_between_hash_lookups;
533
0
        if (BROTLI_PREDICT_FALSE(next_ip > ip_limit)) {
534
0
          goto emit_remainder;
535
0
        }
536
0
        next_hash = Hash(next_ip, shift);
537
0
        candidate = ip - last_distance;
538
0
        if (IsMatch(ip, candidate)) {
539
0
          if (BROTLI_PREDICT_TRUE(candidate < ip)) {
540
0
            table[hash] = (int)(ip - base_ip);
541
0
            break;
542
0
          }
543
0
        }
544
0
        candidate = base_ip + table[hash];
545
0
        BROTLI_DCHECK(candidate >= base_ip);
546
0
        BROTLI_DCHECK(candidate < ip);
547
548
0
        table[hash] = (int)(ip - base_ip);
549
0
      } while (BROTLI_PREDICT_TRUE(!IsMatch(ip, candidate)));
550
551
      /* Check copy distance. If candidate is not feasible, continue search.
552
         Checking is done outside of hot loop to reduce overhead. */
553
0
      if (ip - candidate > MAX_DISTANCE) goto trawl;
554
555
      /* Step 2: Emit the found match together with the literal bytes from
556
         "next_emit" to the bit stream, and then see if we can find a next match
557
         immediately afterwards. Repeat until we find no match for the input
558
         without emitting some literal bytes. */
559
560
0
      {
561
        /* We have a 5-byte match at ip, and we need to emit bytes in
562
           [next_emit, ip). */
563
0
        const uint8_t* base = ip;
564
0
        size_t matched = 5 + FindMatchLengthWithLimit(
565
0
            candidate + 5, ip + 5, (size_t)(ip_end - ip) - 5);
566
0
        int distance = (int)(base - candidate);  /* > 0 */
567
0
        size_t insert = (size_t)(base - next_emit);
568
0
        ip += matched;
569
0
        BROTLI_LOG(("[CompressFragment] pos = %d insert = %lu copy = %d\n",
570
0
                    (int)(next_emit - base_ip), (unsigned long)insert, 2));
571
0
        BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
572
0
        if (BROTLI_PREDICT_TRUE(insert < 6210)) {
573
0
          EmitInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
574
0
                        storage_ix, storage);
575
0
        } else if (ShouldUseUncompressedMode(metablock_start, next_emit, insert,
576
0
                                             literal_ratio)) {
577
0
          EmitUncompressedMetaBlock(metablock_start, base, mlen_storage_ix - 3,
578
0
                                    storage_ix, storage);
579
0
          input_size -= (size_t)(base - input);
580
0
          input = base;
581
0
          next_emit = input;
582
0
          goto next_block;
583
0
        } else {
584
0
          EmitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
585
0
                            storage_ix, storage);
586
0
        }
587
0
        EmitLiterals(next_emit, insert, lit_depth, lit_bits,
588
0
                     storage_ix, storage);
589
0
        if (distance == last_distance) {
590
0
          BrotliWriteBits(cmd_depth[64], cmd_bits[64], storage_ix, storage);
591
0
          ++cmd_histo[64];
592
0
        } else {
593
0
          EmitDistance((size_t)distance, cmd_depth, cmd_bits,
594
0
                       cmd_histo, storage_ix, storage);
595
0
          last_distance = distance;
596
0
        }
597
0
        EmitCopyLenLastDistance(matched, cmd_depth, cmd_bits, cmd_histo,
598
0
                                storage_ix, storage);
599
0
        BROTLI_LOG(("[CompressFragment] pos = %d distance = %d\n"
600
0
                    "[CompressFragment] pos = %d insert = %d copy = %d\n"
601
0
                    "[CompressFragment] pos = %d distance = %d\n",
602
0
                    (int)(base - base_ip), (int)distance,
603
0
                    (int)(base - base_ip) + 2, 0, (int)matched - 2,
604
0
                    (int)(base - base_ip) + 2, (int)distance));
605
606
0
        next_emit = ip;
607
0
        if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
608
0
          goto emit_remainder;
609
0
        }
610
        /* We could immediately start working at ip now, but to improve
611
           compression we first update "table" with the hashes of some positions
612
           within the last copy. */
613
0
        {
614
0
          uint64_t input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
615
0
          uint32_t prev_hash = HashBytesAtOffset(input_bytes, 0, shift);
616
0
          uint32_t cur_hash = HashBytesAtOffset(input_bytes, 3, shift);
617
0
          table[prev_hash] = (int)(ip - base_ip - 3);
618
0
          prev_hash = HashBytesAtOffset(input_bytes, 1, shift);
619
0
          table[prev_hash] = (int)(ip - base_ip - 2);
620
0
          prev_hash = HashBytesAtOffset(input_bytes, 2, shift);
621
0
          table[prev_hash] = (int)(ip - base_ip - 1);
622
623
0
          candidate = base_ip + table[cur_hash];
624
0
          table[cur_hash] = (int)(ip - base_ip);
625
0
        }
626
0
      }
627
628
0
      while (IsMatch(ip, candidate)) {
629
        /* We have a 5-byte match at ip, and no need to emit any literal bytes
630
           prior to ip. */
631
0
        const uint8_t* base = ip;
632
0
        size_t matched = 5 + FindMatchLengthWithLimit(
633
0
            candidate + 5, ip + 5, (size_t)(ip_end - ip) - 5);
634
0
        if (ip - candidate > MAX_DISTANCE) break;
635
0
        ip += matched;
636
0
        last_distance = (int)(base - candidate);  /* > 0 */
637
0
        BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
638
0
        EmitCopyLen(matched, cmd_depth, cmd_bits, cmd_histo,
639
0
                    storage_ix, storage);
640
0
        EmitDistance((size_t)last_distance, cmd_depth, cmd_bits,
641
0
                     cmd_histo, storage_ix, storage);
642
0
        BROTLI_LOG(("[CompressFragment] pos = %d insert = %d copy = %d\n"
643
0
                    "[CompressFragment] pos = %d distance = %d\n",
644
0
                    (int)(base - base_ip), 0, (int)matched,
645
0
                    (int)(base - base_ip), (int)last_distance));
646
647
0
        next_emit = ip;
648
0
        if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
649
0
          goto emit_remainder;
650
0
        }
651
        /* We could immediately start working at ip now, but to improve
652
           compression we first update "table" with the hashes of some positions
653
           within the last copy. */
654
0
        {
655
0
          uint64_t input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
656
0
          uint32_t prev_hash = HashBytesAtOffset(input_bytes, 0, shift);
657
0
          uint32_t cur_hash = HashBytesAtOffset(input_bytes, 3, shift);
658
0
          table[prev_hash] = (int)(ip - base_ip - 3);
659
0
          prev_hash = HashBytesAtOffset(input_bytes, 1, shift);
660
0
          table[prev_hash] = (int)(ip - base_ip - 2);
661
0
          prev_hash = HashBytesAtOffset(input_bytes, 2, shift);
662
0
          table[prev_hash] = (int)(ip - base_ip - 1);
663
664
0
          candidate = base_ip + table[cur_hash];
665
0
          table[cur_hash] = (int)(ip - base_ip);
666
0
        }
667
0
      }
668
669
0
      next_hash = Hash(++ip, shift);
670
0
    }
671
0
  }
672
673
0
 emit_remainder:
674
0
  BROTLI_DCHECK(next_emit <= ip_end);
675
0
  input += block_size;
676
0
  input_size -= block_size;
677
0
  block_size = BROTLI_MIN(size_t, input_size, kMergeBlockSize);
678
679
  /* Decide if we want to continue this meta-block instead of emitting the
680
     last insert-only command. */
681
0
  if (input_size > 0 &&
682
0
      total_block_size + block_size <= (1 << 20) &&
683
0
      ShouldMergeBlock(s, input, block_size, lit_depth)) {
684
0
    BROTLI_DCHECK(total_block_size > (1 << 16));
685
    /* Update the size of the current meta-block and continue emitting commands.
686
       We can do this because the current size and the new size both have 5
687
       nibbles. */
688
0
    total_block_size += block_size;
689
0
    UpdateBits(20, (uint32_t)(total_block_size - 1), mlen_storage_ix, storage);
690
0
    goto emit_commands;
691
0
  }
692
693
  /* Emit the remaining bytes as literals. */
694
0
  if (next_emit < ip_end) {
695
0
    const size_t insert = (size_t)(ip_end - next_emit);
696
0
    BROTLI_LOG(("[CompressFragment] pos = %d insert = %lu copy = %d\n",
697
0
                (int)(next_emit - base_ip), (unsigned long)insert, 2));
698
0
    if (BROTLI_PREDICT_TRUE(insert < 6210)) {
699
0
      EmitInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
700
0
                    storage_ix, storage);
701
0
      EmitLiterals(next_emit, insert, lit_depth, lit_bits, storage_ix, storage);
702
0
    } else if (ShouldUseUncompressedMode(metablock_start, next_emit, insert,
703
0
                                         literal_ratio)) {
704
0
      EmitUncompressedMetaBlock(metablock_start, ip_end, mlen_storage_ix - 3,
705
0
                                storage_ix, storage);
706
0
    } else {
707
0
      EmitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
708
0
                        storage_ix, storage);
709
0
      EmitLiterals(next_emit, insert, lit_depth, lit_bits,
710
0
                   storage_ix, storage);
711
0
    }
712
0
  }
713
0
  next_emit = ip_end;
714
715
0
next_block:
716
  /* If we have more data, write a new meta-block header and prefix codes and
717
     then continue emitting commands. */
718
0
  if (input_size > 0) {
719
0
    metablock_start = input;
720
0
    block_size = BROTLI_MIN(size_t, input_size, kFirstBlockSize);
721
0
    total_block_size = block_size;
722
    /* Save the bit position of the MLEN field of the meta-block header, so that
723
       we can update it later if we decide to extend this meta-block. */
724
0
    mlen_storage_ix = *storage_ix + 3;
725
0
    BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
726
    /* No block splits, no contexts. */
727
0
    BrotliWriteBits(13, 0, storage_ix, storage);
728
0
    literal_ratio = BuildAndStoreLiteralPrefixCode(
729
0
        s, input, block_size, lit_depth, lit_bits, storage_ix, storage);
730
0
    BuildAndStoreCommandPrefixCode(s, storage_ix, storage);
731
0
    goto emit_commands;
732
0
  }
733
734
0
  if (!is_last) {
735
    /* If this is not the last block, update the command and distance prefix
736
       codes for the next block and store the compressed forms. */
737
0
    s->cmd_code[0] = 0;
738
0
    s->cmd_code_numbits = 0;
739
0
    BuildAndStoreCommandPrefixCode(s, &s->cmd_code_numbits, s->cmd_code);
740
0
  }
741
0
}
742
743
0
#define FOR_TABLE_BITS_(X) X(9) X(11) X(13) X(15)
744
745
#define BAKE_METHOD_PARAM_(B) \
746
static BROTLI_NOINLINE void BrotliCompressFragmentFastImpl ## B(             \
747
    BrotliOnePassArena* s, const uint8_t* input, size_t input_size,          \
748
0
    BROTLI_BOOL is_last, int* table, size_t* storage_ix, uint8_t* storage) { \
749
0
  BrotliCompressFragmentFastImpl(s, input, input_size, is_last, table, B,    \
750
0
      storage_ix, storage);                                                  \
751
0
}
Unexecuted instantiation: compress_fragment.cpp:BrotliCompressFragmentFastImpl9(duckdb_brotli::BrotliOnePassArena*, unsigned char const*, unsigned long, int, int*, unsigned long*, unsigned char*)
Unexecuted instantiation: compress_fragment.cpp:BrotliCompressFragmentFastImpl11(duckdb_brotli::BrotliOnePassArena*, unsigned char const*, unsigned long, int, int*, unsigned long*, unsigned char*)
Unexecuted instantiation: compress_fragment.cpp:BrotliCompressFragmentFastImpl13(duckdb_brotli::BrotliOnePassArena*, unsigned char const*, unsigned long, int, int*, unsigned long*, unsigned char*)
Unexecuted instantiation: compress_fragment.cpp:BrotliCompressFragmentFastImpl15(duckdb_brotli::BrotliOnePassArena*, unsigned char const*, unsigned long, int, int*, unsigned long*, unsigned char*)
752
FOR_TABLE_BITS_(BAKE_METHOD_PARAM_)
753
#undef BAKE_METHOD_PARAM_
754
755
void duckdb_brotli::BrotliCompressFragmentFast(
756
    BrotliOnePassArena* s, const uint8_t* input, size_t input_size,
757
    BROTLI_BOOL is_last, int* table, size_t table_size,
758
0
    size_t* storage_ix, uint8_t* storage) {
759
0
  const size_t initial_storage_ix = *storage_ix;
760
0
  const size_t table_bits = Log2FloorNonZero(table_size);
761
762
0
  if (input_size == 0) {
763
0
    BROTLI_DCHECK(is_last);
764
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* islast */
765
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* isempty */
766
0
    *storage_ix = (*storage_ix + 7u) & ~7u;
767
0
    return;
768
0
  }
769
770
0
  switch (table_bits) {
771
0
#define CASE_(B)                                                     \
772
0
    case B:                                                          \
773
0
      BrotliCompressFragmentFastImpl ## B(                           \
774
0
          s, input, input_size, is_last, table, storage_ix, storage);\
775
0
      break;
776
0
    FOR_TABLE_BITS_(CASE_)
777
0
#undef CASE_
778
0
    default: BROTLI_DCHECK(0); break;
779
0
  }
780
781
  /* If output is larger than single uncompressed block, rewrite it. */
782
0
  if (*storage_ix - initial_storage_ix > 31 + (input_size << 3)) {
783
0
    EmitUncompressedMetaBlock(input, input + input_size, initial_storage_ix,
784
0
                              storage_ix, storage);
785
0
  }
786
787
0
  if (is_last) {
788
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* islast */
789
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* isempty */
790
0
    *storage_ix = (*storage_ix + 7u) & ~7u;
791
0
  }
792
0
}
793
794
#undef FOR_TABLE_BITS_
795
796