Coverage Report

Created: 2025-07-11 06:33

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