xref: /freebsd/sys/contrib/zstd/lib/dictBuilder/zdict.c (revision 98689d0ffb0a0e218d3b32201df59be9fa771830)
10c16b537SWarner Losh /*
237f1f268SConrad Meyer  * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
30c16b537SWarner Losh  * All rights reserved.
40c16b537SWarner Losh  *
50c16b537SWarner Losh  * This source code is licensed under both the BSD-style license (found in the
60c16b537SWarner Losh  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
70c16b537SWarner Losh  * in the COPYING file in the root directory of this source tree).
80c16b537SWarner Losh  * You may select, at your option, one of the above-listed licenses.
90c16b537SWarner Losh  */
100c16b537SWarner Losh 
110c16b537SWarner Losh 
120c16b537SWarner Losh /*-**************************************
130c16b537SWarner Losh *  Tuning parameters
140c16b537SWarner Losh ****************************************/
150c16b537SWarner Losh #define MINRATIO 4   /* minimum nb of apparition to be selected in dictionary */
160c16b537SWarner Losh #define ZDICT_MAX_SAMPLES_SIZE (2000U << 20)
170c16b537SWarner Losh #define ZDICT_MIN_SAMPLES_SIZE (ZDICT_CONTENTSIZE_MIN * MINRATIO)
180c16b537SWarner Losh 
190c16b537SWarner Losh 
200c16b537SWarner Losh /*-**************************************
210c16b537SWarner Losh *  Compiler Options
220c16b537SWarner Losh ****************************************/
230c16b537SWarner Losh /* Unix Large Files support (>4GB) */
240c16b537SWarner Losh #define _FILE_OFFSET_BITS 64
250c16b537SWarner Losh #if (defined(__sun__) && (!defined(__LP64__)))   /* Sun Solaris 32-bits requires specific definitions */
260c16b537SWarner Losh #  define _LARGEFILE_SOURCE
270c16b537SWarner Losh #elif ! defined(__LP64__)                        /* No point defining Large file for 64 bit */
280c16b537SWarner Losh #  define _LARGEFILE64_SOURCE
290c16b537SWarner Losh #endif
300c16b537SWarner Losh 
310c16b537SWarner Losh 
320c16b537SWarner Losh /*-*************************************
330c16b537SWarner Losh *  Dependencies
340c16b537SWarner Losh ***************************************/
350c16b537SWarner Losh #include <stdlib.h>        /* malloc, free */
360c16b537SWarner Losh #include <string.h>        /* memset */
370c16b537SWarner Losh #include <stdio.h>         /* fprintf, fopen, ftello64 */
380c16b537SWarner Losh #include <time.h>          /* clock */
390c16b537SWarner Losh 
4037f1f268SConrad Meyer #include "../common/mem.h"           /* read */
4137f1f268SConrad Meyer #include "../common/fse.h"           /* FSE_normalizeCount, FSE_writeNCount */
420c16b537SWarner Losh #define HUF_STATIC_LINKING_ONLY
4337f1f268SConrad Meyer #include "../common/huf.h"           /* HUF_buildCTable, HUF_writeCTable */
4437f1f268SConrad Meyer #include "../common/zstd_internal.h" /* includes zstd.h */
4537f1f268SConrad Meyer #include "../common/xxhash.h"        /* XXH64 */
460c16b537SWarner Losh #include "divsufsort.h"
470c16b537SWarner Losh #ifndef ZDICT_STATIC_LINKING_ONLY
480c16b537SWarner Losh #  define ZDICT_STATIC_LINKING_ONLY
490c16b537SWarner Losh #endif
500c16b537SWarner Losh #include "zdict.h"
5137f1f268SConrad Meyer #include "../compress/zstd_compress_internal.h" /* ZSTD_loadCEntropy() */
520c16b537SWarner Losh 
530c16b537SWarner Losh 
540c16b537SWarner Losh /*-*************************************
550c16b537SWarner Losh *  Constants
560c16b537SWarner Losh ***************************************/
570c16b537SWarner Losh #define KB *(1 <<10)
580c16b537SWarner Losh #define MB *(1 <<20)
590c16b537SWarner Losh #define GB *(1U<<30)
600c16b537SWarner Losh 
610c16b537SWarner Losh #define DICTLISTSIZE_DEFAULT 10000
620c16b537SWarner Losh 
630c16b537SWarner Losh #define NOISELENGTH 32
640c16b537SWarner Losh 
650c16b537SWarner Losh static const U32 g_selectivity_default = 9;
660c16b537SWarner Losh 
670c16b537SWarner Losh 
680c16b537SWarner Losh /*-*************************************
690c16b537SWarner Losh *  Console display
700c16b537SWarner Losh ***************************************/
71f7cd7fe5SConrad Meyer #undef  DISPLAY
720c16b537SWarner Losh #define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
73f7cd7fe5SConrad Meyer #undef  DISPLAYLEVEL
740c16b537SWarner Losh #define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); }    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
750c16b537SWarner Losh 
760c16b537SWarner Losh static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
770c16b537SWarner Losh 
780c16b537SWarner Losh static void ZDICT_printHex(const void* ptr, size_t length)
790c16b537SWarner Losh {
800c16b537SWarner Losh     const BYTE* const b = (const BYTE*)ptr;
810c16b537SWarner Losh     size_t u;
820c16b537SWarner Losh     for (u=0; u<length; u++) {
830c16b537SWarner Losh         BYTE c = b[u];
840c16b537SWarner Losh         if (c<32 || c>126) c = '.';   /* non-printable char */
850c16b537SWarner Losh         DISPLAY("%c", c);
860c16b537SWarner Losh     }
870c16b537SWarner Losh }
880c16b537SWarner Losh 
890c16b537SWarner Losh 
900c16b537SWarner Losh /*-********************************************************
910c16b537SWarner Losh *  Helper functions
920c16b537SWarner Losh **********************************************************/
930c16b537SWarner Losh unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
940c16b537SWarner Losh 
950c16b537SWarner Losh const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
960c16b537SWarner Losh 
970c16b537SWarner Losh unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
980c16b537SWarner Losh {
990c16b537SWarner Losh     if (dictSize < 8) return 0;
1000c16b537SWarner Losh     if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
1010c16b537SWarner Losh     return MEM_readLE32((const char*)dictBuffer + 4);
1020c16b537SWarner Losh }
1030c16b537SWarner Losh 
10437f1f268SConrad Meyer size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)
10537f1f268SConrad Meyer {
10637f1f268SConrad Meyer     size_t headerSize;
10737f1f268SConrad Meyer     if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);
10837f1f268SConrad Meyer 
109f7cd7fe5SConrad Meyer     {   ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));
11037f1f268SConrad Meyer         U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);
111f7cd7fe5SConrad Meyer         if (!bs || !wksp) {
11237f1f268SConrad Meyer             headerSize = ERROR(memory_allocation);
11337f1f268SConrad Meyer         } else {
11437f1f268SConrad Meyer             ZSTD_reset_compressedBlockState(bs);
115f7cd7fe5SConrad Meyer             headerSize = ZSTD_loadCEntropy(bs, wksp, dictBuffer, dictSize);
11637f1f268SConrad Meyer         }
11737f1f268SConrad Meyer 
11837f1f268SConrad Meyer         free(bs);
11937f1f268SConrad Meyer         free(wksp);
12037f1f268SConrad Meyer     }
12137f1f268SConrad Meyer 
12237f1f268SConrad Meyer     return headerSize;
12337f1f268SConrad Meyer }
1240c16b537SWarner Losh 
1250c16b537SWarner Losh /*-********************************************************
1260c16b537SWarner Losh *  Dictionary training functions
1270c16b537SWarner Losh **********************************************************/
128052d3c12SConrad Meyer static unsigned ZDICT_NbCommonBytes (size_t val)
1290c16b537SWarner Losh {
1300c16b537SWarner Losh     if (MEM_isLittleEndian()) {
1310c16b537SWarner Losh         if (MEM_64bits()) {
1320c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
1330c16b537SWarner Losh             unsigned long r = 0;
1340c16b537SWarner Losh             _BitScanForward64( &r, (U64)val );
1350c16b537SWarner Losh             return (unsigned)(r>>3);
1360c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1370c16b537SWarner Losh             return (__builtin_ctzll((U64)val) >> 3);
1380c16b537SWarner Losh #       else
1390c16b537SWarner Losh             static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
1400c16b537SWarner Losh             return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
1410c16b537SWarner Losh #       endif
1420c16b537SWarner Losh         } else { /* 32 bits */
1430c16b537SWarner Losh #       if defined(_MSC_VER)
1440c16b537SWarner Losh             unsigned long r=0;
1450c16b537SWarner Losh             _BitScanForward( &r, (U32)val );
1460c16b537SWarner Losh             return (unsigned)(r>>3);
1470c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1480c16b537SWarner Losh             return (__builtin_ctz((U32)val) >> 3);
1490c16b537SWarner Losh #       else
1500c16b537SWarner Losh             static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
1510c16b537SWarner Losh             return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
1520c16b537SWarner Losh #       endif
1530c16b537SWarner Losh         }
1540c16b537SWarner Losh     } else {  /* Big Endian CPU */
1550c16b537SWarner Losh         if (MEM_64bits()) {
1560c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
1570c16b537SWarner Losh             unsigned long r = 0;
1580c16b537SWarner Losh             _BitScanReverse64( &r, val );
1590c16b537SWarner Losh             return (unsigned)(r>>3);
1600c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1610c16b537SWarner Losh             return (__builtin_clzll(val) >> 3);
1620c16b537SWarner Losh #       else
1630c16b537SWarner Losh             unsigned r;
1640c16b537SWarner Losh             const unsigned n32 = sizeof(size_t)*4;   /* calculate this way due to compiler complaining in 32-bits mode */
1650c16b537SWarner Losh             if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
1660c16b537SWarner Losh             if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
1670c16b537SWarner Losh             r += (!val);
1680c16b537SWarner Losh             return r;
1690c16b537SWarner Losh #       endif
1700c16b537SWarner Losh         } else { /* 32 bits */
1710c16b537SWarner Losh #       if defined(_MSC_VER)
1720c16b537SWarner Losh             unsigned long r = 0;
1730c16b537SWarner Losh             _BitScanReverse( &r, (unsigned long)val );
1740c16b537SWarner Losh             return (unsigned)(r>>3);
1750c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1760c16b537SWarner Losh             return (__builtin_clz((U32)val) >> 3);
1770c16b537SWarner Losh #       else
1780c16b537SWarner Losh             unsigned r;
1790c16b537SWarner Losh             if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
1800c16b537SWarner Losh             r += (!val);
1810c16b537SWarner Losh             return r;
1820c16b537SWarner Losh #       endif
1830c16b537SWarner Losh     }   }
1840c16b537SWarner Losh }
1850c16b537SWarner Losh 
1860c16b537SWarner Losh 
1870c16b537SWarner Losh /*! ZDICT_count() :
1880c16b537SWarner Losh     Count the nb of common bytes between 2 pointers.
1890c16b537SWarner Losh     Note : this function presumes end of buffer followed by noisy guard band.
1900c16b537SWarner Losh */
1910c16b537SWarner Losh static size_t ZDICT_count(const void* pIn, const void* pMatch)
1920c16b537SWarner Losh {
1930c16b537SWarner Losh     const char* const pStart = (const char*)pIn;
1940c16b537SWarner Losh     for (;;) {
1950c16b537SWarner Losh         size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
1960c16b537SWarner Losh         if (!diff) {
1970c16b537SWarner Losh             pIn = (const char*)pIn+sizeof(size_t);
1980c16b537SWarner Losh             pMatch = (const char*)pMatch+sizeof(size_t);
1990c16b537SWarner Losh             continue;
2000c16b537SWarner Losh         }
2010c16b537SWarner Losh         pIn = (const char*)pIn+ZDICT_NbCommonBytes(diff);
2020c16b537SWarner Losh         return (size_t)((const char*)pIn - pStart);
2030c16b537SWarner Losh     }
2040c16b537SWarner Losh }
2050c16b537SWarner Losh 
2060c16b537SWarner Losh 
2070c16b537SWarner Losh typedef struct {
2080c16b537SWarner Losh     U32 pos;
2090c16b537SWarner Losh     U32 length;
2100c16b537SWarner Losh     U32 savings;
2110c16b537SWarner Losh } dictItem;
2120c16b537SWarner Losh 
2130c16b537SWarner Losh static void ZDICT_initDictItem(dictItem* d)
2140c16b537SWarner Losh {
2150c16b537SWarner Losh     d->pos = 1;
2160c16b537SWarner Losh     d->length = 0;
2170c16b537SWarner Losh     d->savings = (U32)(-1);
2180c16b537SWarner Losh }
2190c16b537SWarner Losh 
2200c16b537SWarner Losh 
2210c16b537SWarner Losh #define LLIMIT 64          /* heuristic determined experimentally */
2220c16b537SWarner Losh #define MINMATCHLENGTH 7   /* heuristic determined experimentally */
2230c16b537SWarner Losh static dictItem ZDICT_analyzePos(
2240c16b537SWarner Losh                        BYTE* doneMarks,
2250c16b537SWarner Losh                        const int* suffix, U32 start,
2260c16b537SWarner Losh                        const void* buffer, U32 minRatio, U32 notificationLevel)
2270c16b537SWarner Losh {
2280c16b537SWarner Losh     U32 lengthList[LLIMIT] = {0};
2290c16b537SWarner Losh     U32 cumulLength[LLIMIT] = {0};
2300c16b537SWarner Losh     U32 savings[LLIMIT] = {0};
2310c16b537SWarner Losh     const BYTE* b = (const BYTE*)buffer;
2320c16b537SWarner Losh     size_t maxLength = LLIMIT;
2330c16b537SWarner Losh     size_t pos = suffix[start];
2340c16b537SWarner Losh     U32 end = start;
2350c16b537SWarner Losh     dictItem solution;
2360c16b537SWarner Losh 
2370c16b537SWarner Losh     /* init */
2380c16b537SWarner Losh     memset(&solution, 0, sizeof(solution));
2390c16b537SWarner Losh     doneMarks[pos] = 1;
2400c16b537SWarner Losh 
2410c16b537SWarner Losh     /* trivial repetition cases */
2420c16b537SWarner Losh     if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
2430c16b537SWarner Losh        ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
2440c16b537SWarner Losh        ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
2450c16b537SWarner Losh         /* skip and mark segment */
24619fcbaf1SConrad Meyer         U16 const pattern16 = MEM_read16(b+pos+4);
24719fcbaf1SConrad Meyer         U32 u, patternEnd = 6;
24819fcbaf1SConrad Meyer         while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
24919fcbaf1SConrad Meyer         if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
25019fcbaf1SConrad Meyer         for (u=1; u<patternEnd; u++)
2510c16b537SWarner Losh             doneMarks[pos+u] = 1;
2520c16b537SWarner Losh         return solution;
2530c16b537SWarner Losh     }
2540c16b537SWarner Losh 
2550c16b537SWarner Losh     /* look forward */
25619fcbaf1SConrad Meyer     {   size_t length;
2570c16b537SWarner Losh         do {
2580c16b537SWarner Losh             end++;
2590c16b537SWarner Losh             length = ZDICT_count(b + pos, b + suffix[end]);
2600c16b537SWarner Losh         } while (length >= MINMATCHLENGTH);
26119fcbaf1SConrad Meyer     }
2620c16b537SWarner Losh 
2630c16b537SWarner Losh     /* look backward */
26419fcbaf1SConrad Meyer     {   size_t length;
2650c16b537SWarner Losh         do {
2660c16b537SWarner Losh             length = ZDICT_count(b + pos, b + *(suffix+start-1));
2670c16b537SWarner Losh             if (length >=MINMATCHLENGTH) start--;
2680c16b537SWarner Losh         } while(length >= MINMATCHLENGTH);
26919fcbaf1SConrad Meyer     }
2700c16b537SWarner Losh 
2710c16b537SWarner Losh     /* exit if not found a minimum nb of repetitions */
2720c16b537SWarner Losh     if (end-start < minRatio) {
2730c16b537SWarner Losh         U32 idx;
2740c16b537SWarner Losh         for(idx=start; idx<end; idx++)
2750c16b537SWarner Losh             doneMarks[suffix[idx]] = 1;
2760c16b537SWarner Losh         return solution;
2770c16b537SWarner Losh     }
2780c16b537SWarner Losh 
2790c16b537SWarner Losh     {   int i;
280a0483764SConrad Meyer         U32 mml;
2810c16b537SWarner Losh         U32 refinedStart = start;
2820c16b537SWarner Losh         U32 refinedEnd = end;
2830c16b537SWarner Losh 
2840c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
285a0483764SConrad Meyer         DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u  ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
2860c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
2870c16b537SWarner Losh 
288a0483764SConrad Meyer         for (mml = MINMATCHLENGTH ; ; mml++) {
2890c16b537SWarner Losh             BYTE currentChar = 0;
2900c16b537SWarner Losh             U32 currentCount = 0;
2910c16b537SWarner Losh             U32 currentID = refinedStart;
2920c16b537SWarner Losh             U32 id;
2930c16b537SWarner Losh             U32 selectedCount = 0;
2940c16b537SWarner Losh             U32 selectedID = currentID;
2950c16b537SWarner Losh             for (id =refinedStart; id < refinedEnd; id++) {
296a0483764SConrad Meyer                 if (b[suffix[id] + mml] != currentChar) {
2970c16b537SWarner Losh                     if (currentCount > selectedCount) {
2980c16b537SWarner Losh                         selectedCount = currentCount;
2990c16b537SWarner Losh                         selectedID = currentID;
3000c16b537SWarner Losh                     }
3010c16b537SWarner Losh                     currentID = id;
302a0483764SConrad Meyer                     currentChar = b[ suffix[id] + mml];
3030c16b537SWarner Losh                     currentCount = 0;
3040c16b537SWarner Losh                 }
3050c16b537SWarner Losh                 currentCount ++;
3060c16b537SWarner Losh             }
3070c16b537SWarner Losh             if (currentCount > selectedCount) {  /* for last */
3080c16b537SWarner Losh                 selectedCount = currentCount;
3090c16b537SWarner Losh                 selectedID = currentID;
3100c16b537SWarner Losh             }
3110c16b537SWarner Losh 
3120c16b537SWarner Losh             if (selectedCount < minRatio)
3130c16b537SWarner Losh                 break;
3140c16b537SWarner Losh             refinedStart = selectedID;
3150c16b537SWarner Losh             refinedEnd = refinedStart + selectedCount;
3160c16b537SWarner Losh         }
3170c16b537SWarner Losh 
3180f743729SConrad Meyer         /* evaluate gain based on new dict */
3190c16b537SWarner Losh         start = refinedStart;
3200c16b537SWarner Losh         pos = suffix[refinedStart];
3210c16b537SWarner Losh         end = start;
3220c16b537SWarner Losh         memset(lengthList, 0, sizeof(lengthList));
3230c16b537SWarner Losh 
3240c16b537SWarner Losh         /* look forward */
32519fcbaf1SConrad Meyer         {   size_t length;
3260c16b537SWarner Losh             do {
3270c16b537SWarner Losh                 end++;
3280c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[end]);
3290c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT-1;
3300c16b537SWarner Losh                 lengthList[length]++;
3310c16b537SWarner Losh             } while (length >=MINMATCHLENGTH);
33219fcbaf1SConrad Meyer         }
3330c16b537SWarner Losh 
3340c16b537SWarner Losh         /* look backward */
33519fcbaf1SConrad Meyer         {   size_t length = MINMATCHLENGTH;
3360c16b537SWarner Losh             while ((length >= MINMATCHLENGTH) & (start > 0)) {
3370c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[start - 1]);
3380c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT - 1;
3390c16b537SWarner Losh                 lengthList[length]++;
3400c16b537SWarner Losh                 if (length >= MINMATCHLENGTH) start--;
3410c16b537SWarner Losh             }
34219fcbaf1SConrad Meyer         }
3430c16b537SWarner Losh 
3440c16b537SWarner Losh         /* largest useful length */
3450c16b537SWarner Losh         memset(cumulLength, 0, sizeof(cumulLength));
3460c16b537SWarner Losh         cumulLength[maxLength-1] = lengthList[maxLength-1];
3470c16b537SWarner Losh         for (i=(int)(maxLength-2); i>=0; i--)
3480c16b537SWarner Losh             cumulLength[i] = cumulLength[i+1] + lengthList[i];
3490c16b537SWarner Losh 
3500c16b537SWarner Losh         for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
3510c16b537SWarner Losh         maxLength = i;
3520c16b537SWarner Losh 
3530c16b537SWarner Losh         /* reduce maxLength in case of final into repetitive data */
3540c16b537SWarner Losh         {   U32 l = (U32)maxLength;
3550c16b537SWarner Losh             BYTE const c = b[pos + maxLength-1];
3560c16b537SWarner Losh             while (b[pos+l-2]==c) l--;
3570c16b537SWarner Losh             maxLength = l;
3580c16b537SWarner Losh         }
3590c16b537SWarner Losh         if (maxLength < MINMATCHLENGTH) return solution;   /* skip : no long-enough solution */
3600c16b537SWarner Losh 
3610c16b537SWarner Losh         /* calculate savings */
3620c16b537SWarner Losh         savings[5] = 0;
3630c16b537SWarner Losh         for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
3640c16b537SWarner Losh             savings[i] = savings[i-1] + (lengthList[i] * (i-3));
3650c16b537SWarner Losh 
3660f743729SConrad Meyer         DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f)  \n",
367a0483764SConrad Meyer                      (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / maxLength);
3680c16b537SWarner Losh 
3690c16b537SWarner Losh         solution.pos = (U32)pos;
3700c16b537SWarner Losh         solution.length = (U32)maxLength;
3710c16b537SWarner Losh         solution.savings = savings[maxLength];
3720c16b537SWarner Losh 
3730c16b537SWarner Losh         /* mark positions done */
3740c16b537SWarner Losh         {   U32 id;
3750c16b537SWarner Losh             for (id=start; id<end; id++) {
37619fcbaf1SConrad Meyer                 U32 p, pEnd, length;
3770c16b537SWarner Losh                 U32 const testedPos = suffix[id];
3780c16b537SWarner Losh                 if (testedPos == pos)
3790c16b537SWarner Losh                     length = solution.length;
3800c16b537SWarner Losh                 else {
38119fcbaf1SConrad Meyer                     length = (U32)ZDICT_count(b+pos, b+testedPos);
3820c16b537SWarner Losh                     if (length > solution.length) length = solution.length;
3830c16b537SWarner Losh                 }
3840c16b537SWarner Losh                 pEnd = (U32)(testedPos + length);
3850c16b537SWarner Losh                 for (p=testedPos; p<pEnd; p++)
3860c16b537SWarner Losh                     doneMarks[p] = 1;
3870c16b537SWarner Losh     }   }   }
3880c16b537SWarner Losh 
3890c16b537SWarner Losh     return solution;
3900c16b537SWarner Losh }
3910c16b537SWarner Losh 
3920c16b537SWarner Losh 
3930c16b537SWarner Losh static int isIncluded(const void* in, const void* container, size_t length)
3940c16b537SWarner Losh {
3950c16b537SWarner Losh     const char* const ip = (const char*) in;
3960c16b537SWarner Losh     const char* const into = (const char*) container;
3970c16b537SWarner Losh     size_t u;
3980c16b537SWarner Losh 
3990c16b537SWarner Losh     for (u=0; u<length; u++) {  /* works because end of buffer is a noisy guard band */
4000c16b537SWarner Losh         if (ip[u] != into[u]) break;
4010c16b537SWarner Losh     }
4020c16b537SWarner Losh 
4030c16b537SWarner Losh     return u==length;
4040c16b537SWarner Losh }
4050c16b537SWarner Losh 
4060c16b537SWarner Losh /*! ZDICT_tryMerge() :
4070c16b537SWarner Losh     check if dictItem can be merged, do it if possible
4080c16b537SWarner Losh     @return : id of destination elt, 0 if not merged
4090c16b537SWarner Losh */
4100c16b537SWarner Losh static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
4110c16b537SWarner Losh {
4120c16b537SWarner Losh     const U32 tableSize = table->pos;
4130c16b537SWarner Losh     const U32 eltEnd = elt.pos + elt.length;
4140c16b537SWarner Losh     const char* const buf = (const char*) buffer;
4150c16b537SWarner Losh 
4160c16b537SWarner Losh     /* tail overlap */
4170c16b537SWarner Losh     U32 u; for (u=1; u<tableSize; u++) {
4180c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4190c16b537SWarner Losh         if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) {  /* overlap, existing > new */
4200c16b537SWarner Losh             /* append */
4210c16b537SWarner Losh             U32 const addedLength = table[u].pos - elt.pos;
4220c16b537SWarner Losh             table[u].length += addedLength;
4230c16b537SWarner Losh             table[u].pos = elt.pos;
4240c16b537SWarner Losh             table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4250c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4260c16b537SWarner Losh             elt = table[u];
4270c16b537SWarner Losh             /* sort : improve rank */
4280c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4290c16b537SWarner Losh             table[u] = table[u-1], u--;
4300c16b537SWarner Losh             table[u] = elt;
4310c16b537SWarner Losh             return u;
4320c16b537SWarner Losh     }   }
4330c16b537SWarner Losh 
4340c16b537SWarner Losh     /* front overlap */
4350c16b537SWarner Losh     for (u=1; u<tableSize; u++) {
4360c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4370c16b537SWarner Losh 
4380c16b537SWarner Losh         if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) {  /* overlap, existing < new */
4390c16b537SWarner Losh             /* append */
4400c16b537SWarner Losh             int const addedLength = (int)eltEnd - (table[u].pos + table[u].length);
4410c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4420c16b537SWarner Losh             if (addedLength > 0) {   /* otherwise, elt fully included into existing */
4430c16b537SWarner Losh                 table[u].length += addedLength;
4440c16b537SWarner Losh                 table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4450c16b537SWarner Losh             }
4460c16b537SWarner Losh             /* sort : improve rank */
4470c16b537SWarner Losh             elt = table[u];
4480c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4490c16b537SWarner Losh                 table[u] = table[u-1], u--;
4500c16b537SWarner Losh             table[u] = elt;
4510c16b537SWarner Losh             return u;
4520c16b537SWarner Losh         }
4530c16b537SWarner Losh 
4540c16b537SWarner Losh         if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
4550c16b537SWarner Losh             if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
4560c16b537SWarner Losh                 size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
4570c16b537SWarner Losh                 table[u].pos = elt.pos;
4580c16b537SWarner Losh                 table[u].savings += (U32)(elt.savings * addedLength / elt.length);
4590c16b537SWarner Losh                 table[u].length = MIN(elt.length, table[u].length + 1);
4600c16b537SWarner Losh                 return u;
4610c16b537SWarner Losh             }
4620c16b537SWarner Losh         }
4630c16b537SWarner Losh     }
4640c16b537SWarner Losh 
4650c16b537SWarner Losh     return 0;
4660c16b537SWarner Losh }
4670c16b537SWarner Losh 
4680c16b537SWarner Losh 
4690c16b537SWarner Losh static void ZDICT_removeDictItem(dictItem* table, U32 id)
4700c16b537SWarner Losh {
4710c16b537SWarner Losh     /* convention : table[0].pos stores nb of elts */
4720c16b537SWarner Losh     U32 const max = table[0].pos;
4730c16b537SWarner Losh     U32 u;
4740c16b537SWarner Losh     if (!id) return;   /* protection, should never happen */
4750c16b537SWarner Losh     for (u=id; u<max-1; u++)
4760c16b537SWarner Losh         table[u] = table[u+1];
4770c16b537SWarner Losh     table->pos--;
4780c16b537SWarner Losh }
4790c16b537SWarner Losh 
4800c16b537SWarner Losh 
4810c16b537SWarner Losh static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
4820c16b537SWarner Losh {
4830c16b537SWarner Losh     /* merge if possible */
4840c16b537SWarner Losh     U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
4850c16b537SWarner Losh     if (mergeId) {
4860c16b537SWarner Losh         U32 newMerge = 1;
4870c16b537SWarner Losh         while (newMerge) {
4880c16b537SWarner Losh             newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
4890c16b537SWarner Losh             if (newMerge) ZDICT_removeDictItem(table, mergeId);
4900c16b537SWarner Losh             mergeId = newMerge;
4910c16b537SWarner Losh         }
4920c16b537SWarner Losh         return;
4930c16b537SWarner Losh     }
4940c16b537SWarner Losh 
4950c16b537SWarner Losh     /* insert */
4960c16b537SWarner Losh     {   U32 current;
4970c16b537SWarner Losh         U32 nextElt = table->pos;
4980c16b537SWarner Losh         if (nextElt >= maxSize) nextElt = maxSize-1;
4990c16b537SWarner Losh         current = nextElt-1;
5000c16b537SWarner Losh         while (table[current].savings < elt.savings) {
5010c16b537SWarner Losh             table[current+1] = table[current];
5020c16b537SWarner Losh             current--;
5030c16b537SWarner Losh         }
5040c16b537SWarner Losh         table[current+1] = elt;
5050c16b537SWarner Losh         table->pos = nextElt+1;
5060c16b537SWarner Losh     }
5070c16b537SWarner Losh }
5080c16b537SWarner Losh 
5090c16b537SWarner Losh 
5100c16b537SWarner Losh static U32 ZDICT_dictSize(const dictItem* dictList)
5110c16b537SWarner Losh {
5120c16b537SWarner Losh     U32 u, dictSize = 0;
5130c16b537SWarner Losh     for (u=1; u<dictList[0].pos; u++)
5140c16b537SWarner Losh         dictSize += dictList[u].length;
5150c16b537SWarner Losh     return dictSize;
5160c16b537SWarner Losh }
5170c16b537SWarner Losh 
5180c16b537SWarner Losh 
5190c16b537SWarner Losh static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
5200c16b537SWarner Losh                             const void* const buffer, size_t bufferSize,   /* buffer must end with noisy guard band */
5210c16b537SWarner Losh                             const size_t* fileSizes, unsigned nbFiles,
522a0483764SConrad Meyer                             unsigned minRatio, U32 notificationLevel)
5230c16b537SWarner Losh {
5240c16b537SWarner Losh     int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
5250c16b537SWarner Losh     int* const suffix = suffix0+1;
5260c16b537SWarner Losh     U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
5270c16b537SWarner Losh     BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks));   /* +16 for overflow security */
5280c16b537SWarner Losh     U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
5290c16b537SWarner Losh     size_t result = 0;
5300c16b537SWarner Losh     clock_t displayClock = 0;
5310c16b537SWarner Losh     clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
5320c16b537SWarner Losh 
533f7cd7fe5SConrad Meyer #   undef  DISPLAYUPDATE
5340c16b537SWarner Losh #   define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
5350c16b537SWarner Losh             if (ZDICT_clockSpan(displayClock) > refreshRate)  \
5360c16b537SWarner Losh             { displayClock = clock(); DISPLAY(__VA_ARGS__); \
5370c16b537SWarner Losh             if (notificationLevel>=4) fflush(stderr); } }
5380c16b537SWarner Losh 
5390c16b537SWarner Losh     /* init */
5400c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
5410c16b537SWarner Losh     if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
5420c16b537SWarner Losh         result = ERROR(memory_allocation);
5430c16b537SWarner Losh         goto _cleanup;
5440c16b537SWarner Losh     }
5450c16b537SWarner Losh     if (minRatio < MINRATIO) minRatio = MINRATIO;
5460c16b537SWarner Losh     memset(doneMarks, 0, bufferSize+16);
5470c16b537SWarner Losh 
5480c16b537SWarner Losh     /* limit sample set size (divsufsort limitation)*/
549a0483764SConrad Meyer     if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
5500c16b537SWarner Losh     while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
5510c16b537SWarner Losh 
5520c16b537SWarner Losh     /* sort */
553a0483764SConrad Meyer     DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
5540c16b537SWarner Losh     {   int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
5550c16b537SWarner Losh         if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
5560c16b537SWarner Losh     }
5570c16b537SWarner Losh     suffix[bufferSize] = (int)bufferSize;   /* leads into noise */
5580c16b537SWarner Losh     suffix0[0] = (int)bufferSize;           /* leads into noise */
5590c16b537SWarner Losh     /* build reverse suffix sort */
5600c16b537SWarner Losh     {   size_t pos;
5610c16b537SWarner Losh         for (pos=0; pos < bufferSize; pos++)
5620c16b537SWarner Losh             reverseSuffix[suffix[pos]] = (U32)pos;
5630c16b537SWarner Losh         /* note filePos tracks borders between samples.
5640c16b537SWarner Losh            It's not used at this stage, but planned to become useful in a later update */
5650c16b537SWarner Losh         filePos[0] = 0;
5660c16b537SWarner Losh         for (pos=1; pos<nbFiles; pos++)
5670c16b537SWarner Losh             filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
5680c16b537SWarner Losh     }
5690c16b537SWarner Losh 
5700c16b537SWarner Losh     DISPLAYLEVEL(2, "finding patterns ... \n");
5710c16b537SWarner Losh     DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
5720c16b537SWarner Losh 
5730c16b537SWarner Losh     {   U32 cursor; for (cursor=0; cursor < bufferSize; ) {
5740c16b537SWarner Losh             dictItem solution;
5750c16b537SWarner Losh             if (doneMarks[cursor]) { cursor++; continue; }
5760c16b537SWarner Losh             solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
5770c16b537SWarner Losh             if (solution.length==0) { cursor++; continue; }
5780c16b537SWarner Losh             ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
5790c16b537SWarner Losh             cursor += solution.length;
5800c16b537SWarner Losh             DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / bufferSize * 100);
5810c16b537SWarner Losh     }   }
5820c16b537SWarner Losh 
5830c16b537SWarner Losh _cleanup:
5840c16b537SWarner Losh     free(suffix0);
5850c16b537SWarner Losh     free(reverseSuffix);
5860c16b537SWarner Losh     free(doneMarks);
5870c16b537SWarner Losh     free(filePos);
5880c16b537SWarner Losh     return result;
5890c16b537SWarner Losh }
5900c16b537SWarner Losh 
5910c16b537SWarner Losh 
5920c16b537SWarner Losh static void ZDICT_fillNoise(void* buffer, size_t length)
5930c16b537SWarner Losh {
5940c16b537SWarner Losh     unsigned const prime1 = 2654435761U;
5950c16b537SWarner Losh     unsigned const prime2 = 2246822519U;
5960c16b537SWarner Losh     unsigned acc = prime1;
5979cbefe25SConrad Meyer     size_t p=0;
5980c16b537SWarner Losh     for (p=0; p<length; p++) {
5990c16b537SWarner Losh         acc *= prime2;
6000c16b537SWarner Losh         ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
6010c16b537SWarner Losh     }
6020c16b537SWarner Losh }
6030c16b537SWarner Losh 
6040c16b537SWarner Losh 
6050c16b537SWarner Losh typedef struct
6060c16b537SWarner Losh {
6070f743729SConrad Meyer     ZSTD_CDict* dict;    /* dictionary */
60819fcbaf1SConrad Meyer     ZSTD_CCtx* zc;     /* working context */
6090c16b537SWarner Losh     void* workPlace;   /* must be ZSTD_BLOCKSIZE_MAX allocated */
6100c16b537SWarner Losh } EStats_ress_t;
6110c16b537SWarner Losh 
6120c16b537SWarner Losh #define MAXREPOFFSET 1024
6130c16b537SWarner Losh 
61437f1f268SConrad Meyer static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,
615a0483764SConrad Meyer                               unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
61619fcbaf1SConrad Meyer                               const void* src, size_t srcSize,
61719fcbaf1SConrad Meyer                               U32 notificationLevel)
6180c16b537SWarner Losh {
61937f1f268SConrad Meyer     size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
6200c16b537SWarner Losh     size_t cSize;
6210c16b537SWarner Losh 
6220c16b537SWarner Losh     if (srcSize > blockSizeMax) srcSize = blockSizeMax;   /* protection vs large samples */
6230f743729SConrad Meyer     {   size_t const errorCode = ZSTD_compressBegin_usingCDict(esr.zc, esr.dict);
6240f743729SConrad Meyer         if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
6250f743729SConrad Meyer 
6260c16b537SWarner Losh     }
6270c16b537SWarner Losh     cSize = ZSTD_compressBlock(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
628a0483764SConrad Meyer     if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
6290c16b537SWarner Losh 
6300c16b537SWarner Losh     if (cSize) {  /* if == 0; block is not compressible */
63119fcbaf1SConrad Meyer         const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
6320c16b537SWarner Losh 
6330c16b537SWarner Losh         /* literals stats */
6340c16b537SWarner Losh         {   const BYTE* bytePtr;
6350c16b537SWarner Losh             for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
6360c16b537SWarner Losh                 countLit[*bytePtr]++;
6370c16b537SWarner Losh         }
6380c16b537SWarner Losh 
6390c16b537SWarner Losh         /* seqStats */
6400c16b537SWarner Losh         {   U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
6410c16b537SWarner Losh             ZSTD_seqToCodes(seqStorePtr);
6420c16b537SWarner Losh 
6430c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->ofCode;
6440c16b537SWarner Losh                 U32 u;
6450c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
6460c16b537SWarner Losh             }
6470c16b537SWarner Losh 
6480c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->mlCode;
6490c16b537SWarner Losh                 U32 u;
6500c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
6510c16b537SWarner Losh             }
6520c16b537SWarner Losh 
6530c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->llCode;
6540c16b537SWarner Losh                 U32 u;
6550c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
6560c16b537SWarner Losh             }
6570c16b537SWarner Losh 
6580c16b537SWarner Losh             if (nbSeq >= 2) { /* rep offsets */
6590c16b537SWarner Losh                 const seqDef* const seq = seqStorePtr->sequencesStart;
6600c16b537SWarner Losh                 U32 offset1 = seq[0].offset - 3;
6610c16b537SWarner Losh                 U32 offset2 = seq[1].offset - 3;
6620c16b537SWarner Losh                 if (offset1 >= MAXREPOFFSET) offset1 = 0;
6630c16b537SWarner Losh                 if (offset2 >= MAXREPOFFSET) offset2 = 0;
6640c16b537SWarner Losh                 repOffsets[offset1] += 3;
6650c16b537SWarner Losh                 repOffsets[offset2] += 1;
6660c16b537SWarner Losh     }   }   }
6670c16b537SWarner Losh }
6680c16b537SWarner Losh 
6690c16b537SWarner Losh static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
6700c16b537SWarner Losh {
6710c16b537SWarner Losh     size_t total=0;
6720c16b537SWarner Losh     unsigned u;
6730c16b537SWarner Losh     for (u=0; u<nbFiles; u++) total += fileSizes[u];
6740c16b537SWarner Losh     return total;
6750c16b537SWarner Losh }
6760c16b537SWarner Losh 
6770c16b537SWarner Losh typedef struct { U32 offset; U32 count; } offsetCount_t;
6780c16b537SWarner Losh 
6790c16b537SWarner Losh static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
6800c16b537SWarner Losh {
6810c16b537SWarner Losh     U32 u;
6820c16b537SWarner Losh     table[ZSTD_REP_NUM].offset = val;
6830c16b537SWarner Losh     table[ZSTD_REP_NUM].count = count;
6840c16b537SWarner Losh     for (u=ZSTD_REP_NUM; u>0; u--) {
6850c16b537SWarner Losh         offsetCount_t tmp;
6860c16b537SWarner Losh         if (table[u-1].count >= table[u].count) break;
6870c16b537SWarner Losh         tmp = table[u-1];
6880c16b537SWarner Losh         table[u-1] = table[u];
6890c16b537SWarner Losh         table[u] = tmp;
6900c16b537SWarner Losh     }
6910c16b537SWarner Losh }
6920c16b537SWarner Losh 
69319fcbaf1SConrad Meyer /* ZDICT_flatLit() :
69419fcbaf1SConrad Meyer  * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
69519fcbaf1SConrad Meyer  * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
69619fcbaf1SConrad Meyer  */
697a0483764SConrad Meyer static void ZDICT_flatLit(unsigned* countLit)
69819fcbaf1SConrad Meyer {
69919fcbaf1SConrad Meyer     int u;
70019fcbaf1SConrad Meyer     for (u=1; u<256; u++) countLit[u] = 2;
70119fcbaf1SConrad Meyer     countLit[0]   = 4;
70219fcbaf1SConrad Meyer     countLit[253] = 1;
70319fcbaf1SConrad Meyer     countLit[254] = 1;
70419fcbaf1SConrad Meyer }
7050c16b537SWarner Losh 
7060c16b537SWarner Losh #define OFFCODE_MAX 30  /* only applicable to first block */
7070c16b537SWarner Losh static size_t ZDICT_analyzeEntropy(void*  dstBuffer, size_t maxDstSize,
708f7cd7fe5SConrad Meyer                                    int compressionLevel,
7090c16b537SWarner Losh                              const void*  srcBuffer, const size_t* fileSizes, unsigned nbFiles,
7100c16b537SWarner Losh                              const void* dictBuffer, size_t  dictBufferSize,
7110c16b537SWarner Losh                                    unsigned notificationLevel)
7120c16b537SWarner Losh {
713a0483764SConrad Meyer     unsigned countLit[256];
7140c16b537SWarner Losh     HUF_CREATE_STATIC_CTABLE(hufTable, 255);
715a0483764SConrad Meyer     unsigned offcodeCount[OFFCODE_MAX+1];
7160c16b537SWarner Losh     short offcodeNCount[OFFCODE_MAX+1];
7170c16b537SWarner Losh     U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
718a0483764SConrad Meyer     unsigned matchLengthCount[MaxML+1];
7190c16b537SWarner Losh     short matchLengthNCount[MaxML+1];
720a0483764SConrad Meyer     unsigned litLengthCount[MaxLL+1];
7210c16b537SWarner Losh     short litLengthNCount[MaxLL+1];
7220c16b537SWarner Losh     U32 repOffset[MAXREPOFFSET];
7230c16b537SWarner Losh     offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
7240f743729SConrad Meyer     EStats_ress_t esr = { NULL, NULL, NULL };
7250c16b537SWarner Losh     ZSTD_parameters params;
7260c16b537SWarner Losh     U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
7270c16b537SWarner Losh     size_t pos = 0, errorCode;
7280c16b537SWarner Losh     size_t eSize = 0;
7290c16b537SWarner Losh     size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
7300c16b537SWarner Losh     size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
7310c16b537SWarner Losh     BYTE* dstPtr = (BYTE*)dstBuffer;
7320c16b537SWarner Losh 
7330c16b537SWarner Losh     /* init */
73419fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_analyzeEntropy");
7350c16b537SWarner Losh     if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; }   /* too large dictionary */
7360c16b537SWarner Losh     for (u=0; u<256; u++) countLit[u] = 1;   /* any character must be described */
7370c16b537SWarner Losh     for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
7380c16b537SWarner Losh     for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
7390c16b537SWarner Losh     for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
7400c16b537SWarner Losh     memset(repOffset, 0, sizeof(repOffset));
7410c16b537SWarner Losh     repOffset[1] = repOffset[4] = repOffset[8] = 1;
7420c16b537SWarner Losh     memset(bestRepOffset, 0, sizeof(bestRepOffset));
743f7cd7fe5SConrad Meyer     if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;
7440c16b537SWarner Losh     params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
7450f743729SConrad Meyer 
7460f743729SConrad Meyer     esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
7470f743729SConrad Meyer     esr.zc = ZSTD_createCCtx();
7480f743729SConrad Meyer     esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
7490f743729SConrad Meyer     if (!esr.dict || !esr.zc || !esr.workPlace) {
7500f743729SConrad Meyer         eSize = ERROR(memory_allocation);
7510f743729SConrad Meyer         DISPLAYLEVEL(1, "Not enough memory \n");
7520c16b537SWarner Losh         goto _cleanup;
7530f743729SConrad Meyer     }
7540c16b537SWarner Losh 
75519fcbaf1SConrad Meyer     /* collect stats on all samples */
7560c16b537SWarner Losh     for (u=0; u<nbFiles; u++) {
75737f1f268SConrad Meyer         ZDICT_countEStats(esr, &params,
7580c16b537SWarner Losh                           countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
7590c16b537SWarner Losh                          (const char*)srcBuffer + pos, fileSizes[u],
7600c16b537SWarner Losh                           notificationLevel);
7610c16b537SWarner Losh         pos += fileSizes[u];
7620c16b537SWarner Losh     }
7630c16b537SWarner Losh 
76419fcbaf1SConrad Meyer     /* analyze, build stats, starting with literals */
76519fcbaf1SConrad Meyer     {   size_t maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
76619fcbaf1SConrad Meyer         if (HUF_isError(maxNbBits)) {
7674d3f1eafSConrad Meyer             eSize = maxNbBits;
7680c16b537SWarner Losh             DISPLAYLEVEL(1, " HUF_buildCTable error \n");
7690c16b537SWarner Losh             goto _cleanup;
7700c16b537SWarner Losh         }
77119fcbaf1SConrad Meyer         if (maxNbBits==8) {  /* not compressible : will fail on HUF_writeCTable() */
77219fcbaf1SConrad Meyer             DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
77319fcbaf1SConrad Meyer             ZDICT_flatLit(countLit);  /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
77419fcbaf1SConrad Meyer             maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
77519fcbaf1SConrad Meyer             assert(maxNbBits==9);
77619fcbaf1SConrad Meyer         }
77719fcbaf1SConrad Meyer         huffLog = (U32)maxNbBits;
77819fcbaf1SConrad Meyer     }
7790c16b537SWarner Losh 
7800c16b537SWarner Losh     /* looking for most common first offsets */
7810c16b537SWarner Losh     {   U32 offset;
7820c16b537SWarner Losh         for (offset=1; offset<MAXREPOFFSET; offset++)
7830c16b537SWarner Losh             ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
7840c16b537SWarner Losh     }
7850c16b537SWarner Losh     /* note : the result of this phase should be used to better appreciate the impact on statistics */
7860c16b537SWarner Losh 
7870c16b537SWarner Losh     total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
788f7cd7fe5SConrad Meyer     errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);
7890c16b537SWarner Losh     if (FSE_isError(errorCode)) {
7904d3f1eafSConrad Meyer         eSize = errorCode;
7910c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
7920c16b537SWarner Losh         goto _cleanup;
7930c16b537SWarner Losh     }
7940c16b537SWarner Losh     Offlog = (U32)errorCode;
7950c16b537SWarner Losh 
7960c16b537SWarner Losh     total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
797f7cd7fe5SConrad Meyer     errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);
7980c16b537SWarner Losh     if (FSE_isError(errorCode)) {
7994d3f1eafSConrad Meyer         eSize = errorCode;
8000c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
8010c16b537SWarner Losh         goto _cleanup;
8020c16b537SWarner Losh     }
8030c16b537SWarner Losh     mlLog = (U32)errorCode;
8040c16b537SWarner Losh 
8050c16b537SWarner Losh     total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
806f7cd7fe5SConrad Meyer     errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);
8070c16b537SWarner Losh     if (FSE_isError(errorCode)) {
8084d3f1eafSConrad Meyer         eSize = errorCode;
8090c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
8100c16b537SWarner Losh         goto _cleanup;
8110c16b537SWarner Losh     }
8120c16b537SWarner Losh     llLog = (U32)errorCode;
8130c16b537SWarner Losh 
8140c16b537SWarner Losh     /* write result to buffer */
8150c16b537SWarner Losh     {   size_t const hhSize = HUF_writeCTable(dstPtr, maxDstSize, hufTable, 255, huffLog);
8160c16b537SWarner Losh         if (HUF_isError(hhSize)) {
8174d3f1eafSConrad Meyer             eSize = hhSize;
8180c16b537SWarner Losh             DISPLAYLEVEL(1, "HUF_writeCTable error \n");
8190c16b537SWarner Losh             goto _cleanup;
8200c16b537SWarner Losh         }
8210c16b537SWarner Losh         dstPtr += hhSize;
8220c16b537SWarner Losh         maxDstSize -= hhSize;
8230c16b537SWarner Losh         eSize += hhSize;
8240c16b537SWarner Losh     }
8250c16b537SWarner Losh 
8260c16b537SWarner Losh     {   size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
8270c16b537SWarner Losh         if (FSE_isError(ohSize)) {
8284d3f1eafSConrad Meyer             eSize = ohSize;
8290c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
8300c16b537SWarner Losh             goto _cleanup;
8310c16b537SWarner Losh         }
8320c16b537SWarner Losh         dstPtr += ohSize;
8330c16b537SWarner Losh         maxDstSize -= ohSize;
8340c16b537SWarner Losh         eSize += ohSize;
8350c16b537SWarner Losh     }
8360c16b537SWarner Losh 
8370c16b537SWarner Losh     {   size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
8380c16b537SWarner Losh         if (FSE_isError(mhSize)) {
8394d3f1eafSConrad Meyer             eSize = mhSize;
8400c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
8410c16b537SWarner Losh             goto _cleanup;
8420c16b537SWarner Losh         }
8430c16b537SWarner Losh         dstPtr += mhSize;
8440c16b537SWarner Losh         maxDstSize -= mhSize;
8450c16b537SWarner Losh         eSize += mhSize;
8460c16b537SWarner Losh     }
8470c16b537SWarner Losh 
8480c16b537SWarner Losh     {   size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
8490c16b537SWarner Losh         if (FSE_isError(lhSize)) {
8504d3f1eafSConrad Meyer             eSize = lhSize;
8510c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
8520c16b537SWarner Losh             goto _cleanup;
8530c16b537SWarner Losh         }
8540c16b537SWarner Losh         dstPtr += lhSize;
8550c16b537SWarner Losh         maxDstSize -= lhSize;
8560c16b537SWarner Losh         eSize += lhSize;
8570c16b537SWarner Losh     }
8580c16b537SWarner Losh 
8590c16b537SWarner Losh     if (maxDstSize<12) {
8604d3f1eafSConrad Meyer         eSize = ERROR(dstSize_tooSmall);
8610c16b537SWarner Losh         DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
8620c16b537SWarner Losh         goto _cleanup;
8630c16b537SWarner Losh     }
8640c16b537SWarner Losh # if 0
8650c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
8660c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
8670c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
8680c16b537SWarner Losh #else
8690c16b537SWarner Losh     /* at this stage, we don't use the result of "most common first offset",
8700c16b537SWarner Losh        as the impact of statistics is not properly evaluated */
8710c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, repStartValue[0]);
8720c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, repStartValue[1]);
8730c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, repStartValue[2]);
8740c16b537SWarner Losh #endif
8750c16b537SWarner Losh     eSize += 12;
8760c16b537SWarner Losh 
8770c16b537SWarner Losh _cleanup:
8780f743729SConrad Meyer     ZSTD_freeCDict(esr.dict);
8790c16b537SWarner Losh     ZSTD_freeCCtx(esr.zc);
8800c16b537SWarner Losh     free(esr.workPlace);
8810c16b537SWarner Losh 
8820c16b537SWarner Losh     return eSize;
8830c16b537SWarner Losh }
8840c16b537SWarner Losh 
8850c16b537SWarner Losh 
8860c16b537SWarner Losh 
8870c16b537SWarner Losh size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
8880c16b537SWarner Losh                           const void* customDictContent, size_t dictContentSize,
8890f743729SConrad Meyer                           const void* samplesBuffer, const size_t* samplesSizes,
8900f743729SConrad Meyer                           unsigned nbSamples, ZDICT_params_t params)
8910c16b537SWarner Losh {
8920c16b537SWarner Losh     size_t hSize;
8930c16b537SWarner Losh #define HBUFFSIZE 256   /* should prove large enough for all entropy headers */
8940c16b537SWarner Losh     BYTE header[HBUFFSIZE];
895f7cd7fe5SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
8960c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
8970c16b537SWarner Losh 
8980c16b537SWarner Losh     /* check conditions */
89919fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_finalizeDictionary");
9000c16b537SWarner Losh     if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
9010c16b537SWarner Losh     if (dictContentSize < ZDICT_CONTENTSIZE_MIN) return ERROR(srcSize_wrong);
9020c16b537SWarner Losh     if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
9030c16b537SWarner Losh 
9040c16b537SWarner Losh     /* dictionary header */
9050c16b537SWarner Losh     MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
9060c16b537SWarner Losh     {   U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
9070c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
9080c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
9090c16b537SWarner Losh         MEM_writeLE32(header+4, dictID);
9100c16b537SWarner Losh     }
9110c16b537SWarner Losh     hSize = 8;
9120c16b537SWarner Losh 
9130c16b537SWarner Losh     /* entropy tables */
9140c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
9150c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
9160c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
9170c16b537SWarner Losh                                   compressionLevel,
9180c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
9190c16b537SWarner Losh                                   customDictContent, dictContentSize,
9200c16b537SWarner Losh                                   notificationLevel);
9210c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
9220c16b537SWarner Losh         hSize += eSize;
9230c16b537SWarner Losh     }
9240c16b537SWarner Losh 
9250c16b537SWarner Losh     /* copy elements in final buffer ; note : src and dst buffer can overlap */
9260c16b537SWarner Losh     if (hSize + dictContentSize > dictBufferCapacity) dictContentSize = dictBufferCapacity - hSize;
9270c16b537SWarner Losh     {   size_t const dictSize = hSize + dictContentSize;
9280c16b537SWarner Losh         char* dictEnd = (char*)dictBuffer + dictSize;
9290c16b537SWarner Losh         memmove(dictEnd - dictContentSize, customDictContent, dictContentSize);
9300c16b537SWarner Losh         memcpy(dictBuffer, header, hSize);
9310c16b537SWarner Losh         return dictSize;
9320c16b537SWarner Losh     }
9330c16b537SWarner Losh }
9340c16b537SWarner Losh 
9350c16b537SWarner Losh 
9360f743729SConrad Meyer static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
9370f743729SConrad Meyer         void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
9380c16b537SWarner Losh         const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9390c16b537SWarner Losh         ZDICT_params_t params)
9400c16b537SWarner Losh {
941f7cd7fe5SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
9420c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
9430c16b537SWarner Losh     size_t hSize = 8;
9440c16b537SWarner Losh 
9450c16b537SWarner Losh     /* calculate entropy tables */
9460c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
9470c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
9480c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
9490c16b537SWarner Losh                                   compressionLevel,
9500c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
9510c16b537SWarner Losh                                   (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
9520c16b537SWarner Losh                                   notificationLevel);
9530c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
9540c16b537SWarner Losh         hSize += eSize;
9550c16b537SWarner Losh     }
9560c16b537SWarner Losh 
9570c16b537SWarner Losh     /* add dictionary header (after entropy tables) */
9580c16b537SWarner Losh     MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
9590c16b537SWarner Losh     {   U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
9600c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
9610c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
9620c16b537SWarner Losh         MEM_writeLE32((char*)dictBuffer+4, dictID);
9630c16b537SWarner Losh     }
9640c16b537SWarner Losh 
9650c16b537SWarner Losh     if (hSize + dictContentSize < dictBufferCapacity)
9660c16b537SWarner Losh         memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
9670c16b537SWarner Losh     return MIN(dictBufferCapacity, hSize+dictContentSize);
9680c16b537SWarner Losh }
9690c16b537SWarner Losh 
9700f743729SConrad Meyer /* Hidden declaration for dbio.c */
971*98689d0fSConrad Meyer /* Begin FreeBSD - This symbol is needed by dll-linked CLI zstd(1). */
972*98689d0fSConrad Meyer ZSTDLIB_API
973*98689d0fSConrad Meyer /* End FreeBSD */
9740f743729SConrad Meyer size_t ZDICT_trainFromBuffer_unsafe_legacy(
9750f743729SConrad Meyer                             void* dictBuffer, size_t maxDictSize,
9760f743729SConrad Meyer                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9770f743729SConrad Meyer                             ZDICT_legacy_params_t params);
9780c16b537SWarner Losh /*! ZDICT_trainFromBuffer_unsafe_legacy() :
9790c16b537SWarner Losh *   Warning : `samplesBuffer` must be followed by noisy guard band.
9800c16b537SWarner Losh *   @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
9810c16b537SWarner Losh */
9820c16b537SWarner Losh size_t ZDICT_trainFromBuffer_unsafe_legacy(
9830c16b537SWarner Losh                             void* dictBuffer, size_t maxDictSize,
9840c16b537SWarner Losh                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9850c16b537SWarner Losh                             ZDICT_legacy_params_t params)
9860c16b537SWarner Losh {
9870c16b537SWarner Losh     U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
9880c16b537SWarner Losh     dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
9890c16b537SWarner Losh     unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
9900c16b537SWarner Losh     unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
9910c16b537SWarner Losh     size_t const targetDictSize = maxDictSize;
9920c16b537SWarner Losh     size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
9930c16b537SWarner Losh     size_t dictSize = 0;
9940c16b537SWarner Losh     U32 const notificationLevel = params.zParams.notificationLevel;
9950c16b537SWarner Losh 
9960c16b537SWarner Losh     /* checks */
9970c16b537SWarner Losh     if (!dictList) return ERROR(memory_allocation);
9980c16b537SWarner Losh     if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); }   /* requested dictionary size is too small */
9990c16b537SWarner Losh     if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* not enough source to create dictionary */
10000c16b537SWarner Losh 
10010c16b537SWarner Losh     /* init */
10020c16b537SWarner Losh     ZDICT_initDictItem(dictList);
10030c16b537SWarner Losh 
10040c16b537SWarner Losh     /* build dictionary */
10050c16b537SWarner Losh     ZDICT_trainBuffer_legacy(dictList, dictListSize,
10060c16b537SWarner Losh                        samplesBuffer, samplesBuffSize,
10070c16b537SWarner Losh                        samplesSizes, nbSamples,
10080c16b537SWarner Losh                        minRep, notificationLevel);
10090c16b537SWarner Losh 
10100c16b537SWarner Losh     /* display best matches */
10110c16b537SWarner Losh     if (params.zParams.notificationLevel>= 3) {
1012a0483764SConrad Meyer         unsigned const nb = MIN(25, dictList[0].pos);
1013a0483764SConrad Meyer         unsigned const dictContentSize = ZDICT_dictSize(dictList);
1014a0483764SConrad Meyer         unsigned u;
1015a0483764SConrad Meyer         DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
10160c16b537SWarner Losh         DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
10170c16b537SWarner Losh         for (u=1; u<nb; u++) {
1018a0483764SConrad Meyer             unsigned const pos = dictList[u].pos;
1019a0483764SConrad Meyer             unsigned const length = dictList[u].length;
10200c16b537SWarner Losh             U32 const printedLength = MIN(40, length);
10210f743729SConrad Meyer             if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
10220f743729SConrad Meyer                 free(dictList);
10230c16b537SWarner Losh                 return ERROR(GENERIC);   /* should never happen */
10240f743729SConrad Meyer             }
10250c16b537SWarner Losh             DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
1026a0483764SConrad Meyer                          u, length, pos, (unsigned)dictList[u].savings);
10270c16b537SWarner Losh             ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
10280c16b537SWarner Losh             DISPLAYLEVEL(3, "| \n");
10290c16b537SWarner Losh     }   }
10300c16b537SWarner Losh 
10310c16b537SWarner Losh 
10320c16b537SWarner Losh     /* create dictionary */
1033a0483764SConrad Meyer     {   unsigned dictContentSize = ZDICT_dictSize(dictList);
10340c16b537SWarner Losh         if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* dictionary content too small */
10350c16b537SWarner Losh         if (dictContentSize < targetDictSize/4) {
1036a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
10370c16b537SWarner Losh             if (samplesBuffSize < 10 * targetDictSize)
1038a0483764SConrad Meyer                 DISPLAYLEVEL(2, "!  consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
10390c16b537SWarner Losh             if (minRep > MINRATIO) {
10400c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
10410c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
10420c16b537SWarner Losh             }
10430c16b537SWarner Losh         }
10440c16b537SWarner Losh 
10450c16b537SWarner Losh         if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
1046a0483764SConrad Meyer             unsigned proposedSelectivity = selectivity-1;
10470c16b537SWarner Losh             while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
1048a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
10490c16b537SWarner Losh             DISPLAYLEVEL(2, "!  consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
10500c16b537SWarner Losh             DISPLAYLEVEL(2, "!  always test dictionary efficiency on real samples \n");
10510c16b537SWarner Losh         }
10520c16b537SWarner Losh 
10530c16b537SWarner Losh         /* limit dictionary size */
10540c16b537SWarner Losh         {   U32 const max = dictList->pos;   /* convention : nb of useful elts within dictList */
10550c16b537SWarner Losh             U32 currentSize = 0;
10560c16b537SWarner Losh             U32 n; for (n=1; n<max; n++) {
10570c16b537SWarner Losh                 currentSize += dictList[n].length;
10580c16b537SWarner Losh                 if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
10590c16b537SWarner Losh             }
10600c16b537SWarner Losh             dictList->pos = n;
10610c16b537SWarner Losh             dictContentSize = currentSize;
10620c16b537SWarner Losh         }
10630c16b537SWarner Losh 
10640c16b537SWarner Losh         /* build dict content */
10650c16b537SWarner Losh         {   U32 u;
10660c16b537SWarner Losh             BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
10670c16b537SWarner Losh             for (u=1; u<dictList->pos; u++) {
10680c16b537SWarner Losh                 U32 l = dictList[u].length;
10690c16b537SWarner Losh                 ptr -= l;
10700c16b537SWarner Losh                 if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); }   /* should not happen */
10710c16b537SWarner Losh                 memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
10720c16b537SWarner Losh         }   }
10730c16b537SWarner Losh 
10740c16b537SWarner Losh         dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
10750c16b537SWarner Losh                                                              samplesBuffer, samplesSizes, nbSamples,
10760c16b537SWarner Losh                                                              params.zParams);
10770c16b537SWarner Losh     }
10780c16b537SWarner Losh 
10790c16b537SWarner Losh     /* clean up */
10800c16b537SWarner Losh     free(dictList);
10810c16b537SWarner Losh     return dictSize;
10820c16b537SWarner Losh }
10830c16b537SWarner Losh 
10840c16b537SWarner Losh 
108519fcbaf1SConrad Meyer /* ZDICT_trainFromBuffer_legacy() :
108619fcbaf1SConrad Meyer  * issue : samplesBuffer need to be followed by a noisy guard band.
10870c16b537SWarner Losh  * work around : duplicate the buffer, and add the noise */
10880c16b537SWarner Losh size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
10890c16b537SWarner Losh                               const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
10900c16b537SWarner Losh                               ZDICT_legacy_params_t params)
10910c16b537SWarner Losh {
10920c16b537SWarner Losh     size_t result;
10930c16b537SWarner Losh     void* newBuff;
10940c16b537SWarner Losh     size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
10950c16b537SWarner Losh     if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0;   /* not enough content => no dictionary */
10960c16b537SWarner Losh 
10970c16b537SWarner Losh     newBuff = malloc(sBuffSize + NOISELENGTH);
10980c16b537SWarner Losh     if (!newBuff) return ERROR(memory_allocation);
10990c16b537SWarner Losh 
11000c16b537SWarner Losh     memcpy(newBuff, samplesBuffer, sBuffSize);
11010c16b537SWarner Losh     ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH);   /* guard band, for end of buffer condition */
11020c16b537SWarner Losh 
11030c16b537SWarner Losh     result =
11040c16b537SWarner Losh         ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
11050c16b537SWarner Losh                                             samplesSizes, nbSamples, params);
11060c16b537SWarner Losh     free(newBuff);
11070c16b537SWarner Losh     return result;
11080c16b537SWarner Losh }
11090c16b537SWarner Losh 
11100c16b537SWarner Losh 
11110c16b537SWarner Losh size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
11120c16b537SWarner Losh                              const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
11130c16b537SWarner Losh {
11140f743729SConrad Meyer     ZDICT_fastCover_params_t params;
111519fcbaf1SConrad Meyer     DEBUGLOG(3, "ZDICT_trainFromBuffer");
11160c16b537SWarner Losh     memset(&params, 0, sizeof(params));
11170c16b537SWarner Losh     params.d = 8;
11180c16b537SWarner Losh     params.steps = 4;
1119f7cd7fe5SConrad Meyer     /* Use default level since no compression level information is available */
1120f7cd7fe5SConrad Meyer     params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
11210f743729SConrad Meyer #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
11220f743729SConrad Meyer     params.zParams.notificationLevel = DEBUGLEVEL;
112319fcbaf1SConrad Meyer #endif
11240f743729SConrad Meyer     return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
112519fcbaf1SConrad Meyer                                                samplesBuffer, samplesSizes, nbSamples,
112619fcbaf1SConrad Meyer                                                &params);
11270c16b537SWarner Losh }
11280c16b537SWarner Losh 
11290c16b537SWarner Losh size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
11300c16b537SWarner Losh                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
11310c16b537SWarner Losh {
11320c16b537SWarner Losh     ZDICT_params_t params;
11330c16b537SWarner Losh     memset(&params, 0, sizeof(params));
11340c16b537SWarner Losh     return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
11350c16b537SWarner Losh                                                      samplesBuffer, samplesSizes, nbSamples,
11360c16b537SWarner Losh                                                      params);
11370c16b537SWarner Losh }
1138