xref: /freebsd/sys/contrib/zstd/lib/compress/fse_compress.c (revision f7cd7fe51c4140960ebea00410ed62894f5625d1)
10c16b537SWarner Losh /* ******************************************************************
237f1f268SConrad Meyer  * FSE : Finite State Entropy encoder
337f1f268SConrad Meyer  * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
437f1f268SConrad Meyer  *
537f1f268SConrad Meyer  *  You can contact the author at :
637f1f268SConrad Meyer  *  - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
737f1f268SConrad Meyer  *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
837f1f268SConrad Meyer  *
937f1f268SConrad Meyer  * This source code is licensed under both the BSD-style license (found in the
1037f1f268SConrad Meyer  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
1137f1f268SConrad Meyer  * in the COPYING file in the root directory of this source tree).
1237f1f268SConrad Meyer  * You may select, at your option, one of the above-listed licenses.
130c16b537SWarner Losh ****************************************************************** */
140c16b537SWarner Losh 
150c16b537SWarner Losh /* **************************************************************
160c16b537SWarner Losh *  Includes
170c16b537SWarner Losh ****************************************************************/
1837f1f268SConrad Meyer #include "../common/compiler.h"
1937f1f268SConrad Meyer #include "../common/mem.h"        /* U32, U16, etc. */
2037f1f268SConrad Meyer #include "../common/debug.h"      /* assert, DEBUGLOG */
210f743729SConrad Meyer #include "hist.h"       /* HIST_count_wksp */
2237f1f268SConrad Meyer #include "../common/bitstream.h"
230c16b537SWarner Losh #define FSE_STATIC_LINKING_ONLY
2437f1f268SConrad Meyer #include "../common/fse.h"
2537f1f268SConrad Meyer #include "../common/error_private.h"
26*f7cd7fe5SConrad Meyer #define ZSTD_DEPS_NEED_MALLOC
27*f7cd7fe5SConrad Meyer #define ZSTD_DEPS_NEED_MATH64
28*f7cd7fe5SConrad Meyer #include "../common/zstd_deps.h"  /* ZSTD_malloc, ZSTD_free, ZSTD_memcpy, ZSTD_memset */
290c16b537SWarner Losh 
300c16b537SWarner Losh 
310c16b537SWarner Losh /* **************************************************************
320c16b537SWarner Losh *  Error Management
330c16b537SWarner Losh ****************************************************************/
340c16b537SWarner Losh #define FSE_isError ERR_isError
350c16b537SWarner Losh 
360c16b537SWarner Losh 
370c16b537SWarner Losh /* **************************************************************
380c16b537SWarner Losh *  Templates
390c16b537SWarner Losh ****************************************************************/
400c16b537SWarner Losh /*
410c16b537SWarner Losh   designed to be included
420c16b537SWarner Losh   for type-specific functions (template emulation in C)
430c16b537SWarner Losh   Objective is to write these functions only once, for improved maintenance
440c16b537SWarner Losh */
450c16b537SWarner Losh 
460c16b537SWarner Losh /* safety checks */
470c16b537SWarner Losh #ifndef FSE_FUNCTION_EXTENSION
480c16b537SWarner Losh #  error "FSE_FUNCTION_EXTENSION must be defined"
490c16b537SWarner Losh #endif
500c16b537SWarner Losh #ifndef FSE_FUNCTION_TYPE
510c16b537SWarner Losh #  error "FSE_FUNCTION_TYPE must be defined"
520c16b537SWarner Losh #endif
530c16b537SWarner Losh 
540c16b537SWarner Losh /* Function names */
550c16b537SWarner Losh #define FSE_CAT(X,Y) X##Y
560c16b537SWarner Losh #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
570c16b537SWarner Losh #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
580c16b537SWarner Losh 
590c16b537SWarner Losh 
600c16b537SWarner Losh /* Function templates */
610c16b537SWarner Losh 
620c16b537SWarner Losh /* FSE_buildCTable_wksp() :
630c16b537SWarner Losh  * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
640c16b537SWarner Losh  * wkspSize should be sized to handle worst case situation, which is `1<<max_tableLog * sizeof(FSE_FUNCTION_TYPE)`
650c16b537SWarner Losh  * workSpace must also be properly aligned with FSE_FUNCTION_TYPE requirements
660c16b537SWarner Losh  */
670f743729SConrad Meyer size_t FSE_buildCTable_wksp(FSE_CTable* ct,
680f743729SConrad Meyer                       const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
690f743729SConrad Meyer                             void* workSpace, size_t wkspSize)
700c16b537SWarner Losh {
710c16b537SWarner Losh     U32 const tableSize = 1 << tableLog;
720c16b537SWarner Losh     U32 const tableMask = tableSize - 1;
730c16b537SWarner Losh     void* const ptr = ct;
740c16b537SWarner Losh     U16* const tableU16 = ( (U16*) ptr) + 2;
750c16b537SWarner Losh     void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
760c16b537SWarner Losh     FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
770c16b537SWarner Losh     U32 const step = FSE_TABLESTEP(tableSize);
780c16b537SWarner Losh 
79*f7cd7fe5SConrad Meyer     U32* cumul = (U32*)workSpace;
80*f7cd7fe5SConrad Meyer     FSE_FUNCTION_TYPE* tableSymbol = (FSE_FUNCTION_TYPE*)(cumul + (maxSymbolValue + 2));
81*f7cd7fe5SConrad Meyer 
820c16b537SWarner Losh     U32 highThreshold = tableSize-1;
830c16b537SWarner Losh 
84*f7cd7fe5SConrad Meyer     if ((size_t)workSpace & 3) return ERROR(GENERIC); /* Must be 4 byte aligned */
85*f7cd7fe5SConrad Meyer     if (FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) > wkspSize) return ERROR(tableLog_tooLarge);
860c16b537SWarner Losh     /* CTable header */
870c16b537SWarner Losh     tableU16[-2] = (U16) tableLog;
880c16b537SWarner Losh     tableU16[-1] = (U16) maxSymbolValue;
890f743729SConrad Meyer     assert(tableLog < 16);   /* required for threshold strategy to work */
900c16b537SWarner Losh 
910c16b537SWarner Losh     /* For explanations on how to distribute symbol values over the table :
920c16b537SWarner Losh      * http://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
930c16b537SWarner Losh 
940f743729SConrad Meyer      #ifdef __clang_analyzer__
95*f7cd7fe5SConrad Meyer      ZSTD_memset(tableSymbol, 0, sizeof(*tableSymbol) * tableSize);   /* useless initialization, just to keep scan-build happy */
960f743729SConrad Meyer      #endif
970f743729SConrad Meyer 
980c16b537SWarner Losh     /* symbol start positions */
990c16b537SWarner Losh     {   U32 u;
1000c16b537SWarner Losh         cumul[0] = 0;
1010c16b537SWarner Losh         for (u=1; u <= maxSymbolValue+1; u++) {
1020c16b537SWarner Losh             if (normalizedCounter[u-1]==-1) {  /* Low proba symbol */
1030c16b537SWarner Losh                 cumul[u] = cumul[u-1] + 1;
1040c16b537SWarner Losh                 tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
1050c16b537SWarner Losh             } else {
1060c16b537SWarner Losh                 cumul[u] = cumul[u-1] + normalizedCounter[u-1];
1070c16b537SWarner Losh         }   }
1080c16b537SWarner Losh         cumul[maxSymbolValue+1] = tableSize+1;
1090c16b537SWarner Losh     }
1100c16b537SWarner Losh 
1110c16b537SWarner Losh     /* Spread symbols */
1120c16b537SWarner Losh     {   U32 position = 0;
1130c16b537SWarner Losh         U32 symbol;
1140c16b537SWarner Losh         for (symbol=0; symbol<=maxSymbolValue; symbol++) {
1152b9c00cbSConrad Meyer             int nbOccurrences;
1160f743729SConrad Meyer             int const freq = normalizedCounter[symbol];
1172b9c00cbSConrad Meyer             for (nbOccurrences=0; nbOccurrences<freq; nbOccurrences++) {
1180c16b537SWarner Losh                 tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
1190c16b537SWarner Losh                 position = (position + step) & tableMask;
1200f743729SConrad Meyer                 while (position > highThreshold)
1210f743729SConrad Meyer                     position = (position + step) & tableMask;   /* Low proba area */
1220c16b537SWarner Losh         }   }
1230c16b537SWarner Losh 
1240f743729SConrad Meyer         assert(position==0);  /* Must have initialized all positions */
1250c16b537SWarner Losh     }
1260c16b537SWarner Losh 
1270c16b537SWarner Losh     /* Build table */
1280c16b537SWarner Losh     {   U32 u; for (u=0; u<tableSize; u++) {
1290c16b537SWarner Losh         FSE_FUNCTION_TYPE s = tableSymbol[u];   /* note : static analyzer may not understand tableSymbol is properly initialized */
1300c16b537SWarner Losh         tableU16[cumul[s]++] = (U16) (tableSize+u);   /* TableU16 : sorted by symbol order; gives next state value */
1310c16b537SWarner Losh     }   }
1320c16b537SWarner Losh 
1330c16b537SWarner Losh     /* Build Symbol Transformation Table */
1340c16b537SWarner Losh     {   unsigned total = 0;
1350c16b537SWarner Losh         unsigned s;
1360c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++) {
1370c16b537SWarner Losh             switch (normalizedCounter[s])
1380c16b537SWarner Losh             {
1390f743729SConrad Meyer             case  0:
1400f743729SConrad Meyer                 /* filling nonetheless, for compatibility with FSE_getMaxNbBits() */
1410f743729SConrad Meyer                 symbolTT[s].deltaNbBits = ((tableLog+1) << 16) - (1<<tableLog);
1420f743729SConrad Meyer                 break;
1430c16b537SWarner Losh 
1440c16b537SWarner Losh             case -1:
1450c16b537SWarner Losh             case  1:
1460c16b537SWarner Losh                 symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
1470c16b537SWarner Losh                 symbolTT[s].deltaFindState = total - 1;
1480c16b537SWarner Losh                 total ++;
1490c16b537SWarner Losh                 break;
1500c16b537SWarner Losh             default :
1510c16b537SWarner Losh                 {
1520c16b537SWarner Losh                     U32 const maxBitsOut = tableLog - BIT_highbit32 (normalizedCounter[s]-1);
1530c16b537SWarner Losh                     U32 const minStatePlus = normalizedCounter[s] << maxBitsOut;
1540c16b537SWarner Losh                     symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
1550c16b537SWarner Losh                     symbolTT[s].deltaFindState = total - normalizedCounter[s];
1560c16b537SWarner Losh                     total +=  normalizedCounter[s];
1570c16b537SWarner Losh     }   }   }   }
1580c16b537SWarner Losh 
1590f743729SConrad Meyer #if 0  /* debug : symbol costs */
1600f743729SConrad Meyer     DEBUGLOG(5, "\n --- table statistics : ");
1610f743729SConrad Meyer     {   U32 symbol;
1620f743729SConrad Meyer         for (symbol=0; symbol<=maxSymbolValue; symbol++) {
1630f743729SConrad Meyer             DEBUGLOG(5, "%3u: w=%3i,   maxBits=%u, fracBits=%.2f",
1640f743729SConrad Meyer                 symbol, normalizedCounter[symbol],
1650f743729SConrad Meyer                 FSE_getMaxNbBits(symbolTT, symbol),
1660f743729SConrad Meyer                 (double)FSE_bitCost(symbolTT, tableLog, symbol, 8) / 256);
1670f743729SConrad Meyer         }
1680f743729SConrad Meyer     }
1690f743729SConrad Meyer #endif
1700f743729SConrad Meyer 
1710c16b537SWarner Losh     return 0;
1720c16b537SWarner Losh }
1730c16b537SWarner Losh 
174*f7cd7fe5SConrad Meyer #ifndef ZSTD_NO_UNUSED_FUNCTIONS
1750c16b537SWarner Losh size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
1760c16b537SWarner Losh {
1770c16b537SWarner Losh     FSE_FUNCTION_TYPE tableSymbol[FSE_MAX_TABLESIZE];   /* memset() is not necessary, even if static analyzer complain about it */
1780c16b537SWarner Losh     return FSE_buildCTable_wksp(ct, normalizedCounter, maxSymbolValue, tableLog, tableSymbol, sizeof(tableSymbol));
1790c16b537SWarner Losh }
180*f7cd7fe5SConrad Meyer #endif
1810c16b537SWarner Losh 
1820c16b537SWarner Losh 
1830c16b537SWarner Losh 
1840c16b537SWarner Losh #ifndef FSE_COMMONDEFS_ONLY
1850c16b537SWarner Losh 
1860f743729SConrad Meyer 
1870c16b537SWarner Losh /*-**************************************************************
1880f743729SConrad Meyer *  FSE NCount encoding
1890c16b537SWarner Losh ****************************************************************/
1900c16b537SWarner Losh size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
1910c16b537SWarner Losh {
1920c16b537SWarner Losh     size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog) >> 3) + 3;
1930c16b537SWarner Losh     return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND;  /* maxSymbolValue==0 ? use default */
1940c16b537SWarner Losh }
1950c16b537SWarner Losh 
1960f743729SConrad Meyer static size_t
1970f743729SConrad Meyer FSE_writeNCount_generic (void* header, size_t headerBufferSize,
1980c16b537SWarner Losh                    const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
1990c16b537SWarner Losh                          unsigned writeIsSafe)
2000c16b537SWarner Losh {
2010c16b537SWarner Losh     BYTE* const ostart = (BYTE*) header;
2020c16b537SWarner Losh     BYTE* out = ostart;
2030c16b537SWarner Losh     BYTE* const oend = ostart + headerBufferSize;
2040c16b537SWarner Losh     int nbBits;
2050c16b537SWarner Losh     const int tableSize = 1 << tableLog;
2060c16b537SWarner Losh     int remaining;
2070c16b537SWarner Losh     int threshold;
2080f743729SConrad Meyer     U32 bitStream = 0;
2090f743729SConrad Meyer     int bitCount = 0;
2100f743729SConrad Meyer     unsigned symbol = 0;
2110f743729SConrad Meyer     unsigned const alphabetSize = maxSymbolValue + 1;
2120f743729SConrad Meyer     int previousIs0 = 0;
2130c16b537SWarner Losh 
2140c16b537SWarner Losh     /* Table Size */
2150c16b537SWarner Losh     bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
2160c16b537SWarner Losh     bitCount  += 4;
2170c16b537SWarner Losh 
2180c16b537SWarner Losh     /* Init */
2190c16b537SWarner Losh     remaining = tableSize+1;   /* +1 for extra accuracy */
2200c16b537SWarner Losh     threshold = tableSize;
2210c16b537SWarner Losh     nbBits = tableLog+1;
2220c16b537SWarner Losh 
2230f743729SConrad Meyer     while ((symbol < alphabetSize) && (remaining>1)) {  /* stops at 1 */
2240f743729SConrad Meyer         if (previousIs0) {
2250f743729SConrad Meyer             unsigned start = symbol;
2260f743729SConrad Meyer             while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
2270f743729SConrad Meyer             if (symbol == alphabetSize) break;   /* incorrect distribution */
2280f743729SConrad Meyer             while (symbol >= start+24) {
2290c16b537SWarner Losh                 start+=24;
2300c16b537SWarner Losh                 bitStream += 0xFFFFU << bitCount;
2310f743729SConrad Meyer                 if ((!writeIsSafe) && (out > oend-2))
2320f743729SConrad Meyer                     return ERROR(dstSize_tooSmall);   /* Buffer overflow */
2330c16b537SWarner Losh                 out[0] = (BYTE) bitStream;
2340c16b537SWarner Losh                 out[1] = (BYTE)(bitStream>>8);
2350c16b537SWarner Losh                 out+=2;
2360c16b537SWarner Losh                 bitStream>>=16;
2370c16b537SWarner Losh             }
2380f743729SConrad Meyer             while (symbol >= start+3) {
2390c16b537SWarner Losh                 start+=3;
2400c16b537SWarner Losh                 bitStream += 3 << bitCount;
2410c16b537SWarner Losh                 bitCount += 2;
2420c16b537SWarner Losh             }
2430f743729SConrad Meyer             bitStream += (symbol-start) << bitCount;
2440c16b537SWarner Losh             bitCount += 2;
2450c16b537SWarner Losh             if (bitCount>16) {
2460f743729SConrad Meyer                 if ((!writeIsSafe) && (out > oend - 2))
2470f743729SConrad Meyer                     return ERROR(dstSize_tooSmall);   /* Buffer overflow */
2480c16b537SWarner Losh                 out[0] = (BYTE)bitStream;
2490c16b537SWarner Losh                 out[1] = (BYTE)(bitStream>>8);
2500c16b537SWarner Losh                 out += 2;
2510c16b537SWarner Losh                 bitStream >>= 16;
2520c16b537SWarner Losh                 bitCount -= 16;
2530c16b537SWarner Losh         }   }
2540f743729SConrad Meyer         {   int count = normalizedCounter[symbol++];
2550c16b537SWarner Losh             int const max = (2*threshold-1) - remaining;
2560c16b537SWarner Losh             remaining -= count < 0 ? -count : count;
2570c16b537SWarner Losh             count++;   /* +1 for extra accuracy */
2580f743729SConrad Meyer             if (count>=threshold)
2590f743729SConrad Meyer                 count += max;   /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
2600c16b537SWarner Losh             bitStream += count << bitCount;
2610c16b537SWarner Losh             bitCount  += nbBits;
2620c16b537SWarner Losh             bitCount  -= (count<max);
2630f743729SConrad Meyer             previousIs0  = (count==1);
2640c16b537SWarner Losh             if (remaining<1) return ERROR(GENERIC);
26519fcbaf1SConrad Meyer             while (remaining<threshold) { nbBits--; threshold>>=1; }
2660c16b537SWarner Losh         }
2670c16b537SWarner Losh         if (bitCount>16) {
2680f743729SConrad Meyer             if ((!writeIsSafe) && (out > oend - 2))
2690f743729SConrad Meyer                 return ERROR(dstSize_tooSmall);   /* Buffer overflow */
2700c16b537SWarner Losh             out[0] = (BYTE)bitStream;
2710c16b537SWarner Losh             out[1] = (BYTE)(bitStream>>8);
2720c16b537SWarner Losh             out += 2;
2730c16b537SWarner Losh             bitStream >>= 16;
2740c16b537SWarner Losh             bitCount -= 16;
2750c16b537SWarner Losh     }   }
2760c16b537SWarner Losh 
2770f743729SConrad Meyer     if (remaining != 1)
2780f743729SConrad Meyer         return ERROR(GENERIC);  /* incorrect normalized distribution */
2790f743729SConrad Meyer     assert(symbol <= alphabetSize);
2800f743729SConrad Meyer 
2810c16b537SWarner Losh     /* flush remaining bitStream */
2820f743729SConrad Meyer     if ((!writeIsSafe) && (out > oend - 2))
2830f743729SConrad Meyer         return ERROR(dstSize_tooSmall);   /* Buffer overflow */
2840c16b537SWarner Losh     out[0] = (BYTE)bitStream;
2850c16b537SWarner Losh     out[1] = (BYTE)(bitStream>>8);
2860c16b537SWarner Losh     out+= (bitCount+7) /8;
2870c16b537SWarner Losh 
2880c16b537SWarner Losh     return (out-ostart);
2890c16b537SWarner Losh }
2900c16b537SWarner Losh 
2910c16b537SWarner Losh 
2920f743729SConrad Meyer size_t FSE_writeNCount (void* buffer, size_t bufferSize,
2930f743729SConrad Meyer                   const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
2940c16b537SWarner Losh {
2950c16b537SWarner Losh     if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);   /* Unsupported */
2960c16b537SWarner Losh     if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC);   /* Unsupported */
2970c16b537SWarner Losh 
2980c16b537SWarner Losh     if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
2990c16b537SWarner Losh         return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
3000c16b537SWarner Losh 
3010f743729SConrad Meyer     return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 /* write in buffer is safe */);
3020c16b537SWarner Losh }
3030c16b537SWarner Losh 
3040c16b537SWarner Losh 
3050c16b537SWarner Losh /*-**************************************************************
3060c16b537SWarner Losh *  FSE Compression Code
3070c16b537SWarner Losh ****************************************************************/
3080c16b537SWarner Losh 
3090c16b537SWarner Losh FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog)
3100c16b537SWarner Losh {
3110c16b537SWarner Losh     size_t size;
3120c16b537SWarner Losh     if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
3130c16b537SWarner Losh     size = FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
314*f7cd7fe5SConrad Meyer     return (FSE_CTable*)ZSTD_malloc(size);
3150c16b537SWarner Losh }
3160c16b537SWarner Losh 
317*f7cd7fe5SConrad Meyer void FSE_freeCTable (FSE_CTable* ct) { ZSTD_free(ct); }
3180c16b537SWarner Losh 
3190c16b537SWarner Losh /* provides the minimum logSize to safely represent a distribution */
3200c16b537SWarner Losh static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
3210c16b537SWarner Losh {
3220f743729SConrad Meyer     U32 minBitsSrc = BIT_highbit32((U32)(srcSize)) + 1;
3230c16b537SWarner Losh     U32 minBitsSymbols = BIT_highbit32(maxSymbolValue) + 2;
3240c16b537SWarner Losh     U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
3250c16b537SWarner Losh     assert(srcSize > 1); /* Not supported, RLE should be used instead */
3260c16b537SWarner Losh     return minBits;
3270c16b537SWarner Losh }
3280c16b537SWarner Losh 
3290c16b537SWarner Losh unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
3300c16b537SWarner Losh {
3310c16b537SWarner Losh     U32 maxBitsSrc = BIT_highbit32((U32)(srcSize - 1)) - minus;
3320c16b537SWarner Losh     U32 tableLog = maxTableLog;
3330c16b537SWarner Losh     U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
3340c16b537SWarner Losh     assert(srcSize > 1); /* Not supported, RLE should be used instead */
3350c16b537SWarner Losh     if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
3360c16b537SWarner Losh     if (maxBitsSrc < tableLog) tableLog = maxBitsSrc;   /* Accuracy can be reduced */
3370c16b537SWarner Losh     if (minBits > tableLog) tableLog = minBits;   /* Need a minimum to safely represent all symbol values */
3380c16b537SWarner Losh     if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
3390c16b537SWarner Losh     if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
3400c16b537SWarner Losh     return tableLog;
3410c16b537SWarner Losh }
3420c16b537SWarner Losh 
3430c16b537SWarner Losh unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
3440c16b537SWarner Losh {
3450c16b537SWarner Losh     return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
3460c16b537SWarner Losh }
3470c16b537SWarner Losh 
3480c16b537SWarner Losh /* Secondary normalization method.
3490c16b537SWarner Losh    To be used when primary method fails. */
3500c16b537SWarner Losh 
351*f7cd7fe5SConrad Meyer static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue, short lowProbCount)
3520c16b537SWarner Losh {
3530c16b537SWarner Losh     short const NOT_YET_ASSIGNED = -2;
3540c16b537SWarner Losh     U32 s;
3550c16b537SWarner Losh     U32 distributed = 0;
3560c16b537SWarner Losh     U32 ToDistribute;
3570c16b537SWarner Losh 
3580c16b537SWarner Losh     /* Init */
3590c16b537SWarner Losh     U32 const lowThreshold = (U32)(total >> tableLog);
3600c16b537SWarner Losh     U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
3610c16b537SWarner Losh 
3620c16b537SWarner Losh     for (s=0; s<=maxSymbolValue; s++) {
3630c16b537SWarner Losh         if (count[s] == 0) {
3640c16b537SWarner Losh             norm[s]=0;
3650c16b537SWarner Losh             continue;
3660c16b537SWarner Losh         }
3670c16b537SWarner Losh         if (count[s] <= lowThreshold) {
368*f7cd7fe5SConrad Meyer             norm[s] = lowProbCount;
3690c16b537SWarner Losh             distributed++;
3700c16b537SWarner Losh             total -= count[s];
3710c16b537SWarner Losh             continue;
3720c16b537SWarner Losh         }
3730c16b537SWarner Losh         if (count[s] <= lowOne) {
3740c16b537SWarner Losh             norm[s] = 1;
3750c16b537SWarner Losh             distributed++;
3760c16b537SWarner Losh             total -= count[s];
3770c16b537SWarner Losh             continue;
3780c16b537SWarner Losh         }
3790c16b537SWarner Losh 
3800c16b537SWarner Losh         norm[s]=NOT_YET_ASSIGNED;
3810c16b537SWarner Losh     }
3820c16b537SWarner Losh     ToDistribute = (1 << tableLog) - distributed;
3830c16b537SWarner Losh 
3840f743729SConrad Meyer     if (ToDistribute == 0)
3850f743729SConrad Meyer         return 0;
3860f743729SConrad Meyer 
3870c16b537SWarner Losh     if ((total / ToDistribute) > lowOne) {
3880c16b537SWarner Losh         /* risk of rounding to zero */
3890c16b537SWarner Losh         lowOne = (U32)((total * 3) / (ToDistribute * 2));
3900c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++) {
3910c16b537SWarner Losh             if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
3920c16b537SWarner Losh                 norm[s] = 1;
3930c16b537SWarner Losh                 distributed++;
3940c16b537SWarner Losh                 total -= count[s];
3950c16b537SWarner Losh                 continue;
3960c16b537SWarner Losh         }   }
3970c16b537SWarner Losh         ToDistribute = (1 << tableLog) - distributed;
3980c16b537SWarner Losh     }
3990c16b537SWarner Losh 
4000c16b537SWarner Losh     if (distributed == maxSymbolValue+1) {
4010c16b537SWarner Losh         /* all values are pretty poor;
4020c16b537SWarner Losh            probably incompressible data (should have already been detected);
4030c16b537SWarner Losh            find max, then give all remaining points to max */
4040c16b537SWarner Losh         U32 maxV = 0, maxC = 0;
4050c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++)
40619fcbaf1SConrad Meyer             if (count[s] > maxC) { maxV=s; maxC=count[s]; }
4070c16b537SWarner Losh         norm[maxV] += (short)ToDistribute;
4080c16b537SWarner Losh         return 0;
4090c16b537SWarner Losh     }
4100c16b537SWarner Losh 
4110c16b537SWarner Losh     if (total == 0) {
4120c16b537SWarner Losh         /* all of the symbols were low enough for the lowOne or lowThreshold */
4130c16b537SWarner Losh         for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
41419fcbaf1SConrad Meyer             if (norm[s] > 0) { ToDistribute--; norm[s]++; }
4150c16b537SWarner Losh         return 0;
4160c16b537SWarner Losh     }
4170c16b537SWarner Losh 
4180c16b537SWarner Losh     {   U64 const vStepLog = 62 - tableLog;
4190c16b537SWarner Losh         U64 const mid = (1ULL << (vStepLog-1)) - 1;
420*f7cd7fe5SConrad Meyer         U64 const rStep = ZSTD_div64((((U64)1<<vStepLog) * ToDistribute) + mid, (U32)total);   /* scale on remaining */
4210c16b537SWarner Losh         U64 tmpTotal = mid;
4220c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++) {
4230c16b537SWarner Losh             if (norm[s]==NOT_YET_ASSIGNED) {
4240c16b537SWarner Losh                 U64 const end = tmpTotal + (count[s] * rStep);
4250c16b537SWarner Losh                 U32 const sStart = (U32)(tmpTotal >> vStepLog);
4260c16b537SWarner Losh                 U32 const sEnd = (U32)(end >> vStepLog);
4270c16b537SWarner Losh                 U32 const weight = sEnd - sStart;
4280c16b537SWarner Losh                 if (weight < 1)
4290c16b537SWarner Losh                     return ERROR(GENERIC);
4300c16b537SWarner Losh                 norm[s] = (short)weight;
4310c16b537SWarner Losh                 tmpTotal = end;
4320c16b537SWarner Losh     }   }   }
4330c16b537SWarner Losh 
4340c16b537SWarner Losh     return 0;
4350c16b537SWarner Losh }
4360c16b537SWarner Losh 
4370c16b537SWarner Losh size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
4380c16b537SWarner Losh                            const unsigned* count, size_t total,
439*f7cd7fe5SConrad Meyer                            unsigned maxSymbolValue, unsigned useLowProbCount)
4400c16b537SWarner Losh {
4410c16b537SWarner Losh     /* Sanity checks */
4420c16b537SWarner Losh     if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
4430c16b537SWarner Losh     if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC);   /* Unsupported size */
4440c16b537SWarner Losh     if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);   /* Unsupported size */
4450c16b537SWarner Losh     if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC);   /* Too small tableLog, compression potentially impossible */
4460c16b537SWarner Losh 
4470c16b537SWarner Losh     {   static U32 const rtbTable[] = {     0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
448*f7cd7fe5SConrad Meyer         short const lowProbCount = useLowProbCount ? -1 : 1;
4490c16b537SWarner Losh         U64 const scale = 62 - tableLog;
450*f7cd7fe5SConrad Meyer         U64 const step = ZSTD_div64((U64)1<<62, (U32)total);   /* <== here, one division ! */
4510c16b537SWarner Losh         U64 const vStep = 1ULL<<(scale-20);
4520c16b537SWarner Losh         int stillToDistribute = 1<<tableLog;
4530c16b537SWarner Losh         unsigned s;
4540c16b537SWarner Losh         unsigned largest=0;
4550c16b537SWarner Losh         short largestP=0;
4560c16b537SWarner Losh         U32 lowThreshold = (U32)(total >> tableLog);
4570c16b537SWarner Losh 
4580c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++) {
4590c16b537SWarner Losh             if (count[s] == total) return 0;   /* rle special case */
4600c16b537SWarner Losh             if (count[s] == 0) { normalizedCounter[s]=0; continue; }
4610c16b537SWarner Losh             if (count[s] <= lowThreshold) {
462*f7cd7fe5SConrad Meyer                 normalizedCounter[s] = lowProbCount;
4630c16b537SWarner Losh                 stillToDistribute--;
4640c16b537SWarner Losh             } else {
4650c16b537SWarner Losh                 short proba = (short)((count[s]*step) >> scale);
4660c16b537SWarner Losh                 if (proba<8) {
4670c16b537SWarner Losh                     U64 restToBeat = vStep * rtbTable[proba];
4680c16b537SWarner Losh                     proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
4690c16b537SWarner Losh                 }
47019fcbaf1SConrad Meyer                 if (proba > largestP) { largestP=proba; largest=s; }
4710c16b537SWarner Losh                 normalizedCounter[s] = proba;
4720c16b537SWarner Losh                 stillToDistribute -= proba;
4730c16b537SWarner Losh         }   }
4740c16b537SWarner Losh         if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
4750c16b537SWarner Losh             /* corner case, need another normalization method */
476*f7cd7fe5SConrad Meyer             size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue, lowProbCount);
4770c16b537SWarner Losh             if (FSE_isError(errorCode)) return errorCode;
4780c16b537SWarner Losh         }
4790c16b537SWarner Losh         else normalizedCounter[largest] += (short)stillToDistribute;
4800c16b537SWarner Losh     }
4810c16b537SWarner Losh 
4820c16b537SWarner Losh #if 0
4830c16b537SWarner Losh     {   /* Print Table (debug) */
4840c16b537SWarner Losh         U32 s;
4850c16b537SWarner Losh         U32 nTotal = 0;
4860c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++)
4870f743729SConrad Meyer             RAWLOG(2, "%3i: %4i \n", s, normalizedCounter[s]);
4880c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++)
4890c16b537SWarner Losh             nTotal += abs(normalizedCounter[s]);
4900c16b537SWarner Losh         if (nTotal != (1U<<tableLog))
4910f743729SConrad Meyer             RAWLOG(2, "Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
4920c16b537SWarner Losh         getchar();
4930c16b537SWarner Losh     }
4940c16b537SWarner Losh #endif
4950c16b537SWarner Losh 
4960c16b537SWarner Losh     return tableLog;
4970c16b537SWarner Losh }
4980c16b537SWarner Losh 
4990c16b537SWarner Losh 
5000c16b537SWarner Losh /* fake FSE_CTable, for raw (uncompressed) input */
5010c16b537SWarner Losh size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits)
5020c16b537SWarner Losh {
5030c16b537SWarner Losh     const unsigned tableSize = 1 << nbBits;
5040c16b537SWarner Losh     const unsigned tableMask = tableSize - 1;
5050c16b537SWarner Losh     const unsigned maxSymbolValue = tableMask;
5060c16b537SWarner Losh     void* const ptr = ct;
5070c16b537SWarner Losh     U16* const tableU16 = ( (U16*) ptr) + 2;
5080c16b537SWarner Losh     void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableSize>>1);   /* assumption : tableLog >= 1 */
5090c16b537SWarner Losh     FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
5100c16b537SWarner Losh     unsigned s;
5110c16b537SWarner Losh 
5120c16b537SWarner Losh     /* Sanity checks */
5130c16b537SWarner Losh     if (nbBits < 1) return ERROR(GENERIC);             /* min size */
5140c16b537SWarner Losh 
5150c16b537SWarner Losh     /* header */
5160c16b537SWarner Losh     tableU16[-2] = (U16) nbBits;
5170c16b537SWarner Losh     tableU16[-1] = (U16) maxSymbolValue;
5180c16b537SWarner Losh 
5190c16b537SWarner Losh     /* Build table */
5200c16b537SWarner Losh     for (s=0; s<tableSize; s++)
5210c16b537SWarner Losh         tableU16[s] = (U16)(tableSize + s);
5220c16b537SWarner Losh 
5230c16b537SWarner Losh     /* Build Symbol Transformation Table */
5240c16b537SWarner Losh     {   const U32 deltaNbBits = (nbBits << 16) - (1 << nbBits);
5250c16b537SWarner Losh         for (s=0; s<=maxSymbolValue; s++) {
5260c16b537SWarner Losh             symbolTT[s].deltaNbBits = deltaNbBits;
5270c16b537SWarner Losh             symbolTT[s].deltaFindState = s-1;
5280c16b537SWarner Losh     }   }
5290c16b537SWarner Losh 
5300c16b537SWarner Losh     return 0;
5310c16b537SWarner Losh }
5320c16b537SWarner Losh 
5330c16b537SWarner Losh /* fake FSE_CTable, for rle input (always same symbol) */
5340c16b537SWarner Losh size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
5350c16b537SWarner Losh {
5360c16b537SWarner Losh     void* ptr = ct;
5370c16b537SWarner Losh     U16* tableU16 = ( (U16*) ptr) + 2;
5380c16b537SWarner Losh     void* FSCTptr = (U32*)ptr + 2;
5390c16b537SWarner Losh     FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
5400c16b537SWarner Losh 
5410c16b537SWarner Losh     /* header */
5420c16b537SWarner Losh     tableU16[-2] = (U16) 0;
5430c16b537SWarner Losh     tableU16[-1] = (U16) symbolValue;
5440c16b537SWarner Losh 
5450c16b537SWarner Losh     /* Build table */
5460c16b537SWarner Losh     tableU16[0] = 0;
5470c16b537SWarner Losh     tableU16[1] = 0;   /* just in case */
5480c16b537SWarner Losh 
5490c16b537SWarner Losh     /* Build Symbol Transformation Table */
5500c16b537SWarner Losh     symbolTT[symbolValue].deltaNbBits = 0;
5510c16b537SWarner Losh     symbolTT[symbolValue].deltaFindState = 0;
5520c16b537SWarner Losh 
5530c16b537SWarner Losh     return 0;
5540c16b537SWarner Losh }
5550c16b537SWarner Losh 
5560c16b537SWarner Losh 
5570c16b537SWarner Losh static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
5580c16b537SWarner Losh                            const void* src, size_t srcSize,
5590c16b537SWarner Losh                            const FSE_CTable* ct, const unsigned fast)
5600c16b537SWarner Losh {
5610c16b537SWarner Losh     const BYTE* const istart = (const BYTE*) src;
5620c16b537SWarner Losh     const BYTE* const iend = istart + srcSize;
5630c16b537SWarner Losh     const BYTE* ip=iend;
5640c16b537SWarner Losh 
5650c16b537SWarner Losh     BIT_CStream_t bitC;
5660c16b537SWarner Losh     FSE_CState_t CState1, CState2;
5670c16b537SWarner Losh 
5680c16b537SWarner Losh     /* init */
5690c16b537SWarner Losh     if (srcSize <= 2) return 0;
5700c16b537SWarner Losh     { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
5710c16b537SWarner Losh       if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
5720c16b537SWarner Losh 
5730c16b537SWarner Losh #define FSE_FLUSHBITS(s)  (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
5740c16b537SWarner Losh 
5750c16b537SWarner Losh     if (srcSize & 1) {
5760c16b537SWarner Losh         FSE_initCState2(&CState1, ct, *--ip);
5770c16b537SWarner Losh         FSE_initCState2(&CState2, ct, *--ip);
5780c16b537SWarner Losh         FSE_encodeSymbol(&bitC, &CState1, *--ip);
5790c16b537SWarner Losh         FSE_FLUSHBITS(&bitC);
5800c16b537SWarner Losh     } else {
5810c16b537SWarner Losh         FSE_initCState2(&CState2, ct, *--ip);
5820c16b537SWarner Losh         FSE_initCState2(&CState1, ct, *--ip);
5830c16b537SWarner Losh     }
5840c16b537SWarner Losh 
5850c16b537SWarner Losh     /* join to mod 4 */
5860c16b537SWarner Losh     srcSize -= 2;
5870c16b537SWarner Losh     if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) {  /* test bit 2 */
5880c16b537SWarner Losh         FSE_encodeSymbol(&bitC, &CState2, *--ip);
5890c16b537SWarner Losh         FSE_encodeSymbol(&bitC, &CState1, *--ip);
5900c16b537SWarner Losh         FSE_FLUSHBITS(&bitC);
5910c16b537SWarner Losh     }
5920c16b537SWarner Losh 
5930c16b537SWarner Losh     /* 2 or 4 encoding per loop */
5940c16b537SWarner Losh     while ( ip>istart ) {
5950c16b537SWarner Losh 
5960c16b537SWarner Losh         FSE_encodeSymbol(&bitC, &CState2, *--ip);
5970c16b537SWarner Losh 
5980c16b537SWarner Losh         if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 )   /* this test must be static */
5990c16b537SWarner Losh             FSE_FLUSHBITS(&bitC);
6000c16b537SWarner Losh 
6010c16b537SWarner Losh         FSE_encodeSymbol(&bitC, &CState1, *--ip);
6020c16b537SWarner Losh 
6030c16b537SWarner Losh         if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) {  /* this test must be static */
6040c16b537SWarner Losh             FSE_encodeSymbol(&bitC, &CState2, *--ip);
6050c16b537SWarner Losh             FSE_encodeSymbol(&bitC, &CState1, *--ip);
6060c16b537SWarner Losh         }
6070c16b537SWarner Losh 
6080c16b537SWarner Losh         FSE_FLUSHBITS(&bitC);
6090c16b537SWarner Losh     }
6100c16b537SWarner Losh 
6110c16b537SWarner Losh     FSE_flushCState(&bitC, &CState2);
6120c16b537SWarner Losh     FSE_flushCState(&bitC, &CState1);
6130c16b537SWarner Losh     return BIT_closeCStream(&bitC);
6140c16b537SWarner Losh }
6150c16b537SWarner Losh 
6160c16b537SWarner Losh size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
6170c16b537SWarner Losh                            const void* src, size_t srcSize,
6180c16b537SWarner Losh                            const FSE_CTable* ct)
6190c16b537SWarner Losh {
6200c16b537SWarner Losh     unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
6210c16b537SWarner Losh 
6220c16b537SWarner Losh     if (fast)
6230c16b537SWarner Losh         return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
6240c16b537SWarner Losh     else
6250c16b537SWarner Losh         return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
6260c16b537SWarner Losh }
6270c16b537SWarner Losh 
6280c16b537SWarner Losh 
6290c16b537SWarner Losh size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
6300c16b537SWarner Losh 
631*f7cd7fe5SConrad Meyer #ifndef ZSTD_NO_UNUSED_FUNCTIONS
6320c16b537SWarner Losh /* FSE_compress_wksp() :
6330c16b537SWarner Losh  * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
6340c16b537SWarner Losh  * `wkspSize` size must be `(1<<tableLog)`.
6350c16b537SWarner Losh  */
6360c16b537SWarner Losh size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
6370c16b537SWarner Losh {
6380c16b537SWarner Losh     BYTE* const ostart = (BYTE*) dst;
6390c16b537SWarner Losh     BYTE* op = ostart;
6400c16b537SWarner Losh     BYTE* const oend = ostart + dstSize;
6410c16b537SWarner Losh 
642a0483764SConrad Meyer     unsigned count[FSE_MAX_SYMBOL_VALUE+1];
6430c16b537SWarner Losh     S16   norm[FSE_MAX_SYMBOL_VALUE+1];
6440c16b537SWarner Losh     FSE_CTable* CTable = (FSE_CTable*)workSpace;
6450c16b537SWarner Losh     size_t const CTableSize = FSE_CTABLE_SIZE_U32(tableLog, maxSymbolValue);
6460c16b537SWarner Losh     void* scratchBuffer = (void*)(CTable + CTableSize);
6470c16b537SWarner Losh     size_t const scratchBufferSize = wkspSize - (CTableSize * sizeof(FSE_CTable));
6480c16b537SWarner Losh 
6490c16b537SWarner Losh     /* init conditions */
650*f7cd7fe5SConrad Meyer     if (wkspSize < FSE_COMPRESS_WKSP_SIZE_U32(tableLog, maxSymbolValue)) return ERROR(tableLog_tooLarge);
6510c16b537SWarner Losh     if (srcSize <= 1) return 0;  /* Not compressible */
6520c16b537SWarner Losh     if (!maxSymbolValue) maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
6530c16b537SWarner Losh     if (!tableLog) tableLog = FSE_DEFAULT_TABLELOG;
6540c16b537SWarner Losh 
6550c16b537SWarner Losh     /* Scan input and build symbol stats */
656a0483764SConrad Meyer     {   CHECK_V_F(maxCount, HIST_count_wksp(count, &maxSymbolValue, src, srcSize, scratchBuffer, scratchBufferSize) );
6570c16b537SWarner Losh         if (maxCount == srcSize) return 1;   /* only a single symbol in src : rle */
6580c16b537SWarner Losh         if (maxCount == 1) return 0;         /* each symbol present maximum once => not compressible */
6590c16b537SWarner Losh         if (maxCount < (srcSize >> 7)) return 0;   /* Heuristic : not compressible enough */
6600c16b537SWarner Losh     }
6610c16b537SWarner Losh 
6620c16b537SWarner Losh     tableLog = FSE_optimalTableLog(tableLog, srcSize, maxSymbolValue);
663*f7cd7fe5SConrad Meyer     CHECK_F( FSE_normalizeCount(norm, tableLog, count, srcSize, maxSymbolValue, /* useLowProbCount */ srcSize >= 2048) );
6640c16b537SWarner Losh 
6650c16b537SWarner Losh     /* Write table description header */
6660c16b537SWarner Losh     {   CHECK_V_F(nc_err, FSE_writeNCount(op, oend-op, norm, maxSymbolValue, tableLog) );
6670c16b537SWarner Losh         op += nc_err;
6680c16b537SWarner Losh     }
6690c16b537SWarner Losh 
6700c16b537SWarner Losh     /* Compress */
6710c16b537SWarner Losh     CHECK_F( FSE_buildCTable_wksp(CTable, norm, maxSymbolValue, tableLog, scratchBuffer, scratchBufferSize) );
6720c16b537SWarner Losh     {   CHECK_V_F(cSize, FSE_compress_usingCTable(op, oend - op, src, srcSize, CTable) );
6730c16b537SWarner Losh         if (cSize == 0) return 0;   /* not enough space for compressed data */
6740c16b537SWarner Losh         op += cSize;
6750c16b537SWarner Losh     }
6760c16b537SWarner Losh 
6770c16b537SWarner Losh     /* check compressibility */
6780c16b537SWarner Losh     if ( (size_t)(op-ostart) >= srcSize-1 ) return 0;
6790c16b537SWarner Losh 
6800c16b537SWarner Losh     return op-ostart;
6810c16b537SWarner Losh }
6820c16b537SWarner Losh 
6830c16b537SWarner Losh typedef struct {
6840c16b537SWarner Losh     FSE_CTable CTable_max[FSE_CTABLE_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)];
685*f7cd7fe5SConrad Meyer     union {
686*f7cd7fe5SConrad Meyer       U32 hist_wksp[HIST_WKSP_SIZE_U32];
6870c16b537SWarner Losh       BYTE scratchBuffer[1 << FSE_MAX_TABLELOG];
688*f7cd7fe5SConrad Meyer     } workspace;
6890c16b537SWarner Losh } fseWkspMax_t;
6900c16b537SWarner Losh 
6910c16b537SWarner Losh size_t FSE_compress2 (void* dst, size_t dstCapacity, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog)
6920c16b537SWarner Losh {
6930c16b537SWarner Losh     fseWkspMax_t scratchBuffer;
694*f7cd7fe5SConrad Meyer     DEBUG_STATIC_ASSERT(sizeof(scratchBuffer) >= FSE_COMPRESS_WKSP_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE));   /* compilation failures here means scratchBuffer is not large enough */
6950c16b537SWarner Losh     if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
6960c16b537SWarner Losh     return FSE_compress_wksp(dst, dstCapacity, src, srcSize, maxSymbolValue, tableLog, &scratchBuffer, sizeof(scratchBuffer));
6970c16b537SWarner Losh }
6980c16b537SWarner Losh 
6990c16b537SWarner Losh size_t FSE_compress (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
7000c16b537SWarner Losh {
7010c16b537SWarner Losh     return FSE_compress2(dst, dstCapacity, src, srcSize, FSE_MAX_SYMBOL_VALUE, FSE_DEFAULT_TABLELOG);
7020c16b537SWarner Losh }
703*f7cd7fe5SConrad Meyer #endif
7040c16b537SWarner Losh 
7050c16b537SWarner Losh #endif   /* FSE_COMMONDEFS_ONLY */
706