Coverage Report

Created: 2026-12-01 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/compress/zstd_compress_superblock.c
Line
Count
Source
1
/*
2
 * Copyright (c) Meta Platforms, Inc. and affiliates.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under both the BSD-style license (found in the
6
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
 * in the COPYING file in the root directory of this source tree).
8
 * You may select, at your option, one of the above-listed licenses.
9
 */
10
11
 /*-*************************************
12
 *  Dependencies
13
 ***************************************/
14
#include "zstd_compress_superblock.h"
15
16
#include "../common/zstd_internal.h"  /* ZSTD_getSequenceLength */
17
#include "hist.h"                     /* HIST_countFast_wksp */
18
#include "zstd_compress_internal.h"   /* ZSTD_[huf|fse|entropy]CTablesMetadata_t */
19
#include "zstd_compress_sequences.h"
20
#include "zstd_compress_literals.h"
21
22
/** ZSTD_compressSubBlock_literal() :
23
 *  Compresses literals section for a sub-block.
24
 *  When we have to write the Huffman table we will sometimes choose a header
25
 *  size larger than necessary. This is because we have to pick the header size
26
 *  before we know the table size + compressed size, so we have a bound on the
27
 *  table size. If we guessed incorrectly, we fall back to uncompressed literals.
28
 *
29
 *  We write the header when writeEntropy=1 and set entropyWritten=1 when we succeeded
30
 *  in writing the header, otherwise it is set to 0.
31
 *
32
 *  hufMetadata->hType has literals block type info.
33
 *      If it is set_basic, all sub-blocks literals section will be Raw_Literals_Block.
34
 *      If it is set_rle, all sub-blocks literals section will be RLE_Literals_Block.
35
 *      If it is set_compressed, first sub-block's literals section will be Compressed_Literals_Block
36
 *      If it is set_compressed, first sub-block's literals section will be Treeless_Literals_Block
37
 *      and the following sub-blocks' literals sections will be Treeless_Literals_Block.
38
 *  @return : compressed size of literals section of a sub-block
39
 *            Or 0 if unable to compress.
40
 *            Or error code */
41
static size_t
42
ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
43
                              const ZSTD_hufCTablesMetadata_t* hufMetadata,
44
                              const BYTE* literals, size_t litSize,
45
                              void* dst, size_t dstSize,
46
                              const int bmi2, int writeEntropy, int* entropyWritten)
47
1.39M
{
48
1.39M
    size_t const header = writeEntropy ? 200 : 0;
49
1.39M
    size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header));
50
1.39M
    BYTE* const ostart = (BYTE*)dst;
51
1.39M
    BYTE* const oend = ostart + dstSize;
52
1.39M
    BYTE* op = ostart;
53
1.39M
    U32 const singleStream = lhSize == 3;
54
1.39M
    SymbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat;
55
1.39M
    size_t cLitSize = 0;
56
57
1.39M
    DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy);
58
59
1.39M
    *entropyWritten = 0;
60
1.39M
    if (litSize == 0 || hufMetadata->hType == set_basic) {
61
813k
      DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal");
62
813k
      return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
63
813k
    } else if (hufMetadata->hType == set_rle) {
64
5.03k
      DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal");
65
5.03k
      RETURN_ERROR_IF(dstSize < 4, dstSize_tooSmall, "");
66
5.03k
      return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize);
67
5.03k
    }
68
69
1.39M
    assert(litSize > 0);
70
580k
    assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat);
71
72
580k
    RETURN_ERROR_IF(dstSize < lhSize, dstSize_tooSmall, "");
73
580k
    op += lhSize;
74
580k
    if (writeEntropy && hufMetadata->hType == set_compressed) {
75
454k
        RETURN_ERROR_IF(hufMetadata->hufDesSize > (size_t)(oend-op),
76
454k
                        dstSize_tooSmall, "");
77
454k
        ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize);
78
454k
        op += hufMetadata->hufDesSize;
79
454k
        cLitSize += hufMetadata->hufDesSize;
80
454k
        DEBUGLOG(5, "ZSTD_compressSubBlock_literal (hSize=%zu)", hufMetadata->hufDesSize);
81
454k
    }
82
83
580k
    {   int const flags = bmi2 ? HUF_flags_bmi2 : 0;
84
580k
        const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags)
85
580k
                                          : HUF_compress4X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags);
86
580k
        if (cSize == 0 || ERR_isError(cSize)) {
87
0
            DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize));
88
0
            return 0;
89
0
        }
90
580k
        op += cSize;
91
580k
        cLitSize += cSize;
92
        /* If we expand and we aren't writing a header then emit uncompressed */
93
580k
        if (!writeEntropy && cLitSize >= litSize) {
94
13.1k
            DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible");
95
13.1k
            return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
96
13.1k
        }
97
        /* If we are writing headers then allow expansion that doesn't change our header size. */
98
566k
        if (lhSize < (size_t)(3 + (cLitSize >= 1 KB) + (cLitSize >= 16 KB))) {
99
155
            assert(cLitSize > litSize);
100
155
            DEBUGLOG(5, "Literals expanded beyond allowed header size");
101
155
            return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
102
155
        }
103
566k
        DEBUGLOG(5, "ZSTD_compressSubBlock_literal (cSize=%zu)", cSize);
104
566k
    }
105
106
    /* Build header */
107
0
    switch(lhSize)
108
566k
    {
109
458k
    case 3: /* 2 - 2 - 10 - 10 */
110
458k
        {   U32 const lhc = hType + ((U32)(!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
111
458k
            MEM_writeLE24(ostart, lhc);
112
458k
            break;
113
0
        }
114
106k
    case 4: /* 2 - 2 - 14 - 14 */
115
106k
        {   U32 const lhc = hType + (2 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<18);
116
106k
            MEM_writeLE32(ostart, lhc);
117
106k
            break;
118
0
        }
119
1.67k
    case 5: /* 2 - 2 - 18 - 18 */
120
1.67k
        {   U32 const lhc = hType + (3 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<22);
121
1.67k
            MEM_writeLE32(ostart, lhc);
122
1.67k
            ostart[4] = (BYTE)(cLitSize >> 10);
123
1.67k
            break;
124
0
        }
125
0
    default:  /* not possible : lhSize is {3,4,5} */
126
0
        assert(0);
127
566k
    }
128
566k
    *entropyWritten = 1;
129
566k
    DEBUGLOG(5, "Compressed literals: %u -> %u", (U32)litSize, (U32)(op-ostart));
130
566k
    return (size_t)(op-ostart);
131
566k
}
132
133
static size_t
134
ZSTD_seqDecompressedSize(SeqStore_t const* seqStore,
135
                   const SeqDef* sequences, size_t nbSeqs,
136
                         size_t litSize, int lastSubBlock)
137
1.39M
{
138
1.39M
    size_t matchLengthSum = 0;
139
1.39M
    size_t litLengthSum = 0;
140
1.39M
    size_t n;
141
50.6M
    for (n=0; n<nbSeqs; n++) {
142
49.2M
        const ZSTD_SequenceLength seqLen = ZSTD_getSequenceLength(seqStore, sequences+n);
143
49.2M
        litLengthSum += seqLen.litLength;
144
49.2M
        matchLengthSum += seqLen.matchLength;
145
49.2M
    }
146
1.39M
    DEBUGLOG(5, "ZSTD_seqDecompressedSize: %u sequences from %p: %u literals + %u matchlength",
147
1.39M
                (unsigned)nbSeqs, (const void*)sequences,
148
1.39M
                (unsigned)litLengthSum, (unsigned)matchLengthSum);
149
1.39M
    if (!lastSubBlock)
150
1.39M
        assert(litLengthSum == litSize);
151
1.36M
    else
152
1.39M
        assert(litLengthSum <= litSize);
153
1.39M
    (void)litLengthSum;
154
1.39M
    return matchLengthSum + litSize;
155
1.39M
}
156
157
/** ZSTD_compressSubBlock_sequences() :
158
 *  Compresses sequences section for a sub-block.
159
 *  fseMetadata->llType, fseMetadata->ofType, and fseMetadata->mlType have
160
 *  symbol compression modes for the super-block.
161
 *  The first successfully compressed block will have these in its header.
162
 *  We set entropyWritten=1 when we succeed in compressing the sequences.
163
 *  The following sub-blocks will always have repeat mode.
164
 *  @return : compressed size of sequences section of a sub-block
165
 *            Or 0 if it is unable to compress
166
 *            Or error code. */
167
static size_t
168
ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
169
                                const ZSTD_fseCTablesMetadata_t* fseMetadata,
170
                                const SeqDef* sequences, size_t nbSeq,
171
                                const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
172
                                const ZSTD_CCtx_params* cctxParams,
173
                                void* dst, size_t dstCapacity,
174
                                const int bmi2, int writeEntropy, int* entropyWritten)
175
1.39M
{
176
1.39M
    const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
177
1.39M
    BYTE* const ostart = (BYTE*)dst;
178
1.39M
    BYTE* const oend = ostart + dstCapacity;
179
1.39M
    BYTE* op = ostart;
180
1.39M
    BYTE* seqHead;
181
182
1.39M
    DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (nbSeq=%zu, writeEntropy=%d, longOffsets=%d)", nbSeq, writeEntropy, longOffsets);
183
184
1.39M
    *entropyWritten = 0;
185
    /* Sequences Header */
186
1.39M
    RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
187
1.39M
                    dstSize_tooSmall, "");
188
1.39M
    if (nbSeq < 128)
189
1.32M
        *op++ = (BYTE)nbSeq;
190
72.1k
    else if (nbSeq < LONGNBSEQ)
191
72.1k
        op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
192
18.4E
    else
193
18.4E
        op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
194
1.39M
    if (nbSeq==0) {
195
133k
        return (size_t)(op - ostart);
196
133k
    }
197
198
    /* seqHead : flags for FSE encoding type */
199
1.26M
    seqHead = op++;
200
201
1.26M
    DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (seqHeadSize=%u)", (unsigned)(op-ostart));
202
203
1.26M
    if (writeEntropy) {
204
1.23M
        const U32 LLtype = fseMetadata->llType;
205
1.23M
        const U32 Offtype = fseMetadata->ofType;
206
1.23M
        const U32 MLtype = fseMetadata->mlType;
207
1.23M
        DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize);
208
1.23M
        RETURN_ERROR_IF(fseMetadata->fseTablesSize > (size_t)(oend-op),
209
1.23M
                        dstSize_tooSmall, "");
210
1.23M
        *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
211
1.23M
        ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize);
212
1.23M
        op += fseMetadata->fseTablesSize;
213
1.23M
    } else {
214
28.7k
        const U32 repeat = set_repeat;
215
28.7k
        *seqHead = (BYTE)((repeat<<6) + (repeat<<4) + (repeat<<2));
216
28.7k
    }
217
218
1.26M
    {   size_t const bitstreamSize = ZSTD_encodeSequences(
219
1.26M
                                        op, (size_t)(oend - op),
220
1.26M
                                        fseTables->matchlengthCTable, mlCode,
221
1.26M
                                        fseTables->offcodeCTable, ofCode,
222
1.26M
                                        fseTables->litlengthCTable, llCode,
223
1.26M
                                        sequences, nbSeq,
224
1.26M
                                        longOffsets, bmi2);
225
1.26M
        FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
226
1.26M
        op += bitstreamSize;
227
        /* zstd versions <= 1.3.4 mistakenly report corruption when
228
         * FSE_readNCount() receives a buffer < 4 bytes.
229
         * Fixed by https://github.com/facebook/zstd/pull/1146.
230
         * This can happen when the last set_compressed table present is 2
231
         * bytes and the bitstream is only one byte.
232
         * In this exceedingly rare case, we will simply emit an uncompressed
233
         * block, since it isn't worth optimizing.
234
         */
235
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
236
        if (writeEntropy && fseMetadata->lastCountSize && fseMetadata->lastCountSize + bitstreamSize < 4) {
237
            /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
238
            assert(fseMetadata->lastCountSize + bitstreamSize == 3);
239
            DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
240
                        "emitting an uncompressed block.");
241
            return 0;
242
        }
243
#endif
244
1.26M
        DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (bitstreamSize=%zu)", bitstreamSize);
245
1.26M
    }
246
247
    /* zstd versions <= 1.4.0 mistakenly report error when
248
     * sequences section body size is less than 3 bytes.
249
     * Fixed by https://github.com/facebook/zstd/pull/1664.
250
     * This can happen when the previous sequences section block is compressed
251
     * with rle mode and the current block's sequences section is compressed
252
     * with repeat mode where sequences section body size can be 1 byte.
253
     */
254
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
255
    if (op-seqHead < 4) {
256
        DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.4.0 by emitting "
257
                    "an uncompressed block when sequences are < 4 bytes");
258
        return 0;
259
    }
260
#endif
261
262
0
    *entropyWritten = 1;
263
1.26M
    return (size_t)(op - ostart);
264
1.26M
}
265
266
/** ZSTD_compressSubBlock() :
267
 *  Compresses a single sub-block.
268
 *  @return : compressed size of the sub-block
269
 *            Or 0 if it failed to compress. */
270
static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
271
                                    const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
272
                                    const SeqDef* sequences, size_t nbSeq,
273
                                    const BYTE* literals, size_t litSize,
274
                                    const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
275
                                    const ZSTD_CCtx_params* cctxParams,
276
                                    void* dst, size_t dstCapacity,
277
                                    const int bmi2,
278
                                    int writeLitEntropy, int writeSeqEntropy,
279
                                    int* litEntropyWritten, int* seqEntropyWritten,
280
                                    U32 lastBlock)
281
1.39M
{
282
1.39M
    BYTE* const ostart = (BYTE*)dst;
283
1.39M
    BYTE* const oend = ostart + dstCapacity;
284
1.39M
    BYTE* op = ostart;
285
1.39M
    DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)",
286
1.39M
                litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);
287
1.39M
    RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "");
288
1.39M
    op += ZSTD_blockHeaderSize;
289
1.39M
    {   size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,
290
1.39M
                                                        &entropyMetadata->hufMetadata, literals, litSize,
291
1.39M
                                                        op, (size_t)(oend-op),
292
1.39M
                                                        bmi2, writeLitEntropy, litEntropyWritten);
293
1.39M
        FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");
294
1.39M
        if (cLitSize == 0) return 0;
295
1.39M
        op += cLitSize;
296
1.39M
    }
297
0
    {   size_t cSeqSize = ZSTD_compressSubBlock_sequences(&entropy->fse,
298
1.39M
                                                  &entropyMetadata->fseMetadata,
299
1.39M
                                                  sequences, nbSeq,
300
1.39M
                                                  llCode, mlCode, ofCode,
301
1.39M
                                                  cctxParams,
302
1.39M
                                                  op, (size_t)(oend-op),
303
1.39M
                                                  bmi2, writeSeqEntropy, seqEntropyWritten);
304
1.39M
        FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");
305
1.39M
        if (cSeqSize == 0) return 0;
306
1.39M
        op += cSeqSize;
307
1.39M
    }
308
    /* Write block header */
309
0
    {   size_t cSize = (size_t)(op-ostart) - ZSTD_blockHeaderSize;
310
1.39M
        U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
311
1.39M
        MEM_writeLE24(ostart, cBlockHeader24);
312
1.39M
    }
313
1.39M
    return (size_t)(op-ostart);
314
1.39M
}
315
316
static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,
317
                                                const ZSTD_hufCTables_t* huf,
318
                                                const ZSTD_hufCTablesMetadata_t* hufMetadata,
319
                                                void* workspace, size_t wkspSize,
320
                                                int writeEntropy)
321
1.25M
{
322
1.25M
    unsigned* const countWksp = (unsigned*)workspace;
323
1.25M
    unsigned maxSymbolValue = 255;
324
1.25M
    size_t literalSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
325
326
1.25M
    if (hufMetadata->hType == set_basic) return litSize;
327
524k
    else if (hufMetadata->hType == set_rle) return 1;
328
521k
    else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
329
521k
        size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
330
521k
        if (ZSTD_isError(largest)) return litSize;
331
521k
        {   size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
332
521k
            if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
333
521k
            return cLitSizeEstimate + literalSectionHeaderSize;
334
521k
    }   }
335
18.4E
    assert(0); /* impossible */
336
18.4E
    return 0;
337
18.4E
}
338
339
static size_t ZSTD_estimateSubBlockSize_symbolType(SymbolEncodingType_e type,
340
                        const BYTE* codeTable, unsigned maxCode,
341
                        size_t nbSeq, const FSE_CTable* fseCTable,
342
                        const U8* additionalBits,
343
                        short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
344
                        void* workspace, size_t wkspSize)
345
3.76M
{
346
3.76M
    unsigned* const countWksp = (unsigned*)workspace;
347
3.76M
    const BYTE* ctp = codeTable;
348
3.76M
    const BYTE* const ctStart = ctp;
349
3.76M
    const BYTE* const ctEnd = ctStart + nbSeq;
350
3.76M
    size_t cSymbolTypeSizeEstimateInBits = 0;
351
3.76M
    unsigned max = maxCode;
352
353
3.76M
    HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize);  /* can't fail */
354
3.76M
    if (type == set_basic) {
355
        /* We selected this encoding type, so it must be valid. */
356
2.10M
        assert(max <= defaultMax);
357
2.10M
        cSymbolTypeSizeEstimateInBits = max <= defaultMax
358
2.10M
                ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max)
359
2.10M
                : ERROR(GENERIC);
360
2.10M
    } else if (type == set_rle) {
361
103k
        cSymbolTypeSizeEstimateInBits = 0;
362
1.55M
    } else if (type == set_compressed || type == set_repeat) {
363
1.55M
        cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
364
1.55M
    }
365
3.76M
    if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) return nbSeq * 10;
366
151M
    while (ctp < ctEnd) {
367
147M
        if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
368
49.2M
        else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
369
147M
        ctp++;
370
147M
    }
371
3.76M
    return cSymbolTypeSizeEstimateInBits / 8;
372
3.76M
}
373
374
static size_t ZSTD_estimateSubBlockSize_sequences(const BYTE* ofCodeTable,
375
                                                  const BYTE* llCodeTable,
376
                                                  const BYTE* mlCodeTable,
377
                                                  size_t nbSeq,
378
                                                  const ZSTD_fseCTables_t* fseTables,
379
                                                  const ZSTD_fseCTablesMetadata_t* fseMetadata,
380
                                                  void* workspace, size_t wkspSize,
381
                                                  int writeEntropy)
382
1.25M
{
383
1.25M
    size_t const sequencesSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
384
1.25M
    size_t cSeqSizeEstimate = 0;
385
1.25M
    if (nbSeq == 0) return sequencesSectionHeaderSize;
386
1.25M
    cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, MaxOff,
387
1.25M
                                         nbSeq, fseTables->offcodeCTable, NULL,
388
1.25M
                                         OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
389
1.25M
                                         workspace, wkspSize);
390
1.25M
    cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->llType, llCodeTable, MaxLL,
391
1.25M
                                         nbSeq, fseTables->litlengthCTable, LL_bits,
392
1.25M
                                         LL_defaultNorm, LL_defaultNormLog, MaxLL,
393
1.25M
                                         workspace, wkspSize);
394
1.25M
    cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, MaxML,
395
1.25M
                                         nbSeq, fseTables->matchlengthCTable, ML_bits,
396
1.25M
                                         ML_defaultNorm, ML_defaultNormLog, MaxML,
397
1.25M
                                         workspace, wkspSize);
398
1.25M
    if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
399
1.25M
    return cSeqSizeEstimate + sequencesSectionHeaderSize;
400
1.25M
}
401
402
typedef struct {
403
    size_t estLitSize;
404
    size_t estBlockSize;
405
} EstimatedBlockSize;
406
static EstimatedBlockSize ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
407
                                        const BYTE* ofCodeTable,
408
                                        const BYTE* llCodeTable,
409
                                        const BYTE* mlCodeTable,
410
                                        size_t nbSeq,
411
                                        const ZSTD_entropyCTables_t* entropy,
412
                                        const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
413
                                        void* workspace, size_t wkspSize,
414
                                        int writeLitEntropy, int writeSeqEntropy)
415
1.25M
{
416
1.25M
    EstimatedBlockSize ebs;
417
1.25M
    ebs.estLitSize = ZSTD_estimateSubBlockSize_literal(literals, litSize,
418
1.25M
                                                        &entropy->huf, &entropyMetadata->hufMetadata,
419
1.25M
                                                        workspace, wkspSize, writeLitEntropy);
420
1.25M
    ebs.estBlockSize = ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
421
1.25M
                                                         nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
422
1.25M
                                                         workspace, wkspSize, writeSeqEntropy);
423
1.25M
    ebs.estBlockSize += ebs.estLitSize + ZSTD_blockHeaderSize;
424
1.25M
    return ebs;
425
1.25M
}
426
427
static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMetadata)
428
173k
{
429
173k
    if (fseMetadata->llType == set_compressed || fseMetadata->llType == set_rle)
430
866
        return 1;
431
172k
    if (fseMetadata->mlType == set_compressed || fseMetadata->mlType == set_rle)
432
3.40k
        return 1;
433
168k
    if (fseMetadata->ofType == set_compressed || fseMetadata->ofType == set_rle)
434
584
        return 1;
435
168k
    return 0;
436
168k
}
437
438
static size_t countLiterals(SeqStore_t const* seqStore, const SeqDef* sp, size_t seqCount)
439
35.0k
{
440
35.0k
    size_t n, total = 0;
441
35.0k
    assert(sp != NULL);
442
1.89M
    for (n=0; n<seqCount; n++) {
443
1.85M
        total += ZSTD_getSequenceLength(seqStore, sp+n).litLength;
444
1.85M
    }
445
35.0k
    DEBUGLOG(6, "countLiterals for %zu sequences from %p => %zu bytes", seqCount, (const void*)sp, total);
446
35.0k
    return total;
447
35.0k
}
448
449
3.86M
#define BYTESCALE 256
450
451
static size_t sizeBlockSequences(const SeqDef* sp, size_t nbSeqs,
452
                size_t targetBudget, size_t avgLitCost, size_t avgSeqCost,
453
                int firstSubBlock)
454
39.5k
{
455
39.5k
    size_t n, budget = 0, inSize=0;
456
    /* entropy headers */
457
39.5k
    size_t const headerSize = (size_t)firstSubBlock * 120 * BYTESCALE; /* generous estimate */
458
39.5k
    assert(firstSubBlock==0 || firstSubBlock==1);
459
39.5k
    budget += headerSize;
460
461
    /* first sequence => at least one sequence*/
462
39.5k
    budget += sp[0].litLength * avgLitCost + avgSeqCost;
463
39.5k
    if (budget > targetBudget) return 1;
464
25.9k
    inSize = sp[0].litLength + (sp[0].mlBase+MINMATCH);
465
466
    /* loop over sequences */
467
1.94M
    for (n=1; n<nbSeqs; n++) {
468
1.93M
        size_t currentCost = sp[n].litLength * avgLitCost + avgSeqCost;
469
1.93M
        budget += currentCost;
470
1.93M
        inSize += sp[n].litLength + (sp[n].mlBase+MINMATCH);
471
        /* stop when sub-block budget is reached */
472
1.93M
        if ( (budget > targetBudget)
473
            /* though continue to expand until the sub-block is deemed compressible */
474
62.7k
          && (budget < inSize * BYTESCALE) )
475
21.9k
            break;
476
1.93M
    }
477
478
25.9k
    return n;
479
39.5k
}
480
481
/** ZSTD_compressSubBlock_multi() :
482
 *  Breaks super-block into multiple sub-blocks and compresses them.
483
 *  Entropy will be written into the first block.
484
 *  The following blocks use repeat_mode to compress.
485
 *  Sub-blocks are all compressed, except the last one when beneficial.
486
 *  @return : compressed size of the super block (which features multiple ZSTD blocks)
487
 *            or 0 if it failed to compress. */
488
static size_t ZSTD_compressSubBlock_multi(const SeqStore_t* seqStorePtr,
489
                            const ZSTD_compressedBlockState_t* prevCBlock,
490
                            ZSTD_compressedBlockState_t* nextCBlock,
491
                            const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
492
                            const ZSTD_CCtx_params* cctxParams,
493
                                  void* dst, size_t dstCapacity,
494
                            const void* src, size_t srcSize,
495
                            const int bmi2, U32 lastBlock,
496
                            void* workspace, size_t wkspSize)
497
1.38M
{
498
1.38M
    const SeqDef* const sstart = seqStorePtr->sequencesStart;
499
1.38M
    const SeqDef* const send = seqStorePtr->sequences;
500
1.38M
    const SeqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */
501
1.38M
    size_t const nbSeqs = (size_t)(send - sstart);
502
1.38M
    const BYTE* const lstart = seqStorePtr->litStart;
503
1.38M
    const BYTE* const lend = seqStorePtr->lit;
504
1.38M
    const BYTE* lp = lstart;
505
1.38M
    size_t const nbLiterals = (size_t)(lend - lstart);
506
1.38M
    BYTE const* ip = (BYTE const*)src;
507
1.38M
    BYTE const* const iend = ip + srcSize;
508
1.38M
    BYTE* const ostart = (BYTE*)dst;
509
1.38M
    BYTE* const oend = ostart + dstCapacity;
510
1.38M
    BYTE* op = ostart;
511
1.38M
    const BYTE* llCodePtr = seqStorePtr->llCode;
512
1.38M
    const BYTE* mlCodePtr = seqStorePtr->mlCode;
513
1.38M
    const BYTE* ofCodePtr = seqStorePtr->ofCode;
514
1.38M
    size_t const minTarget = ZSTD_TARGETCBLOCKSIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */
515
1.38M
    size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
516
1.38M
    int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
517
1.38M
    int writeSeqEntropy = 1;
518
519
1.38M
    DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",
520
1.38M
               (unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));
521
522
        /* let's start by a general estimation for the full block */
523
1.38M
    if (nbSeqs > 0) {
524
1.25M
        EstimatedBlockSize const ebs =
525
1.25M
                ZSTD_estimateSubBlockSize(lp, nbLiterals,
526
1.25M
                                        ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
527
1.25M
                                        &nextCBlock->entropy, entropyMetadata,
528
1.25M
                                        workspace, wkspSize,
529
1.25M
                                        writeLitEntropy, writeSeqEntropy);
530
        /* quick estimation */
531
1.25M
        size_t const avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
532
1.25M
        size_t const avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
533
1.25M
        const size_t nbSubBlocks = MAX((ebs.estBlockSize + (targetCBlockSize/2)) / targetCBlockSize, 1);
534
1.25M
        size_t n, avgBlockBudget, blockBudgetSupp=0;
535
1.25M
        avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;
536
1.25M
        DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
537
1.25M
                    (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
538
1.25M
                    (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
539
        /* simplification: if estimates states that the full superblock doesn't compress, just bail out immediately
540
         * this will result in the production of a single uncompressed block covering @srcSize.*/
541
1.25M
        if (ebs.estBlockSize > srcSize) return 0;
542
543
        /* compress and write sub-blocks */
544
1.25M
        assert(nbSubBlocks>0);
545
1.26M
        for (n=0; n < nbSubBlocks-1; n++) {
546
            /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
547
39.5k
            size_t const seqCount = sizeBlockSequences(sp, (size_t)(send-sp),
548
39.5k
                                        avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
549
            /* if reached last sequence : break to last sub-block (simplification) */
550
39.5k
            assert(seqCount <= (size_t)(send-sp));
551
39.5k
            if (sp + seqCount == send) break;
552
39.5k
            assert(seqCount > 0);
553
            /* compress sub-block */
554
35.0k
            {   int litEntropyWritten = 0;
555
35.0k
                int seqEntropyWritten = 0;
556
35.0k
                size_t litSize = countLiterals(seqStorePtr, sp, seqCount);
557
35.0k
                const size_t decompressedSize =
558
35.0k
                        ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 0);
559
35.0k
                size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
560
35.0k
                                                sp, seqCount,
561
35.0k
                                                lp, litSize,
562
35.0k
                                                llCodePtr, mlCodePtr, ofCodePtr,
563
35.0k
                                                cctxParams,
564
35.0k
                                                op, (size_t)(oend-op),
565
35.0k
                                                bmi2, writeLitEntropy, writeSeqEntropy,
566
35.0k
                                                &litEntropyWritten, &seqEntropyWritten,
567
35.0k
                                                0);
568
35.0k
                FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
569
570
                /* check compressibility, update state components */
571
35.0k
                if (cSize > 0 && cSize < decompressedSize) {
572
23.2k
                    DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",
573
23.2k
                                (unsigned)decompressedSize, (unsigned)cSize);
574
23.2k
                    assert(ip + decompressedSize <= iend);
575
23.2k
                    ip += decompressedSize;
576
23.2k
                    lp += litSize;
577
23.2k
                    op += cSize;
578
23.2k
                    llCodePtr += seqCount;
579
23.2k
                    mlCodePtr += seqCount;
580
23.2k
                    ofCodePtr += seqCount;
581
                    /* Entropy only needs to be written once */
582
23.2k
                    if (litEntropyWritten) {
583
14.1k
                        writeLitEntropy = 0;
584
14.1k
                    }
585
23.2k
                    if (seqEntropyWritten) {
586
23.2k
                        writeSeqEntropy = 0;
587
23.2k
                    }
588
23.2k
                    sp += seqCount;
589
23.2k
                    blockBudgetSupp = 0;
590
23.2k
            }   }
591
            /* otherwise : do not compress yet, coalesce current sub-block with following one */
592
35.0k
        }
593
1.22M
    } /* if (nbSeqs > 0) */
594
595
    /* write last block */
596
1.36M
    DEBUGLOG(5, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
597
1.36M
    {   int litEntropyWritten = 0;
598
1.36M
        int seqEntropyWritten = 0;
599
1.36M
        size_t litSize = (size_t)(lend - lp);
600
1.36M
        size_t seqCount = (size_t)(send - sp);
601
1.36M
        const size_t decompressedSize =
602
1.36M
                ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);
603
1.36M
        size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
604
1.36M
                                            sp, seqCount,
605
1.36M
                                            lp, litSize,
606
1.36M
                                            llCodePtr, mlCodePtr, ofCodePtr,
607
1.36M
                                            cctxParams,
608
1.36M
                                            op, (size_t)(oend-op),
609
1.36M
                                            bmi2, writeLitEntropy, writeSeqEntropy,
610
1.36M
                                            &litEntropyWritten, &seqEntropyWritten,
611
1.36M
                                            lastBlock);
612
1.36M
        FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
613
614
        /* update pointers, the nb of literals borrowed from next sequence must be preserved */
615
1.36M
        if (cSize > 0 && cSize < decompressedSize) {
616
1.21M
            DEBUGLOG(5, "Last sub-block compressed %u bytes => %u bytes",
617
1.21M
                        (unsigned)decompressedSize, (unsigned)cSize);
618
1.21M
            assert(ip + decompressedSize <= iend);
619
1.21M
            ip += decompressedSize;
620
1.21M
            lp += litSize;
621
1.21M
            op += cSize;
622
1.21M
            llCodePtr += seqCount;
623
1.21M
            mlCodePtr += seqCount;
624
1.21M
            ofCodePtr += seqCount;
625
            /* Entropy only needs to be written once */
626
1.21M
            if (litEntropyWritten) {
627
536k
                writeLitEntropy = 0;
628
536k
            }
629
1.21M
            if (seqEntropyWritten) {
630
1.18M
                writeSeqEntropy = 0;
631
1.18M
            }
632
1.21M
            sp += seqCount;
633
1.21M
        }
634
1.36M
    }
635
636
637
1.36M
    if (writeLitEntropy) {
638
6.91k
        DEBUGLOG(5, "Literal entropy tables were never written");
639
6.91k
        ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
640
6.91k
    }
641
1.36M
    if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {
642
        /* If we haven't written our entropy tables, then we've violated our contract and
643
         * must emit an uncompressed block.
644
         */
645
4.85k
        DEBUGLOG(5, "Sequence entropy tables were never written => cancel, emit an uncompressed block");
646
4.85k
        return 0;
647
4.85k
    }
648
649
1.35M
    if (ip < iend) {
650
        /* some data left : last part of the block sent uncompressed */
651
138k
        size_t const rSize = (size_t)((iend - ip));
652
138k
        size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);
653
138k
        DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
654
138k
        FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
655
138k
        assert(cSize != 0);
656
138k
        op += cSize;
657
        /* We have to regenerate the repcodes because we've skipped some sequences */
658
138k
        if (sp < send) {
659
35.3k
            const SeqDef* seq;
660
35.3k
            Repcodes_t rep;
661
35.3k
            ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
662
101k
            for (seq = sstart; seq < sp; ++seq) {
663
66.6k
                ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
664
66.6k
            }
665
35.3k
            ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
666
35.3k
        }
667
138k
    }
668
669
1.35M
    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed all subBlocks: total compressed size = %u",
670
1.35M
                (unsigned)(op-ostart));
671
1.35M
    return (size_t)(op-ostart);
672
1.35M
}
673
674
size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
675
                               void* dst, size_t dstCapacity,
676
                               const void* src, size_t srcSize,
677
                               unsigned lastBlock)
678
1.38M
{
679
1.38M
    ZSTD_entropyCTablesMetadata_t entropyMetadata;
680
681
1.38M
    FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,
682
1.38M
          &zc->blockState.prevCBlock->entropy,
683
1.38M
          &zc->blockState.nextCBlock->entropy,
684
1.38M
          &zc->appliedParams,
685
1.38M
          &entropyMetadata,
686
1.38M
          zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */), "");
687
688
1.38M
    return ZSTD_compressSubBlock_multi(&zc->seqStore,
689
1.38M
            zc->blockState.prevCBlock,
690
1.38M
            zc->blockState.nextCBlock,
691
1.38M
            &entropyMetadata,
692
1.38M
            &zc->appliedParams,
693
1.38M
            dst, dstCapacity,
694
1.38M
            src, srcSize,
695
1.38M
            ZSTD_CCtx_get_bmi2(zc), lastBlock,
696
1.38M
            zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */);
697
1.38M
}