Coverage Report

Created: 2026-10-28 07:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/compress/huf_compress.c
Line
Count
Source
1
/* ******************************************************************
2
 * Huffman encoder, part of New Generation Entropy library
3
 * Copyright (c) Meta Platforms, Inc. and affiliates.
4
 *
5
 *  You can contact the author at :
6
 *  - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
7
 *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
8
 *
9
 * This source code is licensed under both the BSD-style license (found in the
10
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11
 * in the COPYING file in the root directory of this source tree).
12
 * You may select, at your option, one of the above-listed licenses.
13
****************************************************************** */
14
15
/* **************************************************************
16
*  Compiler specifics
17
****************************************************************/
18
#ifdef _MSC_VER    /* Visual Studio */
19
#  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
20
#endif
21
22
23
/* **************************************************************
24
*  Includes
25
****************************************************************/
26
#include "../common/zstd_deps.h"     /* ZSTD_memcpy, ZSTD_memset */
27
#include "../common/bmi2.h"
28
#include "../common/compiler.h"
29
#include "../common/bitstream.h"
30
#include "hist.h"
31
#define FSE_STATIC_LINKING_ONLY   /* FSE_optimalTableLog_internal */
32
#include "../common/fse.h"        /* header compression */
33
#include "../common/huf.h"
34
#include "../common/error_private.h"
35
#include "../common/bits.h"       /* ZSTD_highbit32 */
36
37
38
/* **************************************************************
39
*  Error Management
40
****************************************************************/
41
20.4k
#define HUF_isError ERR_isError
42
21.7k
#define HUF_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)   /* use only *after* variable declarations */
43
44
45
/* **************************************************************
46
*  Required declarations
47
****************************************************************/
48
typedef struct nodeElt_s {
49
    U32 count;
50
    U16 parent;
51
    BYTE byte;
52
    BYTE nbBits;
53
} nodeElt;
54
55
56
/* **************************************************************
57
*  Debug Traces
58
****************************************************************/
59
60
#if DEBUGLEVEL >= 2
61
62
static size_t showU32(const U32* arr, size_t size)
63
{
64
    size_t u;
65
    for (u=0; u<size; u++) {
66
        RAWLOG(6, " %u", arr[u]); (void)arr;
67
    }
68
    RAWLOG(6, " \n");
69
    return size;
70
}
71
72
static size_t HUF_getNbBits(HUF_CElt elt);
73
74
static size_t showCTableBits(const HUF_CElt* ctable, size_t size)
75
{
76
    size_t u;
77
    for (u=0; u<size; u++) {
78
        RAWLOG(6, " %zu", HUF_getNbBits(ctable[u])); (void)ctable;
79
    }
80
    RAWLOG(6, " \n");
81
    return size;
82
83
}
84
85
static size_t showHNodeSymbols(const nodeElt* hnode, size_t size)
86
{
87
    size_t u;
88
    for (u=0; u<size; u++) {
89
        RAWLOG(6, " %u", hnode[u].byte); (void)hnode;
90
    }
91
    RAWLOG(6, " \n");
92
    return size;
93
}
94
95
static size_t showHNodeBits(const nodeElt* hnode, size_t size)
96
{
97
    size_t u;
98
    for (u=0; u<size; u++) {
99
        RAWLOG(6, " %u", hnode[u].nbBits); (void)hnode;
100
    }
101
    RAWLOG(6, " \n");
102
    return size;
103
}
104
105
#endif
106
107
108
/* *******************************************************
109
*  HUF : Huffman block compression
110
*********************************************************/
111
#define HUF_WORKSPACE_MAX_ALIGNMENT 8
112
113
static void* HUF_alignUpWorkspace(void* workspace, size_t* workspaceSizePtr, size_t align)
114
21.7k
{
115
21.7k
    size_t const mask = align - 1;
116
21.7k
    size_t const rem = (size_t)workspace & mask;
117
21.7k
    size_t const add = (align - rem) & mask;
118
21.7k
    BYTE* const aligned = (BYTE*)workspace + add;
119
21.7k
    assert((align & (align - 1)) == 0); /* pow 2 */
120
21.7k
    assert(align <= HUF_WORKSPACE_MAX_ALIGNMENT);
121
21.7k
    if (*workspaceSizePtr >= add) {
122
21.7k
        assert(add < align);
123
21.7k
        assert(((size_t)aligned & mask) == 0);
124
21.7k
        *workspaceSizePtr -= add;
125
21.7k
        return aligned;
126
21.7k
    } else {
127
0
        *workspaceSizePtr = 0;
128
0
        return NULL;
129
0
    }
130
21.7k
}
131
132
133
/* HUF_compressWeights() :
134
 * Same as FSE_compress(), but dedicated to huff0's weights compression.
135
 * The use case needs much less stack memory.
136
 * Note : all elements within weightTable are supposed to be <= HUF_TABLELOG_MAX.
137
 */
138
5.42k
#define MAX_FSE_TABLELOG_FOR_HUFF_HEADER 6
139
140
typedef struct {
141
    FSE_CTable CTable[FSE_CTABLE_SIZE_U32(MAX_FSE_TABLELOG_FOR_HUFF_HEADER, HUF_TABLELOG_MAX)];
142
    U32 scratchBuffer[FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(HUF_TABLELOG_MAX, MAX_FSE_TABLELOG_FOR_HUFF_HEADER)];
143
    unsigned count[HUF_TABLELOG_MAX+1];
144
    S16 norm[HUF_TABLELOG_MAX+1];
145
} HUF_CompressWeightsWksp;
146
147
static size_t
148
HUF_compressWeights(void* dst, size_t dstSize,
149
              const void* weightTable, size_t wtSize,
150
                    void* workspace, size_t workspaceSize)
151
5.42k
{
152
5.42k
    BYTE* const ostart = (BYTE*) dst;
153
5.42k
    BYTE* op = ostart;
154
5.42k
    BYTE* const oend = ostart + dstSize;
155
156
5.42k
    unsigned maxSymbolValue = HUF_TABLELOG_MAX;
157
5.42k
    U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;
158
5.42k
    HUF_CompressWeightsWksp* wksp = (HUF_CompressWeightsWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));
159
160
5.42k
    if (workspaceSize < sizeof(HUF_CompressWeightsWksp)) return ERROR(GENERIC);
161
162
    /* init conditions */
163
5.42k
    if (wtSize <= 1) return 0;  /* Not compressible */
164
165
    /* Scan input and build symbol stats */
166
5.37k
    {   unsigned const maxCount = HIST_count_simple(wksp->count, &maxSymbolValue, weightTable, wtSize);   /* never fails */
167
5.37k
        if (maxCount == wtSize) return 1;   /* only a single symbol in src : rle */
168
5.37k
        if (maxCount == 1) return 0;        /* each symbol present maximum once => not compressible */
169
5.37k
    }
170
171
5.37k
    tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);
172
5.37k
    CHECK_F( FSE_normalizeCount(wksp->norm, tableLog, wksp->count, wtSize, maxSymbolValue, /* useLowProbCount */ 0) );
173
174
    /* Write table description header */
175
5.37k
    {   CHECK_V_F(hSize, FSE_writeNCount(op, (size_t)(oend-op), wksp->norm, maxSymbolValue, tableLog) );
176
5.37k
        op += hSize;
177
5.37k
    }
178
179
    /* Compress */
180
5.37k
    CHECK_F( FSE_buildCTable_wksp(wksp->CTable, wksp->norm, maxSymbolValue, tableLog, wksp->scratchBuffer, sizeof(wksp->scratchBuffer)) );
181
5.37k
    {   CHECK_V_F(cSize, FSE_compress_usingCTable(op, (size_t)(oend - op), weightTable, wtSize, wksp->CTable) );
182
5.37k
        if (cSize == 0) return 0;   /* not enough space for compressed data */
183
5.37k
        op += cSize;
184
5.37k
    }
185
186
0
    return (size_t)(op-ostart);
187
5.37k
}
188
189
static size_t HUF_getNbBits(HUF_CElt elt)
190
14.1M
{
191
14.1M
    return elt & 0xFF;
192
14.1M
}
193
194
static size_t HUF_getNbBitsFast(HUF_CElt elt)
195
8.40M
{
196
8.40M
    return elt;
197
8.40M
}
198
199
static size_t HUF_getValue(HUF_CElt elt)
200
708k
{
201
708k
    return elt & ~(size_t)0xFF;
202
708k
}
203
204
static size_t HUF_getValueFast(HUF_CElt elt)
205
7.69M
{
206
7.69M
    return elt;
207
7.69M
}
208
209
static void HUF_setNbBits(HUF_CElt* elt, size_t nbBits)
210
1.38M
{
211
1.38M
    assert(nbBits <= HUF_TABLELOG_ABSOLUTEMAX);
212
1.38M
    *elt = nbBits;
213
1.38M
}
214
215
static void HUF_setValue(HUF_CElt* elt, size_t value)
216
1.38M
{
217
1.38M
    size_t const nbBits = HUF_getNbBits(*elt);
218
1.38M
    if (nbBits > 0) {
219
274k
        assert((value >> nbBits) == 0);
220
274k
        *elt |= value << (sizeof(HUF_CElt) * 8 - nbBits);
221
274k
    }
222
1.38M
}
223
224
HUF_CTableHeader HUF_readCTableHeader(HUF_CElt const* ctable)
225
17.1k
{
226
17.1k
    HUF_CTableHeader header;
227
17.1k
    ZSTD_memcpy(&header, ctable, sizeof(header));
228
17.1k
    return header;
229
17.1k
}
230
231
static void HUF_writeCTableHeader(HUF_CElt* ctable, U32 tableLog, U32 maxSymbolValue)
232
5.42k
{
233
5.42k
    HUF_CTableHeader header;
234
5.42k
    HUF_STATIC_ASSERT(sizeof(ctable[0]) == sizeof(header));
235
5.42k
    ZSTD_memset(&header, 0, sizeof(header));
236
5.42k
    assert(tableLog < 256);
237
5.42k
    header.tableLog = (BYTE)tableLog;
238
5.42k
    assert(maxSymbolValue < 256);
239
5.42k
    header.maxSymbolValue = (BYTE)maxSymbolValue;
240
5.42k
    ZSTD_memcpy(ctable, &header, sizeof(header));
241
5.42k
}
242
243
typedef struct {
244
    HUF_CompressWeightsWksp wksp;
245
    BYTE bitsToWeight[HUF_TABLELOG_MAX + 1];   /* precomputed conversion table */
246
    BYTE huffWeight[HUF_SYMBOLVALUE_MAX];
247
} HUF_WriteCTableWksp;
248
249
size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize,
250
                            const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog,
251
                            void* workspace, size_t workspaceSize)
252
5.42k
{
253
5.42k
    HUF_CElt const* const ct = CTable + 1;
254
5.42k
    BYTE* op = (BYTE*)dst;
255
5.42k
    U32 n;
256
5.42k
    HUF_WriteCTableWksp* wksp = (HUF_WriteCTableWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));
257
258
5.42k
    HUF_STATIC_ASSERT(HUF_CTABLE_WORKSPACE_SIZE >= sizeof(HUF_WriteCTableWksp));
259
260
5.42k
    assert(HUF_readCTableHeader(CTable).maxSymbolValue == maxSymbolValue);
261
5.42k
    assert(HUF_readCTableHeader(CTable).tableLog == huffLog);
262
263
    /* check conditions */
264
5.42k
    if (workspaceSize < sizeof(HUF_WriteCTableWksp)) return ERROR(GENERIC);
265
5.42k
    if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
266
267
    /* convert to weight */
268
5.42k
    wksp->bitsToWeight[0] = 0;
269
29.5k
    for (n=1; n<huffLog+1; n++)
270
24.1k
        wksp->bitsToWeight[n] = (BYTE)(huffLog + 1 - n);
271
1.36M
    for (n=0; n<maxSymbolValue; n++)
272
1.36M
        wksp->huffWeight[n] = wksp->bitsToWeight[HUF_getNbBits(ct[n])];
273
274
    /* attempt weights compression by FSE */
275
5.42k
    if (maxDstSize < 1) return ERROR(dstSize_tooSmall);
276
5.42k
    {   CHECK_V_F(hSize, HUF_compressWeights(op+1, maxDstSize-1, wksp->huffWeight, maxSymbolValue, &wksp->wksp, sizeof(wksp->wksp)) );
277
5.42k
        if ((hSize>1) & (hSize < maxSymbolValue/2)) {   /* FSE compressed */
278
5.37k
            op[0] = (BYTE)hSize;
279
5.37k
            return hSize+1;
280
5.37k
    }   }
281
282
    /* write raw values as 4-bits (max : 15) */
283
48
    if (maxSymbolValue > (256-128)) return ERROR(GENERIC);   /* should not happen : likely means source cannot be compressed */
284
48
    if (((maxSymbolValue+1)/2) + 1 > maxDstSize) return ERROR(dstSize_tooSmall);   /* not enough space within dst buffer */
285
48
    op[0] = (BYTE)(128 /*special case*/ + (maxSymbolValue-1));
286
48
    wksp->huffWeight[maxSymbolValue] = 0;   /* to be sure it doesn't cause msan issue in final combination */
287
96
    for (n=0; n<maxSymbolValue; n+=2)
288
48
        op[(n/2)+1] = (BYTE)((wksp->huffWeight[n] << 4) + wksp->huffWeight[n+1]);
289
48
    return ((maxSymbolValue+1)/2) + 1;
290
48
}
291
292
293
size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned* hasZeroWeights)
294
0
{
295
0
    BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1];   /* init not required, even though some static analyzer may complain */
296
0
    U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1];   /* large enough for values from 0 to 16 */
297
0
    U32 tableLog = 0;
298
0
    U32 nbSymbols = 0;
299
0
    HUF_CElt* const ct = CTable + 1;
300
301
    /* get symbol weights */
302
0
    CHECK_V_F(readSize, HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX+1, rankVal, &nbSymbols, &tableLog, src, srcSize));
303
0
    *hasZeroWeights = (rankVal[0] > 0);
304
305
    /* check result */
306
0
    if (tableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
307
0
    if (nbSymbols > *maxSymbolValuePtr+1) return ERROR(maxSymbolValue_tooSmall);
308
309
0
    *maxSymbolValuePtr = nbSymbols - 1;
310
311
0
    HUF_writeCTableHeader(CTable, tableLog, *maxSymbolValuePtr);
312
313
    /* Prepare base value per rank */
314
0
    {   U32 n, nextRankStart = 0;
315
0
        for (n=1; n<=tableLog; n++) {
316
0
            U32 curr = nextRankStart;
317
0
            nextRankStart += (rankVal[n] << (n-1));
318
0
            rankVal[n] = curr;
319
0
    }   }
320
321
    /* fill nbBits */
322
0
    {   U32 n; for (n=0; n<nbSymbols; n++) {
323
0
            const U32 w = huffWeight[n];
324
0
            HUF_setNbBits(ct + n, (BYTE)(tableLog + 1 - w) & -(w != 0));
325
0
    }   }
326
327
    /* fill val */
328
0
    {   U16 nbPerRank[HUF_TABLELOG_MAX+2]  = {0};  /* support w=0=>n=tableLog+1 */
329
0
        U16 valPerRank[HUF_TABLELOG_MAX+2] = {0};
330
0
        { U32 n; for (n=0; n<nbSymbols; n++) nbPerRank[HUF_getNbBits(ct[n])]++; }
331
        /* determine stating value per rank */
332
0
        valPerRank[tableLog+1] = 0;   /* for w==0 */
333
0
        {   U16 min = 0;
334
0
            U32 n; for (n=tableLog; n>0; n--) {  /* start at n=tablelog <-> w=1 */
335
0
                valPerRank[n] = min;     /* get starting value within each rank */
336
0
                min += nbPerRank[n];
337
0
                min >>= 1;
338
0
        }   }
339
        /* assign value within rank, symbol order */
340
0
        { U32 n; for (n=0; n<nbSymbols; n++) HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++); }
341
0
    }
342
343
0
    return readSize;
344
0
}
345
346
U32 HUF_getNbBitsFromCTable(HUF_CElt const* CTable, U32 symbolValue)
347
0
{
348
0
    const HUF_CElt* const ct = CTable + 1;
349
0
    assert(symbolValue <= HUF_SYMBOLVALUE_MAX);
350
0
    if (symbolValue > HUF_readCTableHeader(CTable).maxSymbolValue)
351
0
        return 0;
352
0
    return (U32)HUF_getNbBits(ct[symbolValue]);
353
0
}
354
355
356
/**
357
 * HUF_setMaxHeight():
358
 * Try to enforce @targetNbBits on the Huffman tree described in @huffNode.
359
 *
360
 * It attempts to convert all nodes with nbBits > @targetNbBits
361
 * to employ @targetNbBits instead. Then it adjusts the tree
362
 * so that it remains a valid canonical Huffman tree.
363
 *
364
 * @pre               The sum of the ranks of each symbol == 2^largestBits,
365
 *                    where largestBits == huffNode[lastNonNull].nbBits.
366
 * @post              The sum of the ranks of each symbol == 2^largestBits,
367
 *                    where largestBits is the return value (expected <= targetNbBits).
368
 *
369
 * @param huffNode    The Huffman tree modified in place to enforce targetNbBits.
370
 *                    It's presumed sorted, from most frequent to rarest symbol.
371
 * @param lastNonNull The symbol with the lowest count in the Huffman tree.
372
 * @param targetNbBits  The allowed number of bits, which the Huffman tree
373
 *                    may not respect. After this function the Huffman tree will
374
 *                    respect targetNbBits.
375
 * @return            The maximum number of bits of the Huffman tree after adjustment.
376
 */
377
static U32 HUF_setMaxHeight(nodeElt* huffNode, U32 lastNonNull, U32 targetNbBits)
378
5.42k
{
379
5.42k
    const U32 largestBits = huffNode[lastNonNull].nbBits;
380
    /* early exit : no elt > targetNbBits, so the tree is already valid. */
381
5.42k
    if (largestBits <= targetNbBits) return largestBits;
382
383
734
    DEBUGLOG(5, "HUF_setMaxHeight (targetNbBits = %u)", targetNbBits);
384
385
    /* there are several too large elements (at least >= 2) */
386
734
    {   int totalCost = 0;
387
734
        const U32 baseCost = 1 << (largestBits - targetNbBits);
388
734
        int n = (int)lastNonNull;
389
390
        /* Adjust any ranks > targetNbBits to targetNbBits.
391
         * Compute totalCost, which is how far the sum of the ranks is
392
         * we are over 2^largestBits after adjust the offending ranks.
393
         */
394
22.1k
        while (huffNode[n].nbBits > targetNbBits) {
395
21.4k
            totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));
396
21.4k
            huffNode[n].nbBits = (BYTE)targetNbBits;
397
21.4k
            n--;
398
21.4k
        }
399
        /* n stops at huffNode[n].nbBits <= targetNbBits */
400
734
        assert(huffNode[n].nbBits <= targetNbBits);
401
        /* n end at index of smallest symbol using < targetNbBits */
402
36.0k
        while (huffNode[n].nbBits == targetNbBits) --n;
403
404
        /* renorm totalCost from 2^largestBits to 2^targetNbBits
405
         * note : totalCost is necessarily a multiple of baseCost */
406
734
        assert(((U32)totalCost & (baseCost - 1)) == 0);
407
734
        totalCost >>= (largestBits - targetNbBits);
408
734
        assert(totalCost > 0);
409
410
        /* repay normalized cost */
411
734
        {   U32 const noSymbol = 0xF0F0F0F0;
412
734
            U32 rankLast[HUF_TABLELOG_MAX+2];
413
414
            /* Get pos of last (smallest = lowest cum. count) symbol per rank */
415
734
            ZSTD_memset(rankLast, 0xF0, sizeof(rankLast));
416
734
            {   U32 currentNbBits = targetNbBits;
417
734
                int pos;
418
87.6k
                for (pos=n ; pos >= 0; pos--) {
419
86.9k
                    if (huffNode[pos].nbBits >= currentNbBits) continue;
420
3.94k
                    currentNbBits = huffNode[pos].nbBits;   /* < targetNbBits */
421
3.94k
                    rankLast[targetNbBits-currentNbBits] = (U32)pos;
422
3.94k
            }   }
423
424
4.03k
            while (totalCost > 0) {
425
                /* Try to reduce the next power of 2 above totalCost because we
426
                 * gain back half the rank.
427
                 */
428
3.30k
                U32 nBitsToDecrease = ZSTD_highbit32((U32)totalCost) + 1;
429
3.30k
                assert(nBitsToDecrease <= HUF_TABLELOG_MAX+1);
430
7.75k
                for ( ; nBitsToDecrease > 1; nBitsToDecrease--) {
431
6.44k
                    U32 const highPos = rankLast[nBitsToDecrease];
432
6.44k
                    U32 const lowPos = rankLast[nBitsToDecrease-1];
433
6.44k
                    if (highPos == noSymbol) continue;
434
                    /* Decrease highPos if no symbols of lowPos or if it is
435
                     * not cheaper to remove 2 lowPos than highPos.
436
                     */
437
5.03k
                    if (lowPos == noSymbol) break;
438
4.83k
                    {   U32 const highTotal = huffNode[highPos].count;
439
4.83k
                        U32 const lowTotal = 2 * huffNode[lowPos].count;
440
4.83k
                        if (highTotal <= lowTotal) break;
441
4.83k
                }   }
442
                /* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */
443
3.30k
                assert(rankLast[nBitsToDecrease] != noSymbol || nBitsToDecrease == 1);
444
                /* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */
445
3.39k
                while ((nBitsToDecrease<=HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))
446
98
                    nBitsToDecrease++;
447
3.30k
                assert(rankLast[nBitsToDecrease] != noSymbol);
448
                /* Increase the number of bits to gain back half the rank cost. */
449
3.30k
                totalCost -= 1 << (nBitsToDecrease-1);
450
3.30k
                huffNode[rankLast[nBitsToDecrease]].nbBits++;
451
452
                /* Fix up the new rank.
453
                 * If the new rank was empty, this symbol is now its smallest.
454
                 * Otherwise, this symbol will be the largest in the new rank so no adjustment.
455
                 */
456
3.30k
                if (rankLast[nBitsToDecrease-1] == noSymbol)
457
721
                    rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease];
458
                /* Fix up the old rank.
459
                 * If the symbol was at position 0, meaning it was the highest weight symbol in the tree,
460
                 * it must be the only symbol in its rank, so the old rank now has no symbols.
461
                 * Otherwise, since the Huffman nodes are sorted by count, the previous position is now
462
                 * the smallest node in the rank. If the previous position belongs to a different rank,
463
                 * then the rank is now empty.
464
                 */
465
3.30k
                if (rankLast[nBitsToDecrease] == 0)    /* special case, reached largest symbol */
466
31
                    rankLast[nBitsToDecrease] = noSymbol;
467
3.27k
                else {
468
3.27k
                    rankLast[nBitsToDecrease]--;
469
3.27k
                    if (huffNode[rankLast[nBitsToDecrease]].nbBits != targetNbBits-nBitsToDecrease)
470
300
                        rankLast[nBitsToDecrease] = noSymbol;   /* this rank is now empty */
471
3.27k
                }
472
3.30k
            }   /* while (totalCost > 0) */
473
474
            /* If we've removed too much weight, then we have to add it back.
475
             * To avoid overshooting again, we only adjust the smallest rank.
476
             * We take the largest nodes from the lowest rank 0 and move them
477
             * to rank 1. There's guaranteed to be enough rank 0 symbols because
478
             * TODO.
479
             */
480
995
            while (totalCost < 0) {  /* Sometimes, cost correction overshoot */
481
                /* special case : no rank 1 symbol (using targetNbBits-1);
482
                 * let's create one from largest rank 0 (using targetNbBits).
483
                 */
484
261
                if (rankLast[1] == noSymbol) {
485
189
                    while (huffNode[n].nbBits == targetNbBits) n--;
486
30
                    huffNode[n+1].nbBits--;
487
30
                    assert(n >= 0);
488
30
                    rankLast[1] = (U32)(n+1);
489
30
                    totalCost++;
490
30
                    continue;
491
30
                }
492
231
                huffNode[ rankLast[1] + 1 ].nbBits--;
493
231
                rankLast[1]++;
494
231
                totalCost ++;
495
231
            }
496
734
        }   /* repay normalized cost */
497
734
    }   /* there are several too large elements (at least >= 2) */
498
499
734
    return targetNbBits;
500
5.42k
}
501
502
typedef struct {
503
    U16 base;
504
    U16 curr;
505
} rankPos;
506
507
typedef nodeElt huffNodeTable[2 * (HUF_SYMBOLVALUE_MAX + 1)];
508
509
/* Number of buckets available for HUF_sort() */
510
5.66M
#define RANK_POSITION_TABLE_SIZE 192
511
512
typedef struct {
513
  huffNodeTable huffNodeTbl;
514
  rankPos rankPosition[RANK_POSITION_TABLE_SIZE];
515
} HUF_buildCTable_wksp_tables;
516
517
/* RANK_POSITION_DISTINCT_COUNT_CUTOFF == Cutoff point in HUF_sort() buckets for which we use log2 bucketing.
518
 * Strategy is to use as many buckets as possible for representing distinct
519
 * counts while using the remainder to represent all "large" counts.
520
 *
521
 * To satisfy this requirement for 192 buckets, we can do the following:
522
 * Let buckets 0-166 represent distinct counts of [0, 166]
523
 * Let buckets 166 to 192 represent all remaining counts up to RANK_POSITION_MAX_COUNT_LOG using log2 bucketing.
524
 */
525
5.51M
#define RANK_POSITION_MAX_COUNT_LOG 32
526
5.51M
#define RANK_POSITION_LOG_BUCKETS_BEGIN ((RANK_POSITION_TABLE_SIZE - 1) - RANK_POSITION_MAX_COUNT_LOG - 1 /* == 158 */)
527
2.74M
#define RANK_POSITION_DISTINCT_COUNT_CUTOFF (RANK_POSITION_LOG_BUCKETS_BEGIN + ZSTD_highbit32(RANK_POSITION_LOG_BUCKETS_BEGIN) /* == 166 */)
528
529
/* Return the appropriate bucket index for a given count. See definition of
530
 * RANK_POSITION_DISTINCT_COUNT_CUTOFF for explanation of bucketing strategy.
531
 */
532
2.73M
static U32 HUF_getIndex(U32 const count) {
533
2.73M
    return (count < RANK_POSITION_DISTINCT_COUNT_CUTOFF)
534
2.73M
        ? count
535
2.73M
        : ZSTD_highbit32(count) + RANK_POSITION_LOG_BUCKETS_BEGIN;
536
2.73M
}
537
538
/* Helper swap function for HUF_quickSortPartition() */
539
13.8k
static void HUF_swapNodes(nodeElt* a, nodeElt* b) {
540
13.8k
  nodeElt tmp = *a;
541
13.8k
  *a = *b;
542
13.8k
  *b = tmp;
543
13.8k
}
544
545
/* Returns 0 if the huffNode array is not sorted by descending count */
546
0
MEM_STATIC int HUF_isSorted(nodeElt huffNode[], U32 const maxSymbolValue1) {
547
0
    U32 i;
548
0
    for (i = 1; i < maxSymbolValue1; ++i) {
549
0
        if (huffNode[i].count > huffNode[i-1].count) {
550
0
            return 0;
551
0
        }
552
0
    }
553
0
    return 1;
554
0
}
555
556
/* Insertion sort by descending order */
557
3.97k
HINT_INLINE void HUF_insertionSort(nodeElt huffNode[], int const low, int const high) {
558
3.97k
    int i;
559
3.97k
    int const size = high-low+1;
560
3.97k
    huffNode += low;
561
8.59k
    for (i = 1; i < size; ++i) {
562
4.62k
        nodeElt const key = huffNode[i];
563
4.62k
        int j = i - 1;
564
8.26k
        while (j >= 0 && huffNode[j].count < key.count) {
565
3.64k
            huffNode[j + 1] = huffNode[j];
566
3.64k
            j--;
567
3.64k
        }
568
4.62k
        huffNode[j + 1] = key;
569
4.62k
    }
570
3.97k
}
571
572
/* Pivot helper function for quicksort. */
573
2.22k
static int HUF_quickSortPartition(nodeElt arr[], int const low, int const high) {
574
    /* Simply select rightmost element as pivot. "Better" selectors like
575
     * median-of-three don't experimentally appear to have any benefit.
576
     */
577
2.22k
    U32 const pivot = arr[high].count;
578
2.22k
    int i = low - 1;
579
2.22k
    int j = low;
580
30.0k
    for ( ; j < high; j++) {
581
27.8k
        if (arr[j].count > pivot) {
582
11.5k
            i++;
583
11.5k
            HUF_swapNodes(&arr[i], &arr[j]);
584
11.5k
        }
585
27.8k
    }
586
2.22k
    HUF_swapNodes(&arr[i + 1], &arr[high]);
587
2.22k
    return i + 1;
588
2.22k
}
589
590
/* Classic quicksort by descending with partially iterative calls
591
 * to reduce worst case callstack size.
592
 */
593
4.29k
static void HUF_simpleQuickSort(nodeElt arr[], int low, int high) {
594
4.29k
    int const kInsertionSortThreshold = 8;
595
4.29k
    if (high - low < kInsertionSortThreshold) {
596
3.97k
        HUF_insertionSort(arr, low, high);
597
3.97k
        return;
598
3.97k
    }
599
2.54k
    while (low < high) {
600
2.22k
        int const idx = HUF_quickSortPartition(arr, low, high);
601
2.22k
        if (idx - low < high - idx) {
602
1.24k
            HUF_simpleQuickSort(arr, low, idx - 1);
603
1.24k
            low = idx + 1;
604
1.24k
        } else {
605
978
            HUF_simpleQuickSort(arr, idx + 1, high);
606
978
            high = idx - 1;
607
978
        }
608
2.22k
    }
609
316
}
610
611
/**
612
 * HUF_sort():
613
 * Sorts the symbols [0, maxSymbolValue] by count[symbol] in decreasing order.
614
 * This is a typical bucket sorting strategy that uses either quicksort or insertion sort to sort each bucket.
615
 *
616
 * @param[out] huffNode       Sorted symbols by decreasing count. Only members `.count` and `.byte` are filled.
617
 *                            Must have (maxSymbolValue + 1) entries.
618
 * @param[in]  count          Histogram of the symbols.
619
 * @param[in]  maxSymbolValue Maximum symbol value.
620
 * @param      rankPosition   This is a scratch workspace. Must have RANK_POSITION_TABLE_SIZE entries.
621
 */
622
5.42k
static void HUF_sort(nodeElt huffNode[], const unsigned count[], U32 const maxSymbolValue, rankPos rankPosition[]) {
623
5.42k
    U32 n;
624
5.42k
    U32 const maxSymbolValue1 = maxSymbolValue+1;
625
626
    /* Compute base and set curr to base.
627
     * For symbol s let lowerRank = HUF_getIndex(count[n]) and rank = lowerRank + 1.
628
     * See HUF_getIndex to see bucketing strategy.
629
     * We attribute each symbol to lowerRank's base value, because we want to know where
630
     * each rank begins in the output, so for rank R we want to count ranks R+1 and above.
631
     */
632
5.42k
    ZSTD_memset(rankPosition, 0, sizeof(*rankPosition) * RANK_POSITION_TABLE_SIZE);
633
1.37M
    for (n = 0; n < maxSymbolValue1; ++n) {
634
1.36M
        U32 lowerRank = HUF_getIndex(count[n]);
635
1.36M
        assert(lowerRank < RANK_POSITION_TABLE_SIZE - 1);
636
1.36M
        rankPosition[lowerRank].base++;
637
1.36M
    }
638
639
5.42k
    assert(rankPosition[RANK_POSITION_TABLE_SIZE - 1].base == 0);
640
    /* Set up the rankPosition table */
641
1.04M
    for (n = RANK_POSITION_TABLE_SIZE - 1; n > 0; --n) {
642
1.03M
        rankPosition[n-1].base += rankPosition[n].base;
643
1.03M
        rankPosition[n-1].curr = rankPosition[n-1].base;
644
1.03M
    }
645
646
    /* Insert each symbol into their appropriate bucket, setting up rankPosition table. */
647
1.37M
    for (n = 0; n < maxSymbolValue1; ++n) {
648
1.36M
        U32 const c = count[n];
649
1.36M
        U32 const r = HUF_getIndex(c) + 1;
650
1.36M
        U32 const pos = rankPosition[r].curr++;
651
1.36M
        assert(pos < maxSymbolValue1);
652
1.36M
        huffNode[pos].count = c;
653
1.36M
        huffNode[pos].byte  = (BYTE)n;
654
1.36M
    }
655
656
    /* Sort each bucket. */
657
146k
    for (n = RANK_POSITION_DISTINCT_COUNT_CUTOFF; n < RANK_POSITION_TABLE_SIZE - 1; ++n) {
658
140k
        int const bucketSize = rankPosition[n].curr - rankPosition[n].base;
659
140k
        U32 const bucketStartIdx = rankPosition[n].base;
660
140k
        if (bucketSize > 1) {
661
2.06k
            assert(bucketStartIdx < maxSymbolValue1);
662
2.06k
            HUF_simpleQuickSort(huffNode + bucketStartIdx, 0, bucketSize-1);
663
2.06k
        }
664
140k
    }
665
666
5.42k
    assert(HUF_isSorted(huffNode, maxSymbolValue1));
667
5.42k
}
668
669
670
/** HUF_buildCTable_wksp() :
671
 *  Same as HUF_buildCTable(), but using externally allocated scratch buffer.
672
 *  `workSpace` must be aligned on 4-bytes boundaries, and be at least as large as sizeof(HUF_buildCTable_wksp_tables).
673
 */
674
259k
#define STARTNODE (HUF_SYMBOLVALUE_MAX+1)
675
676
/* HUF_buildTree():
677
 * Takes the huffNode array sorted by HUF_sort() and builds an unlimited-depth Huffman tree.
678
 *
679
 * @param huffNode        The array sorted by HUF_sort(). Builds the Huffman tree in this array.
680
 * @param maxSymbolValue  The maximum symbol value.
681
 * @return                The smallest node in the Huffman tree (by count).
682
 */
683
static int HUF_buildTree(nodeElt* huffNode, U32 maxSymbolValue)
684
5.42k
{
685
5.42k
    nodeElt* const huffNode0 = huffNode - 1;
686
5.42k
    int nonNullRank;
687
5.42k
    int lowS, lowN;
688
5.42k
    int nodeNb = STARTNODE;
689
5.42k
    int n, nodeRoot;
690
5.42k
    DEBUGLOG(5, "HUF_buildTree (alphabet size = %u)", maxSymbolValue + 1);
691
    /* init for parents */
692
5.42k
    nonNullRank = (int)maxSymbolValue;
693
1.11M
    while(huffNode[nonNullRank].count == 0) nonNullRank--;
694
5.42k
    lowS = nonNullRank; nodeRoot = nodeNb + lowS - 1; lowN = nodeNb;
695
5.42k
    huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count;
696
5.42k
    huffNode[lowS].parent = huffNode[lowS-1].parent = (U16)nodeNb;
697
5.42k
    nodeNb++; lowS-=2;
698
254k
    for (n=nodeNb; n<=nodeRoot; n++) huffNode[n].count = (U32)(1U<<30);
699
5.42k
    huffNode0[0].count = (U32)(1U<<31);  /* fake entry, strong barrier */
700
701
    /* create parents */
702
254k
    while (nodeNb <= nodeRoot) {
703
248k
        int const n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
704
248k
        int const n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
705
248k
        huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;
706
248k
        huffNode[n1].parent = huffNode[n2].parent = (U16)nodeNb;
707
248k
        nodeNb++;
708
248k
    }
709
710
    /* distribute weights (unlimited tree height) */
711
5.42k
    huffNode[nodeRoot].nbBits = 0;
712
254k
    for (n=nodeRoot-1; n>=STARTNODE; n--)
713
248k
        huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
714
265k
    for (n=0; n<=nonNullRank; n++)
715
259k
        huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
716
717
5.42k
    DEBUGLOG(6, "Initial distribution of bits completed (%zu sorted symbols)", showHNodeBits(huffNode, maxSymbolValue+1));
718
719
5.42k
    return nonNullRank;
720
5.42k
}
721
722
/**
723
 * HUF_buildCTableFromTree():
724
 * Build the CTable given the Huffman tree in huffNode.
725
 *
726
 * @param[out] CTable         The output Huffman CTable.
727
 * @param      huffNode       The Huffman tree.
728
 * @param      nonNullRank    The last and smallest node in the Huffman tree.
729
 * @param      maxSymbolValue The maximum symbol value.
730
 * @param      maxNbBits      The exact maximum number of bits used in the Huffman tree.
731
 */
732
static void HUF_buildCTableFromTree(HUF_CElt* CTable, nodeElt const* huffNode, int nonNullRank, U32 maxSymbolValue, U32 maxNbBits)
733
5.42k
{
734
5.42k
    HUF_CElt* const ct = CTable + 1;
735
    /* fill result into ctable (val, nbBits) */
736
5.42k
    int n;
737
5.42k
    U16 nbPerRank[HUF_TABLELOG_MAX+1] = {0};
738
5.42k
    U16 valPerRank[HUF_TABLELOG_MAX+1] = {0};
739
5.42k
    int const alphabetSize = (int)(maxSymbolValue + 1);
740
265k
    for (n=0; n<=nonNullRank; n++)
741
259k
        nbPerRank[huffNode[n].nbBits]++;
742
    /* determine starting value per rank */
743
5.42k
    {   U16 min = 0;
744
29.5k
        for (n=(int)maxNbBits; n>0; n--) {
745
24.1k
            valPerRank[n] = min;      /* get starting value within each rank */
746
24.1k
            min += nbPerRank[n];
747
24.1k
            min >>= 1;
748
24.1k
    }   }
749
1.37M
    for (n=0; n<alphabetSize; n++)
750
1.36M
        HUF_setNbBits(ct + huffNode[n].byte, huffNode[n].nbBits);   /* push nbBits per symbol, symbol order */
751
1.37M
    for (n=0; n<alphabetSize; n++)
752
1.36M
        HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++);   /* assign value within rank, symbol order */
753
754
5.42k
    HUF_writeCTableHeader(CTable, maxNbBits, maxSymbolValue);
755
5.42k
}
756
757
size_t
758
HUF_buildCTable_wksp(HUF_CElt* CTable, const unsigned* count, U32 maxSymbolValue, U32 maxNbBits,
759
                     void* workSpace, size_t wkspSize)
760
5.42k
{
761
5.42k
    HUF_buildCTable_wksp_tables* const wksp_tables =
762
5.42k
        (HUF_buildCTable_wksp_tables*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(U32));
763
5.42k
    nodeElt* const huffNode0 = wksp_tables->huffNodeTbl;
764
5.42k
    nodeElt* const huffNode = huffNode0+1;
765
5.42k
    int nonNullRank;
766
767
5.42k
    HUF_STATIC_ASSERT(HUF_CTABLE_WORKSPACE_SIZE == sizeof(HUF_buildCTable_wksp_tables));
768
769
5.42k
    DEBUGLOG(5, "HUF_buildCTable_wksp (alphabet size = %u)", maxSymbolValue+1);
770
771
    /* safety checks */
772
5.42k
    if (wkspSize < sizeof(HUF_buildCTable_wksp_tables))
773
0
        return ERROR(workSpace_tooSmall);
774
5.42k
    if (maxNbBits == 0) maxNbBits = HUF_TABLELOG_DEFAULT;
775
5.42k
    if (maxSymbolValue > HUF_SYMBOLVALUE_MAX)
776
0
        return ERROR(maxSymbolValue_tooLarge);
777
5.42k
    ZSTD_memset(huffNode0, 0, sizeof(huffNodeTable));
778
779
    /* sort, decreasing order */
780
5.42k
    HUF_sort(huffNode, count, maxSymbolValue, wksp_tables->rankPosition);
781
5.42k
    DEBUGLOG(6, "sorted symbols completed (%zu symbols)", showHNodeSymbols(huffNode, maxSymbolValue+1));
782
783
    /* build tree */
784
5.42k
    nonNullRank = HUF_buildTree(huffNode, maxSymbolValue);
785
786
    /* determine and enforce maxTableLog */
787
5.42k
    maxNbBits = HUF_setMaxHeight(huffNode, (U32)nonNullRank, maxNbBits);
788
5.42k
    if (maxNbBits > HUF_TABLELOG_MAX) return ERROR(GENERIC);   /* check fit into table */
789
790
5.42k
    HUF_buildCTableFromTree(CTable, huffNode, nonNullRank, maxSymbolValue, maxNbBits);
791
792
5.42k
    return maxNbBits;
793
5.42k
}
794
795
size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue)
796
4.19k
{
797
4.19k
    HUF_CElt const* ct = CTable + 1;
798
4.19k
    size_t nbBits = 0;
799
4.19k
    int s;
800
1.06M
    for (s = 0; s <= (int)maxSymbolValue; ++s) {
801
1.05M
        nbBits += HUF_getNbBits(ct[s]) * count[s];
802
1.05M
    }
803
4.19k
    return nbBits >> 3;
804
4.19k
}
805
806
2.20k
int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue) {
807
2.20k
    HUF_CTableHeader header = HUF_readCTableHeader(CTable);
808
2.20k
    HUF_CElt const* ct = CTable + 1;
809
2.20k
    int bad = 0;
810
2.20k
    int s;
811
812
2.20k
    assert(header.tableLog <= HUF_TABLELOG_ABSOLUTEMAX);
813
814
2.20k
    if (header.maxSymbolValue < maxSymbolValue)
815
17
        return 0;
816
817
551k
    for (s = 0; s <= (int)maxSymbolValue; ++s) {
818
549k
        bad |= (count[s] != 0) & (HUF_getNbBits(ct[s]) == 0);
819
549k
    }
820
2.18k
    return !bad;
821
2.20k
}
822
823
0
size_t HUF_compressBound(size_t size) { return HUF_COMPRESSBOUND(size); }
824
825
/** HUF_CStream_t:
826
 * Huffman uses its own BIT_CStream_t implementation.
827
 * There are three major differences from BIT_CStream_t:
828
 *   1. HUF_addBits() takes a HUF_CElt (size_t) which is
829
 *      the pair (nbBits, value) in the format:
830
 *      format:
831
 *        - Bits [0, 4)            = nbBits
832
 *        - Bits [4, 64 - nbBits)  = 0
833
 *        - Bits [64 - nbBits, 64) = value
834
 *   2. The bitContainer is built from the upper bits and
835
 *      right shifted. E.g. to add a new value of N bits
836
 *      you right shift the bitContainer by N, then or in
837
 *      the new value into the N upper bits.
838
 *   3. The bitstream has two bit containers. You can add
839
 *      bits to the second container and merge them into
840
 *      the first container.
841
 */
842
843
1.36M
#define HUF_BITS_IN_CONTAINER (sizeof(size_t) * 8)
844
845
typedef struct {
846
    size_t bitContainer[2];
847
    size_t bitPos[2];
848
849
    BYTE* startPtr;
850
    BYTE* ptr;
851
    BYTE* endPtr;
852
} HUF_CStream_t;
853
854
/**! HUF_initCStream():
855
 * Initializes the bitstream.
856
 * @returns 0 or an error code.
857
 */
858
static size_t HUF_initCStream(HUF_CStream_t* bitC,
859
                                  void* startPtr, size_t dstCapacity)
860
14.9k
{
861
14.9k
    ZSTD_memset(bitC, 0, sizeof(*bitC));
862
14.9k
    bitC->startPtr = (BYTE*)startPtr;
863
14.9k
    bitC->ptr = bitC->startPtr;
864
14.9k
    bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer[0]);
865
14.9k
    if (dstCapacity <= sizeof(bitC->bitContainer[0])) return ERROR(dstSize_tooSmall);
866
14.9k
    return 0;
867
14.9k
}
868
869
/*! HUF_addBits():
870
 * Adds the symbol stored in HUF_CElt elt to the bitstream.
871
 *
872
 * @param elt   The element we're adding. This is a (nbBits, value) pair.
873
 *              See the HUF_CStream_t docs for the format.
874
 * @param idx   Insert into the bitstream at this idx.
875
 * @param kFast This is a template parameter. If the bitstream is guaranteed
876
 *              to have at least 4 unused bits after this call it may be 1,
877
 *              otherwise it must be 0. HUF_addBits() is faster when fast is set.
878
 */
879
FORCE_INLINE_TEMPLATE void HUF_addBits(HUF_CStream_t* bitC, HUF_CElt elt, int idx, int kFast)
880
8.40M
{
881
8.40M
    assert(idx <= 1);
882
8.40M
    assert(HUF_getNbBits(elt) <= HUF_TABLELOG_ABSOLUTEMAX);
883
    /* This is efficient on x86-64 with BMI2 because shrx
884
     * only reads the low 6 bits of the register. The compiler
885
     * knows this and elides the mask. When fast is set,
886
     * every operation can use the same value loaded from elt.
887
     */
888
8.40M
    bitC->bitContainer[idx] >>= HUF_getNbBits(elt);
889
8.40M
    bitC->bitContainer[idx] |= kFast ? HUF_getValueFast(elt) : HUF_getValue(elt);
890
    /* We only read the low 8 bits of bitC->bitPos[idx] so it
891
     * doesn't matter that the high bits have noise from the value.
892
     */
893
8.40M
    bitC->bitPos[idx] += HUF_getNbBitsFast(elt);
894
8.40M
    assert((bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);
895
    /* The last 4-bits of elt are dirty if fast is set,
896
     * so we must not be overwriting bits that have already been
897
     * inserted into the bit container.
898
     */
899
#if DEBUGLEVEL >= 1
900
    {
901
        size_t const nbBits = HUF_getNbBits(elt);
902
        size_t const dirtyBits = nbBits == 0 ? 0 : ZSTD_highbit32((U32)nbBits) + 1;
903
        (void)dirtyBits;
904
        /* Middle bits are 0. */
905
        assert(((elt >> dirtyBits) << (dirtyBits + nbBits)) == 0);
906
        /* We didn't overwrite any bits in the bit container. */
907
        assert(!kFast || (bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);
908
        (void)dirtyBits;
909
    }
910
#endif
911
8.40M
}
912
913
FORCE_INLINE_TEMPLATE void HUF_zeroIndex1(HUF_CStream_t* bitC)
914
666k
{
915
666k
    bitC->bitContainer[1] = 0;
916
666k
    bitC->bitPos[1] = 0;
917
666k
}
918
919
/*! HUF_mergeIndex1() :
920
 * Merges the bit container @ index 1 into the bit container @ index 0
921
 * and zeros the bit container @ index 1.
922
 */
923
FORCE_INLINE_TEMPLATE void HUF_mergeIndex1(HUF_CStream_t* bitC)
924
666k
{
925
666k
    assert((bitC->bitPos[1] & 0xFF) < HUF_BITS_IN_CONTAINER);
926
666k
    bitC->bitContainer[0] >>= (bitC->bitPos[1] & 0xFF);
927
666k
    bitC->bitContainer[0] |= bitC->bitContainer[1];
928
666k
    bitC->bitPos[0] += bitC->bitPos[1];
929
666k
    assert((bitC->bitPos[0] & 0xFF) <= HUF_BITS_IN_CONTAINER);
930
666k
}
931
932
/*! HUF_flushBits() :
933
* Flushes the bits in the bit container @ index 0.
934
*
935
* @post bitPos will be < 8.
936
* @param kFast If kFast is set then we must know a-priori that
937
*              the bit container will not overflow.
938
*/
939
FORCE_INLINE_TEMPLATE void HUF_flushBits(HUF_CStream_t* bitC, int kFast)
940
1.36M
{
941
    /* The upper bits of bitPos are noisy, so we must mask by 0xFF. */
942
1.36M
    size_t const nbBits = bitC->bitPos[0] & 0xFF;
943
1.36M
    size_t const nbBytes = nbBits >> 3;
944
    /* The top nbBits bits of bitContainer are the ones we need. */
945
1.36M
    size_t const bitContainer = bitC->bitContainer[0] >> (HUF_BITS_IN_CONTAINER - nbBits);
946
    /* Mask bitPos to account for the bytes we consumed. */
947
1.36M
    bitC->bitPos[0] &= 7;
948
1.36M
    assert(nbBits > 0);
949
1.36M
    assert(nbBits <= sizeof(bitC->bitContainer[0]) * 8);
950
1.36M
    assert(bitC->ptr <= bitC->endPtr);
951
1.36M
    MEM_writeLEST(bitC->ptr, bitContainer);
952
1.36M
    bitC->ptr += nbBytes;
953
1.36M
    assert(!kFast || bitC->ptr <= bitC->endPtr);
954
1.36M
    if (!kFast && bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
955
    /* bitContainer doesn't need to be modified because the leftover
956
     * bits are already the top bitPos bits. And we don't care about
957
     * noise in the lower values.
958
     */
959
1.36M
}
960
961
/*! HUF_endMark()
962
 * @returns The Huffman stream end mark: A 1-bit value = 1.
963
 */
964
static HUF_CElt HUF_endMark(void)
965
14.9k
{
966
14.9k
    HUF_CElt endMark;
967
14.9k
    HUF_setNbBits(&endMark, 1);
968
14.9k
    HUF_setValue(&endMark, 1);
969
14.9k
    return endMark;
970
14.9k
}
971
972
/*! HUF_closeCStream() :
973
 *  @return Size of CStream, in bytes,
974
 *          or 0 if it could not fit into dstBuffer */
975
static size_t HUF_closeCStream(HUF_CStream_t* bitC)
976
14.9k
{
977
14.9k
    HUF_addBits(bitC, HUF_endMark(), /* idx */ 0, /* kFast */ 0);
978
14.9k
    HUF_flushBits(bitC, /* kFast */ 0);
979
14.9k
    {
980
14.9k
        size_t const nbBits = bitC->bitPos[0] & 0xFF;
981
14.9k
        if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
982
14.9k
        return (size_t)(bitC->ptr - bitC->startPtr) + (nbBits > 0);
983
14.9k
    }
984
14.9k
}
985
986
FORCE_INLINE_TEMPLATE void
987
HUF_encodeSymbol(HUF_CStream_t* bitCPtr, U32 symbol, const HUF_CElt* CTable, int idx, int fast)
988
8.39M
{
989
8.39M
    HUF_addBits(bitCPtr, CTable[symbol], idx, fast);
990
8.39M
}
991
992
FORCE_INLINE_TEMPLATE void
993
HUF_compress1X_usingCTable_internal_body_loop(HUF_CStream_t* bitC,
994
                                   const BYTE* ip, size_t srcSize,
995
                                   const HUF_CElt* ct,
996
                                   int kUnroll, int kFastFlush, int kLastFast)
997
14.9k
{
998
    /* Join to kUnroll */
999
14.9k
    int n = (int)srcSize;
1000
14.9k
    int rem = n % kUnroll;
1001
14.9k
    if (rem > 0) {
1002
64.0k
        for (; rem > 0; --rem) {
1003
51.2k
            HUF_encodeSymbol(bitC, ip[--n], ct, 0, /* fast */ 0);
1004
51.2k
        }
1005
12.7k
        HUF_flushBits(bitC, kFastFlush);
1006
12.7k
    }
1007
14.9k
    assert(n % kUnroll == 0);
1008
1009
    /* Join to 2 * kUnroll */
1010
14.9k
    if (n % (2 * kUnroll)) {
1011
7.82k
        int u;
1012
63.1k
        for (u = 1; u < kUnroll; ++u) {
1013
55.3k
            HUF_encodeSymbol(bitC, ip[n - u], ct, 0, 1);
1014
55.3k
        }
1015
7.82k
        HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, 0, kLastFast);
1016
7.82k
        HUF_flushBits(bitC, kFastFlush);
1017
7.82k
        n -= kUnroll;
1018
7.82k
    }
1019
14.9k
    assert(n % (2 * kUnroll) == 0);
1020
1021
681k
    for (; n>0; n-= 2 * kUnroll) {
1022
        /* Encode kUnroll symbols into the bitstream @ index 0. */
1023
666k
        int u;
1024
4.13M
        for (u = 1; u < kUnroll; ++u) {
1025
3.47M
            HUF_encodeSymbol(bitC, ip[n - u], ct, /* idx */ 0, /* fast */ 1);
1026
3.47M
        }
1027
666k
        HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, /* idx */ 0, /* fast */ kLastFast);
1028
666k
        HUF_flushBits(bitC, kFastFlush);
1029
        /* Encode kUnroll symbols into the bitstream @ index 1.
1030
         * This allows us to start filling the bit container
1031
         * without any data dependencies.
1032
         */
1033
666k
        HUF_zeroIndex1(bitC);
1034
4.13M
        for (u = 1; u < kUnroll; ++u) {
1035
3.47M
            HUF_encodeSymbol(bitC, ip[n - kUnroll - u], ct, /* idx */ 1, /* fast */ 1);
1036
3.47M
        }
1037
666k
        HUF_encodeSymbol(bitC, ip[n - kUnroll - kUnroll], ct, /* idx */ 1, /* fast */ kLastFast);
1038
        /* Merge bitstream @ index 1 into the bitstream @ index 0 */
1039
666k
        HUF_mergeIndex1(bitC);
1040
666k
        HUF_flushBits(bitC, kFastFlush);
1041
666k
    }
1042
14.9k
    assert(n == 0);
1043
1044
14.9k
}
1045
1046
/**
1047
 * Returns a tight upper bound on the output space needed by Huffman
1048
 * with 8 bytes buffer to handle over-writes. If the output is at least
1049
 * this large we don't need to do bounds checks during Huffman encoding.
1050
 */
1051
static size_t HUF_tightCompressBound(size_t srcSize, size_t tableLog)
1052
14.9k
{
1053
14.9k
    return ((srcSize * tableLog) >> 3) + 8;
1054
14.9k
}
1055
1056
1057
FORCE_INLINE_TEMPLATE size_t
1058
HUF_compress1X_usingCTable_internal_body(void* dst, size_t dstSize,
1059
                                   const void* src, size_t srcSize,
1060
                                   const HUF_CElt* CTable)
1061
14.9k
{
1062
14.9k
    U32 const tableLog = HUF_readCTableHeader(CTable).tableLog;
1063
14.9k
    HUF_CElt const* ct = CTable + 1;
1064
14.9k
    const BYTE* ip = (const BYTE*) src;
1065
14.9k
    BYTE* const ostart = (BYTE*)dst;
1066
14.9k
    BYTE* const oend = ostart + dstSize;
1067
14.9k
    HUF_CStream_t bitC;
1068
1069
    /* init */
1070
14.9k
    if (dstSize < 8) return 0;   /* not enough space to compress */
1071
14.9k
    { BYTE* op = ostart;
1072
14.9k
      size_t const initErr = HUF_initCStream(&bitC, op, (size_t)(oend-op));
1073
14.9k
      if (HUF_isError(initErr)) return 0; }
1074
1075
14.9k
    if (dstSize < HUF_tightCompressBound(srcSize, (size_t)tableLog) || tableLog > 11)
1076
0
        HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ MEM_32bits() ? 2 : 4, /* kFast */ 0, /* kLastFast */ 0);
1077
14.9k
    else {
1078
14.9k
        if (MEM_32bits()) {
1079
0
            switch (tableLog) {
1080
0
            case 11:
1081
0
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 0);
1082
0
                break;
1083
0
            case 10: ZSTD_FALLTHROUGH;
1084
0
            case 9: ZSTD_FALLTHROUGH;
1085
0
            case 8:
1086
0
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 1);
1087
0
                break;
1088
0
            case 7: ZSTD_FALLTHROUGH;
1089
0
            default:
1090
0
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 3, /* kFastFlush */ 1, /* kLastFast */ 1);
1091
0
                break;
1092
0
            }
1093
14.9k
        } else {
1094
14.9k
            switch (tableLog) {
1095
784
            case 11:
1096
784
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 0);
1097
784
                break;
1098
1.15k
            case 10:
1099
1.15k
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 1);
1100
1.15k
                break;
1101
1.84k
            case 9:
1102
1.84k
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 6, /* kFastFlush */ 1, /* kLastFast */ 0);
1103
1.84k
                break;
1104
443
            case 8:
1105
443
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 7, /* kFastFlush */ 1, /* kLastFast */ 0);
1106
443
                break;
1107
536
            case 7:
1108
536
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 8, /* kFastFlush */ 1, /* kLastFast */ 0);
1109
536
                break;
1110
314
            case 6: ZSTD_FALLTHROUGH;
1111
10.2k
            default:
1112
10.2k
                HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 9, /* kFastFlush */ 1, /* kLastFast */ 1);
1113
10.2k
                break;
1114
14.9k
            }
1115
14.9k
        }
1116
14.9k
    }
1117
14.9k
    assert(bitC.ptr <= bitC.endPtr);
1118
1119
14.9k
    return HUF_closeCStream(&bitC);
1120
14.9k
}
1121
1122
#if DYNAMIC_BMI2
1123
1124
static BMI2_TARGET_ATTRIBUTE size_t
1125
HUF_compress1X_usingCTable_internal_bmi2(void* dst, size_t dstSize,
1126
                                   const void* src, size_t srcSize,
1127
                                   const HUF_CElt* CTable)
1128
14.9k
{
1129
14.9k
    return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
1130
14.9k
}
1131
1132
static size_t
1133
HUF_compress1X_usingCTable_internal_default(void* dst, size_t dstSize,
1134
                                      const void* src, size_t srcSize,
1135
                                      const HUF_CElt* CTable)
1136
0
{
1137
0
    return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
1138
0
}
1139
1140
static size_t
1141
HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
1142
                              const void* src, size_t srcSize,
1143
                              const HUF_CElt* CTable, const int flags)
1144
14.9k
{
1145
14.9k
    if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) {
1146
14.9k
        return HUF_compress1X_usingCTable_internal_bmi2(dst, dstSize, src, srcSize, CTable);
1147
14.9k
    }
1148
0
    (void)flags;
1149
0
    return HUF_compress1X_usingCTable_internal_default(dst, dstSize, src, srcSize, CTable);
1150
14.9k
}
1151
1152
#else
1153
1154
static size_t
1155
HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
1156
                              const void* src, size_t srcSize,
1157
                              const HUF_CElt* CTable, const int flags)
1158
{
1159
    (void)flags;
1160
    return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
1161
}
1162
1163
#endif
1164
1165
size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags)
1166
0
{
1167
0
    return HUF_compress1X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, flags);
1168
0
}
1169
1170
static size_t
1171
HUF_compress4X_usingCTable_internal(void* dst, size_t dstSize,
1172
                              const void* src, size_t srcSize,
1173
                              const HUF_CElt* CTable, int flags)
1174
3.19k
{
1175
3.19k
    size_t const segmentSize = (srcSize+3)/4;   /* first 3 segments */
1176
3.19k
    const BYTE* ip = (const BYTE*) src;
1177
3.19k
    const BYTE* const iend = ip + srcSize;
1178
3.19k
    BYTE* const ostart = (BYTE*) dst;
1179
3.19k
    BYTE* const oend = ostart + dstSize;
1180
3.19k
    BYTE* op = ostart;
1181
1182
3.19k
    if (dstSize < 6 + 1 + 1 + 1 + 8) return 0;   /* minimum space to compress successfully */
1183
3.19k
    if (srcSize < 12) return 0;   /* no saving possible : too small input */
1184
3.19k
    op += 6;   /* jumpTable */
1185
1186
3.19k
    assert(op <= oend);
1187
3.19k
    {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
1188
3.19k
        if (cSize == 0 || cSize > 65535) return 0;
1189
3.19k
        MEM_writeLE16(ostart, (U16)cSize);
1190
3.19k
        op += cSize;
1191
3.19k
    }
1192
1193
0
    ip += segmentSize;
1194
3.19k
    assert(op <= oend);
1195
3.19k
    {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
1196
3.19k
        if (cSize == 0 || cSize > 65535) return 0;
1197
3.19k
        MEM_writeLE16(ostart+2, (U16)cSize);
1198
3.19k
        op += cSize;
1199
3.19k
    }
1200
1201
0
    ip += segmentSize;
1202
3.19k
    assert(op <= oend);
1203
3.19k
    {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
1204
3.19k
        if (cSize == 0 || cSize > 65535) return 0;
1205
3.19k
        MEM_writeLE16(ostart+4, (U16)cSize);
1206
3.19k
        op += cSize;
1207
3.19k
    }
1208
1209
0
    ip += segmentSize;
1210
3.19k
    assert(op <= oend);
1211
3.19k
    assert(ip <= iend);
1212
3.19k
    {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, (size_t)(iend-ip), CTable, flags) );
1213
3.19k
        if (cSize == 0 || cSize > 65535) return 0;
1214
3.19k
        op += cSize;
1215
3.19k
    }
1216
1217
0
    return (size_t)(op-ostart);
1218
3.19k
}
1219
1220
size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags)
1221
0
{
1222
0
    return HUF_compress4X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, flags);
1223
0
}
1224
1225
typedef enum { HUF_singleStream, HUF_fourStreams } HUF_nbStreams_e;
1226
1227
static size_t HUF_compressCTable_internal(
1228
                BYTE* const ostart, BYTE* op, BYTE* const oend,
1229
                const void* src, size_t srcSize,
1230
                HUF_nbStreams_e nbStreams, const HUF_CElt* CTable, const int flags)
1231
5.42k
{
1232
5.42k
    size_t const cSize = (nbStreams==HUF_singleStream) ?
1233
2.23k
                         HUF_compress1X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, flags) :
1234
5.42k
                         HUF_compress4X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, flags);
1235
5.42k
    if (HUF_isError(cSize)) { return cSize; }
1236
5.42k
    if (cSize==0) { return 0; }   /* uncompressible */
1237
5.42k
    op += cSize;
1238
    /* check compressibility */
1239
5.42k
    assert(op >= ostart);
1240
5.42k
    if ((size_t)(op-ostart) >= srcSize-1) { return 0; }
1241
5.17k
    return (size_t)(op-ostart);
1242
5.42k
}
1243
1244
typedef struct {
1245
    unsigned count[HUF_SYMBOLVALUE_MAX + 1];
1246
    HUF_CElt CTable[HUF_CTABLE_SIZE_ST(HUF_SYMBOLVALUE_MAX)];
1247
    union {
1248
        HUF_buildCTable_wksp_tables buildCTable_wksp;
1249
        HUF_WriteCTableWksp writeCTable_wksp;
1250
        U32 hist_wksp[HIST_WKSP_SIZE_U32];
1251
    } wksps;
1252
} HUF_compress_tables_t;
1253
1254
641
#define SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE 4096
1255
634
#define SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO 10  /* Must be >= 2 */
1256
1257
unsigned HUF_cardinality(const unsigned* count, unsigned maxSymbolValue)
1258
0
{
1259
0
    unsigned cardinality = 0;
1260
0
    unsigned i;
1261
1262
0
    for (i = 0; i < maxSymbolValue + 1; i++) {
1263
0
        if (count[i] != 0) cardinality += 1;
1264
0
    }
1265
1266
0
    return cardinality;
1267
0
}
1268
1269
unsigned HUF_minTableLog(unsigned symbolCardinality)
1270
0
{
1271
0
    U32 minBitsSymbols = ZSTD_highbit32(symbolCardinality) + 1;
1272
0
    return minBitsSymbols;
1273
0
}
1274
1275
unsigned HUF_optimalTableLog(
1276
            unsigned maxTableLog,
1277
            size_t srcSize,
1278
            unsigned maxSymbolValue,
1279
            void* workSpace, size_t wkspSize,
1280
            HUF_CElt* table,
1281
      const unsigned* count,
1282
            int flags)
1283
5.42k
{
1284
5.42k
    assert(srcSize > 1); /* Not supported, RLE should be used instead */
1285
5.42k
    assert(wkspSize >= sizeof(HUF_buildCTable_wksp_tables));
1286
1287
5.42k
    if (!(flags & HUF_flags_optimalDepth)) {
1288
        /* cheap evaluation, based on FSE */
1289
5.42k
        return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 1);
1290
5.42k
    }
1291
1292
0
    {   BYTE* dst = (BYTE*)workSpace + sizeof(HUF_WriteCTableWksp);
1293
0
        size_t dstSize = wkspSize - sizeof(HUF_WriteCTableWksp);
1294
0
        size_t hSize, newSize;
1295
0
        const unsigned symbolCardinality = HUF_cardinality(count, maxSymbolValue);
1296
0
        const unsigned minTableLog = HUF_minTableLog(symbolCardinality);
1297
0
        size_t optSize = ((size_t) ~0) - 1;
1298
0
        unsigned optLog = maxTableLog, optLogGuess;
1299
1300
0
        DEBUGLOG(6, "HUF_optimalTableLog: probing huf depth (srcSize=%zu)", srcSize);
1301
1302
        /* Search until size increases */
1303
0
        for (optLogGuess = minTableLog; optLogGuess <= maxTableLog; optLogGuess++) {
1304
0
            DEBUGLOG(7, "checking for huffLog=%u", optLogGuess);
1305
1306
0
            {   size_t maxBits = HUF_buildCTable_wksp(table, count, maxSymbolValue, optLogGuess, workSpace, wkspSize);
1307
0
                if (ERR_isError(maxBits)) continue;
1308
1309
0
                if (maxBits < optLogGuess && optLogGuess > minTableLog) break;
1310
1311
0
                hSize = HUF_writeCTable_wksp(dst, dstSize, table, maxSymbolValue, (U32)maxBits, workSpace, wkspSize);
1312
0
            }
1313
1314
0
            if (ERR_isError(hSize)) continue;
1315
1316
0
            newSize = HUF_estimateCompressedSize(table, count, maxSymbolValue) + hSize;
1317
1318
0
            if (newSize > optSize + 1) {
1319
0
                break;
1320
0
            }
1321
1322
0
            if (newSize < optSize) {
1323
0
                optSize = newSize;
1324
0
                optLog = optLogGuess;
1325
0
            }
1326
0
        }
1327
0
        assert(optLog <= HUF_TABLELOG_MAX);
1328
0
        return optLog;
1329
5.42k
    }
1330
5.42k
}
1331
1332
/* HUF_compress_internal() :
1333
 * `workSpace_align4` must be aligned on 4-bytes boundaries,
1334
 * and occupies the same space as a table of HUF_WORKSPACE_SIZE_U64 unsigned */
1335
static size_t
1336
HUF_compress_internal (void* dst, size_t dstSize,
1337
                 const void* src, size_t srcSize,
1338
                       unsigned maxSymbolValue, unsigned huffLog,
1339
                       HUF_nbStreams_e nbStreams,
1340
                       void* workSpace, size_t wkspSize,
1341
                       HUF_CElt* oldHufTable, HUF_repeat* repeat, int flags)
1342
5.48k
{
1343
5.48k
    HUF_compress_tables_t* const table = (HUF_compress_tables_t*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(size_t));
1344
5.48k
    BYTE* const ostart = (BYTE*)dst;
1345
5.48k
    BYTE* const oend = ostart + dstSize;
1346
5.48k
    BYTE* op = ostart;
1347
1348
5.48k
    DEBUGLOG(5, "HUF_compress_internal (srcSize=%zu)", srcSize);
1349
5.48k
    HUF_STATIC_ASSERT(sizeof(*table) + HUF_WORKSPACE_MAX_ALIGNMENT <= HUF_WORKSPACE_SIZE);
1350
1351
    /* checks & inits */
1352
5.48k
    if (wkspSize < sizeof(*table)) return ERROR(workSpace_tooSmall);
1353
5.48k
    if (!srcSize) return 0;  /* Uncompressed */
1354
5.48k
    if (!dstSize) return 0;  /* cannot fit anything within dst budget */
1355
5.48k
    if (srcSize > HUF_BLOCKSIZE_MAX) return ERROR(srcSize_wrong);   /* current block size limit */
1356
5.48k
    if (huffLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
1357
5.48k
    if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
1358
5.48k
    if (!maxSymbolValue) maxSymbolValue = HUF_SYMBOLVALUE_MAX;
1359
5.48k
    if (!huffLog) huffLog = HUF_TABLELOG_DEFAULT;
1360
1361
    /* Heuristic : If old table is valid, use it for small inputs */
1362
5.48k
    if ((flags & HUF_flags_preferRepeat) && repeat && *repeat == HUF_repeat_valid) {
1363
0
        return HUF_compressCTable_internal(ostart, op, oend,
1364
0
                                           src, srcSize,
1365
0
                                           nbStreams, oldHufTable, flags);
1366
0
    }
1367
1368
    /* If uncompressible data is suspected, do a smaller sampling first */
1369
5.48k
    DEBUG_STATIC_ASSERT(SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO >= 2);
1370
5.48k
    if ((flags & HUF_flags_suspectUncompressible) && srcSize >= (SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE * SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO)) {
1371
7
        size_t largestTotal = 0;
1372
7
        DEBUGLOG(5, "input suspected incompressible : sampling to check");
1373
7
        {   unsigned maxSymbolValueBegin = maxSymbolValue;
1374
7
            CHECK_V_F(largestBegin, HIST_count_simple (table->count, &maxSymbolValueBegin, (const BYTE*)src, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );
1375
7
            largestTotal += largestBegin;
1376
7
        }
1377
0
        {   unsigned maxSymbolValueEnd = maxSymbolValue;
1378
7
            CHECK_V_F(largestEnd, HIST_count_simple (table->count, &maxSymbolValueEnd, (const BYTE*)src + srcSize - SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );
1379
7
            largestTotal += largestEnd;
1380
7
        }
1381
7
        if (largestTotal <= ((2 * SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) >> 7)+4) return 0;   /* heuristic : probably not compressible enough */
1382
7
    }
1383
1384
    /* Scan input and build symbol stats */
1385
5.48k
    {   CHECK_V_F(largest, HIST_count_wksp (table->count, &maxSymbolValue, (const BYTE*)src, srcSize, table->wksps.hist_wksp, sizeof(table->wksps.hist_wksp)) );
1386
5.48k
        if (largest == srcSize) { *ostart = ((const BYTE*)src)[0]; return 1; }   /* single symbol, rle */
1387
5.44k
        if (largest <= (srcSize >> 7)+4) return 0;   /* heuristic : probably not compressible enough */
1388
5.44k
    }
1389
5.42k
    DEBUGLOG(6, "histogram detail completed (%zu symbols)", showU32(table->count, maxSymbolValue+1));
1390
1391
    /* Check validity of previous table */
1392
5.42k
    if ( repeat
1393
5.42k
      && *repeat == HUF_repeat_check
1394
2.20k
      && !HUF_validateCTable(oldHufTable, table->count, maxSymbolValue)) {
1395
103
        *repeat = HUF_repeat_none;
1396
103
    }
1397
    /* Heuristic : use existing table for small inputs */
1398
5.42k
    if ((flags & HUF_flags_preferRepeat) && repeat && *repeat != HUF_repeat_none) {
1399
0
        return HUF_compressCTable_internal(ostart, op, oend,
1400
0
                                           src, srcSize,
1401
0
                                           nbStreams, oldHufTable, flags);
1402
0
    }
1403
1404
    /* Build Huffman Tree */
1405
5.42k
    huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, &table->wksps, sizeof(table->wksps), table->CTable, table->count, flags);
1406
5.42k
    {   size_t const maxBits = HUF_buildCTable_wksp(table->CTable, table->count,
1407
5.42k
                                            maxSymbolValue, huffLog,
1408
5.42k
                                            &table->wksps.buildCTable_wksp, sizeof(table->wksps.buildCTable_wksp));
1409
5.42k
        CHECK_F(maxBits);
1410
5.42k
        huffLog = (U32)maxBits;
1411
5.42k
        DEBUGLOG(6, "bit distribution completed (%zu symbols)", showCTableBits(table->CTable + 1, maxSymbolValue+1));
1412
5.42k
    }
1413
1414
    /* Write table description header */
1415
5.42k
    {   CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, table->CTable, maxSymbolValue, huffLog,
1416
5.42k
                                              &table->wksps.writeCTable_wksp, sizeof(table->wksps.writeCTable_wksp)) );
1417
        /* Check if using previous huffman table is beneficial */
1418
5.42k
        if (repeat && *repeat != HUF_repeat_none) {
1419
2.09k
            size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, table->count, maxSymbolValue);
1420
2.09k
            size_t const newSize = HUF_estimateCompressedSize(table->CTable, table->count, maxSymbolValue);
1421
2.09k
            if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {
1422
1.81k
                return HUF_compressCTable_internal(ostart, op, oend,
1423
1.81k
                                                   src, srcSize,
1424
1.81k
                                                   nbStreams, oldHufTable, flags);
1425
1.81k
        }   }
1426
1427
        /* Use the new huffman table */
1428
3.61k
        if (hSize + 12ul >= srcSize) { return 0; }
1429
3.61k
        op += hSize;
1430
3.61k
        if (repeat) { *repeat = HUF_repeat_none; }
1431
3.61k
        if (oldHufTable)
1432
3.61k
            ZSTD_memcpy(oldHufTable, table->CTable, sizeof(table->CTable));  /* Save new table */
1433
3.61k
    }
1434
0
    return HUF_compressCTable_internal(ostart, op, oend,
1435
3.61k
                                       src, srcSize,
1436
3.61k
                                       nbStreams, table->CTable, flags);
1437
3.61k
}
1438
1439
size_t HUF_compress1X_repeat (void* dst, size_t dstSize,
1440
                      const void* src, size_t srcSize,
1441
                      unsigned maxSymbolValue, unsigned huffLog,
1442
                      void* workSpace, size_t wkspSize,
1443
                      HUF_CElt* hufTable, HUF_repeat* repeat, int flags)
1444
2.28k
{
1445
2.28k
    DEBUGLOG(5, "HUF_compress1X_repeat (srcSize = %zu)", srcSize);
1446
2.28k
    return HUF_compress_internal(dst, dstSize, src, srcSize,
1447
2.28k
                                 maxSymbolValue, huffLog, HUF_singleStream,
1448
2.28k
                                 workSpace, wkspSize, hufTable,
1449
2.28k
                                 repeat, flags);
1450
2.28k
}
1451
1452
/* HUF_compress4X_repeat():
1453
 * compress input using 4 streams.
1454
 * consider skipping quickly
1455
 * reuse an existing huffman compression table */
1456
size_t HUF_compress4X_repeat (void* dst, size_t dstSize,
1457
                      const void* src, size_t srcSize,
1458
                      unsigned maxSymbolValue, unsigned huffLog,
1459
                      void* workSpace, size_t wkspSize,
1460
                      HUF_CElt* hufTable, HUF_repeat* repeat, int flags)
1461
3.20k
{
1462
3.20k
    DEBUGLOG(5, "HUF_compress4X_repeat (srcSize = %zu)", srcSize);
1463
3.20k
    return HUF_compress_internal(dst, dstSize, src, srcSize,
1464
3.20k
                                 maxSymbolValue, huffLog, HUF_fourStreams,
1465
3.20k
                                 workSpace, wkspSize,
1466
3.20k
                                 hufTable, repeat, flags);
1467
3.20k
}