xref: /freebsd/sys/contrib/zstd/lib/dictBuilder/zdict.c (revision a0483764f3d68669e9b7db074bcbd45b050166bb)
10c16b537SWarner Losh /*
20c16b537SWarner Losh  * Copyright (c) 2016-present, 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 
400c16b537SWarner Losh #include "mem.h"           /* read */
410c16b537SWarner Losh #include "fse.h"           /* FSE_normalizeCount, FSE_writeNCount */
420c16b537SWarner Losh #define HUF_STATIC_LINKING_ONLY
430c16b537SWarner Losh #include "huf.h"           /* HUF_buildCTable, HUF_writeCTable */
440c16b537SWarner Losh #include "zstd_internal.h" /* includes zstd.h */
450c16b537SWarner Losh #include "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"
510c16b537SWarner Losh 
520c16b537SWarner Losh 
530c16b537SWarner Losh /*-*************************************
540c16b537SWarner Losh *  Constants
550c16b537SWarner Losh ***************************************/
560c16b537SWarner Losh #define KB *(1 <<10)
570c16b537SWarner Losh #define MB *(1 <<20)
580c16b537SWarner Losh #define GB *(1U<<30)
590c16b537SWarner Losh 
600c16b537SWarner Losh #define DICTLISTSIZE_DEFAULT 10000
610c16b537SWarner Losh 
620c16b537SWarner Losh #define NOISELENGTH 32
630c16b537SWarner Losh 
640c16b537SWarner Losh static const int g_compressionLevel_default = 3;
650c16b537SWarner Losh static const U32 g_selectivity_default = 9;
660c16b537SWarner Losh 
670c16b537SWarner Losh 
680c16b537SWarner Losh /*-*************************************
690c16b537SWarner Losh *  Console display
700c16b537SWarner Losh ***************************************/
710c16b537SWarner Losh #define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
720c16b537SWarner Losh #define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); }    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
730c16b537SWarner Losh 
740c16b537SWarner Losh static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
750c16b537SWarner Losh 
760c16b537SWarner Losh static void ZDICT_printHex(const void* ptr, size_t length)
770c16b537SWarner Losh {
780c16b537SWarner Losh     const BYTE* const b = (const BYTE*)ptr;
790c16b537SWarner Losh     size_t u;
800c16b537SWarner Losh     for (u=0; u<length; u++) {
810c16b537SWarner Losh         BYTE c = b[u];
820c16b537SWarner Losh         if (c<32 || c>126) c = '.';   /* non-printable char */
830c16b537SWarner Losh         DISPLAY("%c", c);
840c16b537SWarner Losh     }
850c16b537SWarner Losh }
860c16b537SWarner Losh 
870c16b537SWarner Losh 
880c16b537SWarner Losh /*-********************************************************
890c16b537SWarner Losh *  Helper functions
900c16b537SWarner Losh **********************************************************/
910c16b537SWarner Losh unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
920c16b537SWarner Losh 
930c16b537SWarner Losh const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
940c16b537SWarner Losh 
950c16b537SWarner Losh unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
960c16b537SWarner Losh {
970c16b537SWarner Losh     if (dictSize < 8) return 0;
980c16b537SWarner Losh     if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
990c16b537SWarner Losh     return MEM_readLE32((const char*)dictBuffer + 4);
1000c16b537SWarner Losh }
1010c16b537SWarner Losh 
1020c16b537SWarner Losh 
1030c16b537SWarner Losh /*-********************************************************
1040c16b537SWarner Losh *  Dictionary training functions
1050c16b537SWarner Losh **********************************************************/
106052d3c12SConrad Meyer static unsigned ZDICT_NbCommonBytes (size_t val)
1070c16b537SWarner Losh {
1080c16b537SWarner Losh     if (MEM_isLittleEndian()) {
1090c16b537SWarner Losh         if (MEM_64bits()) {
1100c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
1110c16b537SWarner Losh             unsigned long r = 0;
1120c16b537SWarner Losh             _BitScanForward64( &r, (U64)val );
1130c16b537SWarner Losh             return (unsigned)(r>>3);
1140c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1150c16b537SWarner Losh             return (__builtin_ctzll((U64)val) >> 3);
1160c16b537SWarner Losh #       else
1170c16b537SWarner 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 };
1180c16b537SWarner Losh             return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
1190c16b537SWarner Losh #       endif
1200c16b537SWarner Losh         } else { /* 32 bits */
1210c16b537SWarner Losh #       if defined(_MSC_VER)
1220c16b537SWarner Losh             unsigned long r=0;
1230c16b537SWarner Losh             _BitScanForward( &r, (U32)val );
1240c16b537SWarner Losh             return (unsigned)(r>>3);
1250c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1260c16b537SWarner Losh             return (__builtin_ctz((U32)val) >> 3);
1270c16b537SWarner Losh #       else
1280c16b537SWarner 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 };
1290c16b537SWarner Losh             return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
1300c16b537SWarner Losh #       endif
1310c16b537SWarner Losh         }
1320c16b537SWarner Losh     } else {  /* Big Endian CPU */
1330c16b537SWarner Losh         if (MEM_64bits()) {
1340c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
1350c16b537SWarner Losh             unsigned long r = 0;
1360c16b537SWarner Losh             _BitScanReverse64( &r, val );
1370c16b537SWarner Losh             return (unsigned)(r>>3);
1380c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1390c16b537SWarner Losh             return (__builtin_clzll(val) >> 3);
1400c16b537SWarner Losh #       else
1410c16b537SWarner Losh             unsigned r;
1420c16b537SWarner Losh             const unsigned n32 = sizeof(size_t)*4;   /* calculate this way due to compiler complaining in 32-bits mode */
1430c16b537SWarner Losh             if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
1440c16b537SWarner Losh             if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
1450c16b537SWarner Losh             r += (!val);
1460c16b537SWarner Losh             return r;
1470c16b537SWarner Losh #       endif
1480c16b537SWarner Losh         } else { /* 32 bits */
1490c16b537SWarner Losh #       if defined(_MSC_VER)
1500c16b537SWarner Losh             unsigned long r = 0;
1510c16b537SWarner Losh             _BitScanReverse( &r, (unsigned long)val );
1520c16b537SWarner Losh             return (unsigned)(r>>3);
1530c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1540c16b537SWarner Losh             return (__builtin_clz((U32)val) >> 3);
1550c16b537SWarner Losh #       else
1560c16b537SWarner Losh             unsigned r;
1570c16b537SWarner Losh             if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
1580c16b537SWarner Losh             r += (!val);
1590c16b537SWarner Losh             return r;
1600c16b537SWarner Losh #       endif
1610c16b537SWarner Losh     }   }
1620c16b537SWarner Losh }
1630c16b537SWarner Losh 
1640c16b537SWarner Losh 
1650c16b537SWarner Losh /*! ZDICT_count() :
1660c16b537SWarner Losh     Count the nb of common bytes between 2 pointers.
1670c16b537SWarner Losh     Note : this function presumes end of buffer followed by noisy guard band.
1680c16b537SWarner Losh */
1690c16b537SWarner Losh static size_t ZDICT_count(const void* pIn, const void* pMatch)
1700c16b537SWarner Losh {
1710c16b537SWarner Losh     const char* const pStart = (const char*)pIn;
1720c16b537SWarner Losh     for (;;) {
1730c16b537SWarner Losh         size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
1740c16b537SWarner Losh         if (!diff) {
1750c16b537SWarner Losh             pIn = (const char*)pIn+sizeof(size_t);
1760c16b537SWarner Losh             pMatch = (const char*)pMatch+sizeof(size_t);
1770c16b537SWarner Losh             continue;
1780c16b537SWarner Losh         }
1790c16b537SWarner Losh         pIn = (const char*)pIn+ZDICT_NbCommonBytes(diff);
1800c16b537SWarner Losh         return (size_t)((const char*)pIn - pStart);
1810c16b537SWarner Losh     }
1820c16b537SWarner Losh }
1830c16b537SWarner Losh 
1840c16b537SWarner Losh 
1850c16b537SWarner Losh typedef struct {
1860c16b537SWarner Losh     U32 pos;
1870c16b537SWarner Losh     U32 length;
1880c16b537SWarner Losh     U32 savings;
1890c16b537SWarner Losh } dictItem;
1900c16b537SWarner Losh 
1910c16b537SWarner Losh static void ZDICT_initDictItem(dictItem* d)
1920c16b537SWarner Losh {
1930c16b537SWarner Losh     d->pos = 1;
1940c16b537SWarner Losh     d->length = 0;
1950c16b537SWarner Losh     d->savings = (U32)(-1);
1960c16b537SWarner Losh }
1970c16b537SWarner Losh 
1980c16b537SWarner Losh 
1990c16b537SWarner Losh #define LLIMIT 64          /* heuristic determined experimentally */
2000c16b537SWarner Losh #define MINMATCHLENGTH 7   /* heuristic determined experimentally */
2010c16b537SWarner Losh static dictItem ZDICT_analyzePos(
2020c16b537SWarner Losh                        BYTE* doneMarks,
2030c16b537SWarner Losh                        const int* suffix, U32 start,
2040c16b537SWarner Losh                        const void* buffer, U32 minRatio, U32 notificationLevel)
2050c16b537SWarner Losh {
2060c16b537SWarner Losh     U32 lengthList[LLIMIT] = {0};
2070c16b537SWarner Losh     U32 cumulLength[LLIMIT] = {0};
2080c16b537SWarner Losh     U32 savings[LLIMIT] = {0};
2090c16b537SWarner Losh     const BYTE* b = (const BYTE*)buffer;
2100c16b537SWarner Losh     size_t maxLength = LLIMIT;
2110c16b537SWarner Losh     size_t pos = suffix[start];
2120c16b537SWarner Losh     U32 end = start;
2130c16b537SWarner Losh     dictItem solution;
2140c16b537SWarner Losh 
2150c16b537SWarner Losh     /* init */
2160c16b537SWarner Losh     memset(&solution, 0, sizeof(solution));
2170c16b537SWarner Losh     doneMarks[pos] = 1;
2180c16b537SWarner Losh 
2190c16b537SWarner Losh     /* trivial repetition cases */
2200c16b537SWarner Losh     if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
2210c16b537SWarner Losh        ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
2220c16b537SWarner Losh        ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
2230c16b537SWarner Losh         /* skip and mark segment */
22419fcbaf1SConrad Meyer         U16 const pattern16 = MEM_read16(b+pos+4);
22519fcbaf1SConrad Meyer         U32 u, patternEnd = 6;
22619fcbaf1SConrad Meyer         while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
22719fcbaf1SConrad Meyer         if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
22819fcbaf1SConrad Meyer         for (u=1; u<patternEnd; u++)
2290c16b537SWarner Losh             doneMarks[pos+u] = 1;
2300c16b537SWarner Losh         return solution;
2310c16b537SWarner Losh     }
2320c16b537SWarner Losh 
2330c16b537SWarner Losh     /* look forward */
23419fcbaf1SConrad Meyer     {   size_t length;
2350c16b537SWarner Losh         do {
2360c16b537SWarner Losh             end++;
2370c16b537SWarner Losh             length = ZDICT_count(b + pos, b + suffix[end]);
2380c16b537SWarner Losh         } while (length >= MINMATCHLENGTH);
23919fcbaf1SConrad Meyer     }
2400c16b537SWarner Losh 
2410c16b537SWarner Losh     /* look backward */
24219fcbaf1SConrad Meyer     {   size_t length;
2430c16b537SWarner Losh         do {
2440c16b537SWarner Losh             length = ZDICT_count(b + pos, b + *(suffix+start-1));
2450c16b537SWarner Losh             if (length >=MINMATCHLENGTH) start--;
2460c16b537SWarner Losh         } while(length >= MINMATCHLENGTH);
24719fcbaf1SConrad Meyer     }
2480c16b537SWarner Losh 
2490c16b537SWarner Losh     /* exit if not found a minimum nb of repetitions */
2500c16b537SWarner Losh     if (end-start < minRatio) {
2510c16b537SWarner Losh         U32 idx;
2520c16b537SWarner Losh         for(idx=start; idx<end; idx++)
2530c16b537SWarner Losh             doneMarks[suffix[idx]] = 1;
2540c16b537SWarner Losh         return solution;
2550c16b537SWarner Losh     }
2560c16b537SWarner Losh 
2570c16b537SWarner Losh     {   int i;
258*a0483764SConrad Meyer         U32 mml;
2590c16b537SWarner Losh         U32 refinedStart = start;
2600c16b537SWarner Losh         U32 refinedEnd = end;
2610c16b537SWarner Losh 
2620c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
263*a0483764SConrad Meyer         DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u  ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
2640c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
2650c16b537SWarner Losh 
266*a0483764SConrad Meyer         for (mml = MINMATCHLENGTH ; ; mml++) {
2670c16b537SWarner Losh             BYTE currentChar = 0;
2680c16b537SWarner Losh             U32 currentCount = 0;
2690c16b537SWarner Losh             U32 currentID = refinedStart;
2700c16b537SWarner Losh             U32 id;
2710c16b537SWarner Losh             U32 selectedCount = 0;
2720c16b537SWarner Losh             U32 selectedID = currentID;
2730c16b537SWarner Losh             for (id =refinedStart; id < refinedEnd; id++) {
274*a0483764SConrad Meyer                 if (b[suffix[id] + mml] != currentChar) {
2750c16b537SWarner Losh                     if (currentCount > selectedCount) {
2760c16b537SWarner Losh                         selectedCount = currentCount;
2770c16b537SWarner Losh                         selectedID = currentID;
2780c16b537SWarner Losh                     }
2790c16b537SWarner Losh                     currentID = id;
280*a0483764SConrad Meyer                     currentChar = b[ suffix[id] + mml];
2810c16b537SWarner Losh                     currentCount = 0;
2820c16b537SWarner Losh                 }
2830c16b537SWarner Losh                 currentCount ++;
2840c16b537SWarner Losh             }
2850c16b537SWarner Losh             if (currentCount > selectedCount) {  /* for last */
2860c16b537SWarner Losh                 selectedCount = currentCount;
2870c16b537SWarner Losh                 selectedID = currentID;
2880c16b537SWarner Losh             }
2890c16b537SWarner Losh 
2900c16b537SWarner Losh             if (selectedCount < minRatio)
2910c16b537SWarner Losh                 break;
2920c16b537SWarner Losh             refinedStart = selectedID;
2930c16b537SWarner Losh             refinedEnd = refinedStart + selectedCount;
2940c16b537SWarner Losh         }
2950c16b537SWarner Losh 
2960f743729SConrad Meyer         /* evaluate gain based on new dict */
2970c16b537SWarner Losh         start = refinedStart;
2980c16b537SWarner Losh         pos = suffix[refinedStart];
2990c16b537SWarner Losh         end = start;
3000c16b537SWarner Losh         memset(lengthList, 0, sizeof(lengthList));
3010c16b537SWarner Losh 
3020c16b537SWarner Losh         /* look forward */
30319fcbaf1SConrad Meyer         {   size_t length;
3040c16b537SWarner Losh             do {
3050c16b537SWarner Losh                 end++;
3060c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[end]);
3070c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT-1;
3080c16b537SWarner Losh                 lengthList[length]++;
3090c16b537SWarner Losh             } while (length >=MINMATCHLENGTH);
31019fcbaf1SConrad Meyer         }
3110c16b537SWarner Losh 
3120c16b537SWarner Losh         /* look backward */
31319fcbaf1SConrad Meyer         {   size_t length = MINMATCHLENGTH;
3140c16b537SWarner Losh             while ((length >= MINMATCHLENGTH) & (start > 0)) {
3150c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[start - 1]);
3160c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT - 1;
3170c16b537SWarner Losh                 lengthList[length]++;
3180c16b537SWarner Losh                 if (length >= MINMATCHLENGTH) start--;
3190c16b537SWarner Losh             }
32019fcbaf1SConrad Meyer         }
3210c16b537SWarner Losh 
3220c16b537SWarner Losh         /* largest useful length */
3230c16b537SWarner Losh         memset(cumulLength, 0, sizeof(cumulLength));
3240c16b537SWarner Losh         cumulLength[maxLength-1] = lengthList[maxLength-1];
3250c16b537SWarner Losh         for (i=(int)(maxLength-2); i>=0; i--)
3260c16b537SWarner Losh             cumulLength[i] = cumulLength[i+1] + lengthList[i];
3270c16b537SWarner Losh 
3280c16b537SWarner Losh         for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
3290c16b537SWarner Losh         maxLength = i;
3300c16b537SWarner Losh 
3310c16b537SWarner Losh         /* reduce maxLength in case of final into repetitive data */
3320c16b537SWarner Losh         {   U32 l = (U32)maxLength;
3330c16b537SWarner Losh             BYTE const c = b[pos + maxLength-1];
3340c16b537SWarner Losh             while (b[pos+l-2]==c) l--;
3350c16b537SWarner Losh             maxLength = l;
3360c16b537SWarner Losh         }
3370c16b537SWarner Losh         if (maxLength < MINMATCHLENGTH) return solution;   /* skip : no long-enough solution */
3380c16b537SWarner Losh 
3390c16b537SWarner Losh         /* calculate savings */
3400c16b537SWarner Losh         savings[5] = 0;
3410c16b537SWarner Losh         for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
3420c16b537SWarner Losh             savings[i] = savings[i-1] + (lengthList[i] * (i-3));
3430c16b537SWarner Losh 
3440f743729SConrad Meyer         DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f)  \n",
345*a0483764SConrad Meyer                      (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / maxLength);
3460c16b537SWarner Losh 
3470c16b537SWarner Losh         solution.pos = (U32)pos;
3480c16b537SWarner Losh         solution.length = (U32)maxLength;
3490c16b537SWarner Losh         solution.savings = savings[maxLength];
3500c16b537SWarner Losh 
3510c16b537SWarner Losh         /* mark positions done */
3520c16b537SWarner Losh         {   U32 id;
3530c16b537SWarner Losh             for (id=start; id<end; id++) {
35419fcbaf1SConrad Meyer                 U32 p, pEnd, length;
3550c16b537SWarner Losh                 U32 const testedPos = suffix[id];
3560c16b537SWarner Losh                 if (testedPos == pos)
3570c16b537SWarner Losh                     length = solution.length;
3580c16b537SWarner Losh                 else {
35919fcbaf1SConrad Meyer                     length = (U32)ZDICT_count(b+pos, b+testedPos);
3600c16b537SWarner Losh                     if (length > solution.length) length = solution.length;
3610c16b537SWarner Losh                 }
3620c16b537SWarner Losh                 pEnd = (U32)(testedPos + length);
3630c16b537SWarner Losh                 for (p=testedPos; p<pEnd; p++)
3640c16b537SWarner Losh                     doneMarks[p] = 1;
3650c16b537SWarner Losh     }   }   }
3660c16b537SWarner Losh 
3670c16b537SWarner Losh     return solution;
3680c16b537SWarner Losh }
3690c16b537SWarner Losh 
3700c16b537SWarner Losh 
3710c16b537SWarner Losh static int isIncluded(const void* in, const void* container, size_t length)
3720c16b537SWarner Losh {
3730c16b537SWarner Losh     const char* const ip = (const char*) in;
3740c16b537SWarner Losh     const char* const into = (const char*) container;
3750c16b537SWarner Losh     size_t u;
3760c16b537SWarner Losh 
3770c16b537SWarner Losh     for (u=0; u<length; u++) {  /* works because end of buffer is a noisy guard band */
3780c16b537SWarner Losh         if (ip[u] != into[u]) break;
3790c16b537SWarner Losh     }
3800c16b537SWarner Losh 
3810c16b537SWarner Losh     return u==length;
3820c16b537SWarner Losh }
3830c16b537SWarner Losh 
3840c16b537SWarner Losh /*! ZDICT_tryMerge() :
3850c16b537SWarner Losh     check if dictItem can be merged, do it if possible
3860c16b537SWarner Losh     @return : id of destination elt, 0 if not merged
3870c16b537SWarner Losh */
3880c16b537SWarner Losh static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
3890c16b537SWarner Losh {
3900c16b537SWarner Losh     const U32 tableSize = table->pos;
3910c16b537SWarner Losh     const U32 eltEnd = elt.pos + elt.length;
3920c16b537SWarner Losh     const char* const buf = (const char*) buffer;
3930c16b537SWarner Losh 
3940c16b537SWarner Losh     /* tail overlap */
3950c16b537SWarner Losh     U32 u; for (u=1; u<tableSize; u++) {
3960c16b537SWarner Losh         if (u==eltNbToSkip) continue;
3970c16b537SWarner Losh         if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) {  /* overlap, existing > new */
3980c16b537SWarner Losh             /* append */
3990c16b537SWarner Losh             U32 const addedLength = table[u].pos - elt.pos;
4000c16b537SWarner Losh             table[u].length += addedLength;
4010c16b537SWarner Losh             table[u].pos = elt.pos;
4020c16b537SWarner Losh             table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4030c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4040c16b537SWarner Losh             elt = table[u];
4050c16b537SWarner Losh             /* sort : improve rank */
4060c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4070c16b537SWarner Losh             table[u] = table[u-1], u--;
4080c16b537SWarner Losh             table[u] = elt;
4090c16b537SWarner Losh             return u;
4100c16b537SWarner Losh     }   }
4110c16b537SWarner Losh 
4120c16b537SWarner Losh     /* front overlap */
4130c16b537SWarner Losh     for (u=1; u<tableSize; u++) {
4140c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4150c16b537SWarner Losh 
4160c16b537SWarner Losh         if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) {  /* overlap, existing < new */
4170c16b537SWarner Losh             /* append */
4180c16b537SWarner Losh             int const addedLength = (int)eltEnd - (table[u].pos + table[u].length);
4190c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4200c16b537SWarner Losh             if (addedLength > 0) {   /* otherwise, elt fully included into existing */
4210c16b537SWarner Losh                 table[u].length += addedLength;
4220c16b537SWarner Losh                 table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4230c16b537SWarner Losh             }
4240c16b537SWarner Losh             /* sort : improve rank */
4250c16b537SWarner Losh             elt = table[u];
4260c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4270c16b537SWarner Losh                 table[u] = table[u-1], u--;
4280c16b537SWarner Losh             table[u] = elt;
4290c16b537SWarner Losh             return u;
4300c16b537SWarner Losh         }
4310c16b537SWarner Losh 
4320c16b537SWarner Losh         if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
4330c16b537SWarner Losh             if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
4340c16b537SWarner Losh                 size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
4350c16b537SWarner Losh                 table[u].pos = elt.pos;
4360c16b537SWarner Losh                 table[u].savings += (U32)(elt.savings * addedLength / elt.length);
4370c16b537SWarner Losh                 table[u].length = MIN(elt.length, table[u].length + 1);
4380c16b537SWarner Losh                 return u;
4390c16b537SWarner Losh             }
4400c16b537SWarner Losh         }
4410c16b537SWarner Losh     }
4420c16b537SWarner Losh 
4430c16b537SWarner Losh     return 0;
4440c16b537SWarner Losh }
4450c16b537SWarner Losh 
4460c16b537SWarner Losh 
4470c16b537SWarner Losh static void ZDICT_removeDictItem(dictItem* table, U32 id)
4480c16b537SWarner Losh {
4490c16b537SWarner Losh     /* convention : table[0].pos stores nb of elts */
4500c16b537SWarner Losh     U32 const max = table[0].pos;
4510c16b537SWarner Losh     U32 u;
4520c16b537SWarner Losh     if (!id) return;   /* protection, should never happen */
4530c16b537SWarner Losh     for (u=id; u<max-1; u++)
4540c16b537SWarner Losh         table[u] = table[u+1];
4550c16b537SWarner Losh     table->pos--;
4560c16b537SWarner Losh }
4570c16b537SWarner Losh 
4580c16b537SWarner Losh 
4590c16b537SWarner Losh static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
4600c16b537SWarner Losh {
4610c16b537SWarner Losh     /* merge if possible */
4620c16b537SWarner Losh     U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
4630c16b537SWarner Losh     if (mergeId) {
4640c16b537SWarner Losh         U32 newMerge = 1;
4650c16b537SWarner Losh         while (newMerge) {
4660c16b537SWarner Losh             newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
4670c16b537SWarner Losh             if (newMerge) ZDICT_removeDictItem(table, mergeId);
4680c16b537SWarner Losh             mergeId = newMerge;
4690c16b537SWarner Losh         }
4700c16b537SWarner Losh         return;
4710c16b537SWarner Losh     }
4720c16b537SWarner Losh 
4730c16b537SWarner Losh     /* insert */
4740c16b537SWarner Losh     {   U32 current;
4750c16b537SWarner Losh         U32 nextElt = table->pos;
4760c16b537SWarner Losh         if (nextElt >= maxSize) nextElt = maxSize-1;
4770c16b537SWarner Losh         current = nextElt-1;
4780c16b537SWarner Losh         while (table[current].savings < elt.savings) {
4790c16b537SWarner Losh             table[current+1] = table[current];
4800c16b537SWarner Losh             current--;
4810c16b537SWarner Losh         }
4820c16b537SWarner Losh         table[current+1] = elt;
4830c16b537SWarner Losh         table->pos = nextElt+1;
4840c16b537SWarner Losh     }
4850c16b537SWarner Losh }
4860c16b537SWarner Losh 
4870c16b537SWarner Losh 
4880c16b537SWarner Losh static U32 ZDICT_dictSize(const dictItem* dictList)
4890c16b537SWarner Losh {
4900c16b537SWarner Losh     U32 u, dictSize = 0;
4910c16b537SWarner Losh     for (u=1; u<dictList[0].pos; u++)
4920c16b537SWarner Losh         dictSize += dictList[u].length;
4930c16b537SWarner Losh     return dictSize;
4940c16b537SWarner Losh }
4950c16b537SWarner Losh 
4960c16b537SWarner Losh 
4970c16b537SWarner Losh static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
4980c16b537SWarner Losh                             const void* const buffer, size_t bufferSize,   /* buffer must end with noisy guard band */
4990c16b537SWarner Losh                             const size_t* fileSizes, unsigned nbFiles,
500*a0483764SConrad Meyer                             unsigned minRatio, U32 notificationLevel)
5010c16b537SWarner Losh {
5020c16b537SWarner Losh     int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
5030c16b537SWarner Losh     int* const suffix = suffix0+1;
5040c16b537SWarner Losh     U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
5050c16b537SWarner Losh     BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks));   /* +16 for overflow security */
5060c16b537SWarner Losh     U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
5070c16b537SWarner Losh     size_t result = 0;
5080c16b537SWarner Losh     clock_t displayClock = 0;
5090c16b537SWarner Losh     clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
5100c16b537SWarner Losh 
5110c16b537SWarner Losh #   define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
5120c16b537SWarner Losh             if (ZDICT_clockSpan(displayClock) > refreshRate)  \
5130c16b537SWarner Losh             { displayClock = clock(); DISPLAY(__VA_ARGS__); \
5140c16b537SWarner Losh             if (notificationLevel>=4) fflush(stderr); } }
5150c16b537SWarner Losh 
5160c16b537SWarner Losh     /* init */
5170c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
5180c16b537SWarner Losh     if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
5190c16b537SWarner Losh         result = ERROR(memory_allocation);
5200c16b537SWarner Losh         goto _cleanup;
5210c16b537SWarner Losh     }
5220c16b537SWarner Losh     if (minRatio < MINRATIO) minRatio = MINRATIO;
5230c16b537SWarner Losh     memset(doneMarks, 0, bufferSize+16);
5240c16b537SWarner Losh 
5250c16b537SWarner Losh     /* limit sample set size (divsufsort limitation)*/
526*a0483764SConrad Meyer     if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
5270c16b537SWarner Losh     while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
5280c16b537SWarner Losh 
5290c16b537SWarner Losh     /* sort */
530*a0483764SConrad Meyer     DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
5310c16b537SWarner Losh     {   int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
5320c16b537SWarner Losh         if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
5330c16b537SWarner Losh     }
5340c16b537SWarner Losh     suffix[bufferSize] = (int)bufferSize;   /* leads into noise */
5350c16b537SWarner Losh     suffix0[0] = (int)bufferSize;           /* leads into noise */
5360c16b537SWarner Losh     /* build reverse suffix sort */
5370c16b537SWarner Losh     {   size_t pos;
5380c16b537SWarner Losh         for (pos=0; pos < bufferSize; pos++)
5390c16b537SWarner Losh             reverseSuffix[suffix[pos]] = (U32)pos;
5400c16b537SWarner Losh         /* note filePos tracks borders between samples.
5410c16b537SWarner Losh            It's not used at this stage, but planned to become useful in a later update */
5420c16b537SWarner Losh         filePos[0] = 0;
5430c16b537SWarner Losh         for (pos=1; pos<nbFiles; pos++)
5440c16b537SWarner Losh             filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
5450c16b537SWarner Losh     }
5460c16b537SWarner Losh 
5470c16b537SWarner Losh     DISPLAYLEVEL(2, "finding patterns ... \n");
5480c16b537SWarner Losh     DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
5490c16b537SWarner Losh 
5500c16b537SWarner Losh     {   U32 cursor; for (cursor=0; cursor < bufferSize; ) {
5510c16b537SWarner Losh             dictItem solution;
5520c16b537SWarner Losh             if (doneMarks[cursor]) { cursor++; continue; }
5530c16b537SWarner Losh             solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
5540c16b537SWarner Losh             if (solution.length==0) { cursor++; continue; }
5550c16b537SWarner Losh             ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
5560c16b537SWarner Losh             cursor += solution.length;
5570c16b537SWarner Losh             DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / bufferSize * 100);
5580c16b537SWarner Losh     }   }
5590c16b537SWarner Losh 
5600c16b537SWarner Losh _cleanup:
5610c16b537SWarner Losh     free(suffix0);
5620c16b537SWarner Losh     free(reverseSuffix);
5630c16b537SWarner Losh     free(doneMarks);
5640c16b537SWarner Losh     free(filePos);
5650c16b537SWarner Losh     return result;
5660c16b537SWarner Losh }
5670c16b537SWarner Losh 
5680c16b537SWarner Losh 
5690c16b537SWarner Losh static void ZDICT_fillNoise(void* buffer, size_t length)
5700c16b537SWarner Losh {
5710c16b537SWarner Losh     unsigned const prime1 = 2654435761U;
5720c16b537SWarner Losh     unsigned const prime2 = 2246822519U;
5730c16b537SWarner Losh     unsigned acc = prime1;
5740c16b537SWarner Losh     size_t p=0;;
5750c16b537SWarner Losh     for (p=0; p<length; p++) {
5760c16b537SWarner Losh         acc *= prime2;
5770c16b537SWarner Losh         ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
5780c16b537SWarner Losh     }
5790c16b537SWarner Losh }
5800c16b537SWarner Losh 
5810c16b537SWarner Losh 
5820c16b537SWarner Losh typedef struct
5830c16b537SWarner Losh {
5840f743729SConrad Meyer     ZSTD_CDict* dict;    /* dictionary */
58519fcbaf1SConrad Meyer     ZSTD_CCtx* zc;     /* working context */
5860c16b537SWarner Losh     void* workPlace;   /* must be ZSTD_BLOCKSIZE_MAX allocated */
5870c16b537SWarner Losh } EStats_ress_t;
5880c16b537SWarner Losh 
5890c16b537SWarner Losh #define MAXREPOFFSET 1024
5900c16b537SWarner Losh 
5910c16b537SWarner Losh static void ZDICT_countEStats(EStats_ress_t esr, ZSTD_parameters params,
592*a0483764SConrad Meyer                               unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
59319fcbaf1SConrad Meyer                               const void* src, size_t srcSize,
59419fcbaf1SConrad Meyer                               U32 notificationLevel)
5950c16b537SWarner Losh {
5960c16b537SWarner Losh     size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params.cParams.windowLog);
5970c16b537SWarner Losh     size_t cSize;
5980c16b537SWarner Losh 
5990c16b537SWarner Losh     if (srcSize > blockSizeMax) srcSize = blockSizeMax;   /* protection vs large samples */
6000f743729SConrad Meyer     {   size_t const errorCode = ZSTD_compressBegin_usingCDict(esr.zc, esr.dict);
6010f743729SConrad Meyer         if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
6020f743729SConrad Meyer 
6030c16b537SWarner Losh     }
6040c16b537SWarner Losh     cSize = ZSTD_compressBlock(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
605*a0483764SConrad Meyer     if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
6060c16b537SWarner Losh 
6070c16b537SWarner Losh     if (cSize) {  /* if == 0; block is not compressible */
60819fcbaf1SConrad Meyer         const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
6090c16b537SWarner Losh 
6100c16b537SWarner Losh         /* literals stats */
6110c16b537SWarner Losh         {   const BYTE* bytePtr;
6120c16b537SWarner Losh             for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
6130c16b537SWarner Losh                 countLit[*bytePtr]++;
6140c16b537SWarner Losh         }
6150c16b537SWarner Losh 
6160c16b537SWarner Losh         /* seqStats */
6170c16b537SWarner Losh         {   U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
6180c16b537SWarner Losh             ZSTD_seqToCodes(seqStorePtr);
6190c16b537SWarner Losh 
6200c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->ofCode;
6210c16b537SWarner Losh                 U32 u;
6220c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
6230c16b537SWarner Losh             }
6240c16b537SWarner Losh 
6250c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->mlCode;
6260c16b537SWarner Losh                 U32 u;
6270c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
6280c16b537SWarner Losh             }
6290c16b537SWarner Losh 
6300c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->llCode;
6310c16b537SWarner Losh                 U32 u;
6320c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
6330c16b537SWarner Losh             }
6340c16b537SWarner Losh 
6350c16b537SWarner Losh             if (nbSeq >= 2) { /* rep offsets */
6360c16b537SWarner Losh                 const seqDef* const seq = seqStorePtr->sequencesStart;
6370c16b537SWarner Losh                 U32 offset1 = seq[0].offset - 3;
6380c16b537SWarner Losh                 U32 offset2 = seq[1].offset - 3;
6390c16b537SWarner Losh                 if (offset1 >= MAXREPOFFSET) offset1 = 0;
6400c16b537SWarner Losh                 if (offset2 >= MAXREPOFFSET) offset2 = 0;
6410c16b537SWarner Losh                 repOffsets[offset1] += 3;
6420c16b537SWarner Losh                 repOffsets[offset2] += 1;
6430c16b537SWarner Losh     }   }   }
6440c16b537SWarner Losh }
6450c16b537SWarner Losh 
6460c16b537SWarner Losh static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
6470c16b537SWarner Losh {
6480c16b537SWarner Losh     size_t total=0;
6490c16b537SWarner Losh     unsigned u;
6500c16b537SWarner Losh     for (u=0; u<nbFiles; u++) total += fileSizes[u];
6510c16b537SWarner Losh     return total;
6520c16b537SWarner Losh }
6530c16b537SWarner Losh 
6540c16b537SWarner Losh typedef struct { U32 offset; U32 count; } offsetCount_t;
6550c16b537SWarner Losh 
6560c16b537SWarner Losh static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
6570c16b537SWarner Losh {
6580c16b537SWarner Losh     U32 u;
6590c16b537SWarner Losh     table[ZSTD_REP_NUM].offset = val;
6600c16b537SWarner Losh     table[ZSTD_REP_NUM].count = count;
6610c16b537SWarner Losh     for (u=ZSTD_REP_NUM; u>0; u--) {
6620c16b537SWarner Losh         offsetCount_t tmp;
6630c16b537SWarner Losh         if (table[u-1].count >= table[u].count) break;
6640c16b537SWarner Losh         tmp = table[u-1];
6650c16b537SWarner Losh         table[u-1] = table[u];
6660c16b537SWarner Losh         table[u] = tmp;
6670c16b537SWarner Losh     }
6680c16b537SWarner Losh }
6690c16b537SWarner Losh 
67019fcbaf1SConrad Meyer /* ZDICT_flatLit() :
67119fcbaf1SConrad Meyer  * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
67219fcbaf1SConrad Meyer  * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
67319fcbaf1SConrad Meyer  */
674*a0483764SConrad Meyer static void ZDICT_flatLit(unsigned* countLit)
67519fcbaf1SConrad Meyer {
67619fcbaf1SConrad Meyer     int u;
67719fcbaf1SConrad Meyer     for (u=1; u<256; u++) countLit[u] = 2;
67819fcbaf1SConrad Meyer     countLit[0]   = 4;
67919fcbaf1SConrad Meyer     countLit[253] = 1;
68019fcbaf1SConrad Meyer     countLit[254] = 1;
68119fcbaf1SConrad Meyer }
6820c16b537SWarner Losh 
6830c16b537SWarner Losh #define OFFCODE_MAX 30  /* only applicable to first block */
6840c16b537SWarner Losh static size_t ZDICT_analyzeEntropy(void*  dstBuffer, size_t maxDstSize,
6850c16b537SWarner Losh                                    unsigned compressionLevel,
6860c16b537SWarner Losh                              const void*  srcBuffer, const size_t* fileSizes, unsigned nbFiles,
6870c16b537SWarner Losh                              const void* dictBuffer, size_t  dictBufferSize,
6880c16b537SWarner Losh                                    unsigned notificationLevel)
6890c16b537SWarner Losh {
690*a0483764SConrad Meyer     unsigned countLit[256];
6910c16b537SWarner Losh     HUF_CREATE_STATIC_CTABLE(hufTable, 255);
692*a0483764SConrad Meyer     unsigned offcodeCount[OFFCODE_MAX+1];
6930c16b537SWarner Losh     short offcodeNCount[OFFCODE_MAX+1];
6940c16b537SWarner Losh     U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
695*a0483764SConrad Meyer     unsigned matchLengthCount[MaxML+1];
6960c16b537SWarner Losh     short matchLengthNCount[MaxML+1];
697*a0483764SConrad Meyer     unsigned litLengthCount[MaxLL+1];
6980c16b537SWarner Losh     short litLengthNCount[MaxLL+1];
6990c16b537SWarner Losh     U32 repOffset[MAXREPOFFSET];
7000c16b537SWarner Losh     offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
7010f743729SConrad Meyer     EStats_ress_t esr = { NULL, NULL, NULL };
7020c16b537SWarner Losh     ZSTD_parameters params;
7030c16b537SWarner Losh     U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
7040c16b537SWarner Losh     size_t pos = 0, errorCode;
7050c16b537SWarner Losh     size_t eSize = 0;
7060c16b537SWarner Losh     size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
7070c16b537SWarner Losh     size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
7080c16b537SWarner Losh     BYTE* dstPtr = (BYTE*)dstBuffer;
7090c16b537SWarner Losh 
7100c16b537SWarner Losh     /* init */
71119fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_analyzeEntropy");
7120c16b537SWarner Losh     if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; }   /* too large dictionary */
7130c16b537SWarner Losh     for (u=0; u<256; u++) countLit[u] = 1;   /* any character must be described */
7140c16b537SWarner Losh     for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
7150c16b537SWarner Losh     for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
7160c16b537SWarner Losh     for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
7170c16b537SWarner Losh     memset(repOffset, 0, sizeof(repOffset));
7180c16b537SWarner Losh     repOffset[1] = repOffset[4] = repOffset[8] = 1;
7190c16b537SWarner Losh     memset(bestRepOffset, 0, sizeof(bestRepOffset));
7200f743729SConrad Meyer     if (compressionLevel==0) compressionLevel = g_compressionLevel_default;
7210c16b537SWarner Losh     params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
7220f743729SConrad Meyer 
7230f743729SConrad Meyer     esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
7240f743729SConrad Meyer     esr.zc = ZSTD_createCCtx();
7250f743729SConrad Meyer     esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
7260f743729SConrad Meyer     if (!esr.dict || !esr.zc || !esr.workPlace) {
7270f743729SConrad Meyer         eSize = ERROR(memory_allocation);
7280f743729SConrad Meyer         DISPLAYLEVEL(1, "Not enough memory \n");
7290c16b537SWarner Losh         goto _cleanup;
7300f743729SConrad Meyer     }
7310c16b537SWarner Losh 
73219fcbaf1SConrad Meyer     /* collect stats on all samples */
7330c16b537SWarner Losh     for (u=0; u<nbFiles; u++) {
7340c16b537SWarner Losh         ZDICT_countEStats(esr, params,
7350c16b537SWarner Losh                           countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
7360c16b537SWarner Losh                          (const char*)srcBuffer + pos, fileSizes[u],
7370c16b537SWarner Losh                           notificationLevel);
7380c16b537SWarner Losh         pos += fileSizes[u];
7390c16b537SWarner Losh     }
7400c16b537SWarner Losh 
74119fcbaf1SConrad Meyer     /* analyze, build stats, starting with literals */
74219fcbaf1SConrad Meyer     {   size_t maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
74319fcbaf1SConrad Meyer         if (HUF_isError(maxNbBits)) {
7440c16b537SWarner Losh             eSize = ERROR(GENERIC);
7450c16b537SWarner Losh             DISPLAYLEVEL(1, " HUF_buildCTable error \n");
7460c16b537SWarner Losh             goto _cleanup;
7470c16b537SWarner Losh         }
74819fcbaf1SConrad Meyer         if (maxNbBits==8) {  /* not compressible : will fail on HUF_writeCTable() */
74919fcbaf1SConrad Meyer             DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
75019fcbaf1SConrad Meyer             ZDICT_flatLit(countLit);  /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
75119fcbaf1SConrad Meyer             maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
75219fcbaf1SConrad Meyer             assert(maxNbBits==9);
75319fcbaf1SConrad Meyer         }
75419fcbaf1SConrad Meyer         huffLog = (U32)maxNbBits;
75519fcbaf1SConrad Meyer     }
7560c16b537SWarner Losh 
7570c16b537SWarner Losh     /* looking for most common first offsets */
7580c16b537SWarner Losh     {   U32 offset;
7590c16b537SWarner Losh         for (offset=1; offset<MAXREPOFFSET; offset++)
7600c16b537SWarner Losh             ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
7610c16b537SWarner Losh     }
7620c16b537SWarner Losh     /* note : the result of this phase should be used to better appreciate the impact on statistics */
7630c16b537SWarner Losh 
7640c16b537SWarner Losh     total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
7650c16b537SWarner Losh     errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax);
7660c16b537SWarner Losh     if (FSE_isError(errorCode)) {
7670c16b537SWarner Losh         eSize = ERROR(GENERIC);
7680c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
7690c16b537SWarner Losh         goto _cleanup;
7700c16b537SWarner Losh     }
7710c16b537SWarner Losh     Offlog = (U32)errorCode;
7720c16b537SWarner Losh 
7730c16b537SWarner Losh     total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
7740c16b537SWarner Losh     errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML);
7750c16b537SWarner Losh     if (FSE_isError(errorCode)) {
7760c16b537SWarner Losh         eSize = ERROR(GENERIC);
7770c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
7780c16b537SWarner Losh         goto _cleanup;
7790c16b537SWarner Losh     }
7800c16b537SWarner Losh     mlLog = (U32)errorCode;
7810c16b537SWarner Losh 
7820c16b537SWarner Losh     total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
7830c16b537SWarner Losh     errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL);
7840c16b537SWarner Losh     if (FSE_isError(errorCode)) {
7850c16b537SWarner Losh         eSize = ERROR(GENERIC);
7860c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
7870c16b537SWarner Losh         goto _cleanup;
7880c16b537SWarner Losh     }
7890c16b537SWarner Losh     llLog = (U32)errorCode;
7900c16b537SWarner Losh 
7910c16b537SWarner Losh     /* write result to buffer */
7920c16b537SWarner Losh     {   size_t const hhSize = HUF_writeCTable(dstPtr, maxDstSize, hufTable, 255, huffLog);
7930c16b537SWarner Losh         if (HUF_isError(hhSize)) {
7940c16b537SWarner Losh             eSize = ERROR(GENERIC);
7950c16b537SWarner Losh             DISPLAYLEVEL(1, "HUF_writeCTable error \n");
7960c16b537SWarner Losh             goto _cleanup;
7970c16b537SWarner Losh         }
7980c16b537SWarner Losh         dstPtr += hhSize;
7990c16b537SWarner Losh         maxDstSize -= hhSize;
8000c16b537SWarner Losh         eSize += hhSize;
8010c16b537SWarner Losh     }
8020c16b537SWarner Losh 
8030c16b537SWarner Losh     {   size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
8040c16b537SWarner Losh         if (FSE_isError(ohSize)) {
8050c16b537SWarner Losh             eSize = ERROR(GENERIC);
8060c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
8070c16b537SWarner Losh             goto _cleanup;
8080c16b537SWarner Losh         }
8090c16b537SWarner Losh         dstPtr += ohSize;
8100c16b537SWarner Losh         maxDstSize -= ohSize;
8110c16b537SWarner Losh         eSize += ohSize;
8120c16b537SWarner Losh     }
8130c16b537SWarner Losh 
8140c16b537SWarner Losh     {   size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
8150c16b537SWarner Losh         if (FSE_isError(mhSize)) {
8160c16b537SWarner Losh             eSize = ERROR(GENERIC);
8170c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
8180c16b537SWarner Losh             goto _cleanup;
8190c16b537SWarner Losh         }
8200c16b537SWarner Losh         dstPtr += mhSize;
8210c16b537SWarner Losh         maxDstSize -= mhSize;
8220c16b537SWarner Losh         eSize += mhSize;
8230c16b537SWarner Losh     }
8240c16b537SWarner Losh 
8250c16b537SWarner Losh     {   size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
8260c16b537SWarner Losh         if (FSE_isError(lhSize)) {
8270c16b537SWarner Losh             eSize = ERROR(GENERIC);
8280c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
8290c16b537SWarner Losh             goto _cleanup;
8300c16b537SWarner Losh         }
8310c16b537SWarner Losh         dstPtr += lhSize;
8320c16b537SWarner Losh         maxDstSize -= lhSize;
8330c16b537SWarner Losh         eSize += lhSize;
8340c16b537SWarner Losh     }
8350c16b537SWarner Losh 
8360c16b537SWarner Losh     if (maxDstSize<12) {
8370c16b537SWarner Losh         eSize = ERROR(GENERIC);
8380c16b537SWarner Losh         DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
8390c16b537SWarner Losh         goto _cleanup;
8400c16b537SWarner Losh     }
8410c16b537SWarner Losh # if 0
8420c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
8430c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
8440c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
8450c16b537SWarner Losh #else
8460c16b537SWarner Losh     /* at this stage, we don't use the result of "most common first offset",
8470c16b537SWarner Losh        as the impact of statistics is not properly evaluated */
8480c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, repStartValue[0]);
8490c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, repStartValue[1]);
8500c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, repStartValue[2]);
8510c16b537SWarner Losh #endif
8520c16b537SWarner Losh     eSize += 12;
8530c16b537SWarner Losh 
8540c16b537SWarner Losh _cleanup:
8550f743729SConrad Meyer     ZSTD_freeCDict(esr.dict);
8560c16b537SWarner Losh     ZSTD_freeCCtx(esr.zc);
8570c16b537SWarner Losh     free(esr.workPlace);
8580c16b537SWarner Losh 
8590c16b537SWarner Losh     return eSize;
8600c16b537SWarner Losh }
8610c16b537SWarner Losh 
8620c16b537SWarner Losh 
8630c16b537SWarner Losh 
8640c16b537SWarner Losh size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
8650c16b537SWarner Losh                           const void* customDictContent, size_t dictContentSize,
8660f743729SConrad Meyer                           const void* samplesBuffer, const size_t* samplesSizes,
8670f743729SConrad Meyer                           unsigned nbSamples, ZDICT_params_t params)
8680c16b537SWarner Losh {
8690c16b537SWarner Losh     size_t hSize;
8700c16b537SWarner Losh #define HBUFFSIZE 256   /* should prove large enough for all entropy headers */
8710c16b537SWarner Losh     BYTE header[HBUFFSIZE];
8720f743729SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? g_compressionLevel_default : params.compressionLevel;
8730c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
8740c16b537SWarner Losh 
8750c16b537SWarner Losh     /* check conditions */
87619fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_finalizeDictionary");
8770c16b537SWarner Losh     if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
8780c16b537SWarner Losh     if (dictContentSize < ZDICT_CONTENTSIZE_MIN) return ERROR(srcSize_wrong);
8790c16b537SWarner Losh     if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
8800c16b537SWarner Losh 
8810c16b537SWarner Losh     /* dictionary header */
8820c16b537SWarner Losh     MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
8830c16b537SWarner Losh     {   U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
8840c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
8850c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
8860c16b537SWarner Losh         MEM_writeLE32(header+4, dictID);
8870c16b537SWarner Losh     }
8880c16b537SWarner Losh     hSize = 8;
8890c16b537SWarner Losh 
8900c16b537SWarner Losh     /* entropy tables */
8910c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
8920c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
8930c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
8940c16b537SWarner Losh                                   compressionLevel,
8950c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
8960c16b537SWarner Losh                                   customDictContent, dictContentSize,
8970c16b537SWarner Losh                                   notificationLevel);
8980c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
8990c16b537SWarner Losh         hSize += eSize;
9000c16b537SWarner Losh     }
9010c16b537SWarner Losh 
9020c16b537SWarner Losh     /* copy elements in final buffer ; note : src and dst buffer can overlap */
9030c16b537SWarner Losh     if (hSize + dictContentSize > dictBufferCapacity) dictContentSize = dictBufferCapacity - hSize;
9040c16b537SWarner Losh     {   size_t const dictSize = hSize + dictContentSize;
9050c16b537SWarner Losh         char* dictEnd = (char*)dictBuffer + dictSize;
9060c16b537SWarner Losh         memmove(dictEnd - dictContentSize, customDictContent, dictContentSize);
9070c16b537SWarner Losh         memcpy(dictBuffer, header, hSize);
9080c16b537SWarner Losh         return dictSize;
9090c16b537SWarner Losh     }
9100c16b537SWarner Losh }
9110c16b537SWarner Losh 
9120c16b537SWarner Losh 
9130f743729SConrad Meyer static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
9140f743729SConrad Meyer         void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
9150c16b537SWarner Losh         const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9160c16b537SWarner Losh         ZDICT_params_t params)
9170c16b537SWarner Losh {
9180f743729SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? g_compressionLevel_default : params.compressionLevel;
9190c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
9200c16b537SWarner Losh     size_t hSize = 8;
9210c16b537SWarner Losh 
9220c16b537SWarner Losh     /* calculate entropy tables */
9230c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
9240c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
9250c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
9260c16b537SWarner Losh                                   compressionLevel,
9270c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
9280c16b537SWarner Losh                                   (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
9290c16b537SWarner Losh                                   notificationLevel);
9300c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
9310c16b537SWarner Losh         hSize += eSize;
9320c16b537SWarner Losh     }
9330c16b537SWarner Losh 
9340c16b537SWarner Losh     /* add dictionary header (after entropy tables) */
9350c16b537SWarner Losh     MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
9360c16b537SWarner Losh     {   U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
9370c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
9380c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
9390c16b537SWarner Losh         MEM_writeLE32((char*)dictBuffer+4, dictID);
9400c16b537SWarner Losh     }
9410c16b537SWarner Losh 
9420c16b537SWarner Losh     if (hSize + dictContentSize < dictBufferCapacity)
9430c16b537SWarner Losh         memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
9440c16b537SWarner Losh     return MIN(dictBufferCapacity, hSize+dictContentSize);
9450c16b537SWarner Losh }
9460c16b537SWarner Losh 
9470f743729SConrad Meyer /* Hidden declaration for dbio.c */
9480f743729SConrad Meyer size_t ZDICT_trainFromBuffer_unsafe_legacy(
9490f743729SConrad Meyer                             void* dictBuffer, size_t maxDictSize,
9500f743729SConrad Meyer                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9510f743729SConrad Meyer                             ZDICT_legacy_params_t params);
9520c16b537SWarner Losh /*! ZDICT_trainFromBuffer_unsafe_legacy() :
9530c16b537SWarner Losh *   Warning : `samplesBuffer` must be followed by noisy guard band.
9540c16b537SWarner Losh *   @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
9550c16b537SWarner Losh */
9560c16b537SWarner Losh size_t ZDICT_trainFromBuffer_unsafe_legacy(
9570c16b537SWarner Losh                             void* dictBuffer, size_t maxDictSize,
9580c16b537SWarner Losh                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9590c16b537SWarner Losh                             ZDICT_legacy_params_t params)
9600c16b537SWarner Losh {
9610c16b537SWarner Losh     U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
9620c16b537SWarner Losh     dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
9630c16b537SWarner Losh     unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
9640c16b537SWarner Losh     unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
9650c16b537SWarner Losh     size_t const targetDictSize = maxDictSize;
9660c16b537SWarner Losh     size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
9670c16b537SWarner Losh     size_t dictSize = 0;
9680c16b537SWarner Losh     U32 const notificationLevel = params.zParams.notificationLevel;
9690c16b537SWarner Losh 
9700c16b537SWarner Losh     /* checks */
9710c16b537SWarner Losh     if (!dictList) return ERROR(memory_allocation);
9720c16b537SWarner Losh     if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); }   /* requested dictionary size is too small */
9730c16b537SWarner Losh     if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* not enough source to create dictionary */
9740c16b537SWarner Losh 
9750c16b537SWarner Losh     /* init */
9760c16b537SWarner Losh     ZDICT_initDictItem(dictList);
9770c16b537SWarner Losh 
9780c16b537SWarner Losh     /* build dictionary */
9790c16b537SWarner Losh     ZDICT_trainBuffer_legacy(dictList, dictListSize,
9800c16b537SWarner Losh                        samplesBuffer, samplesBuffSize,
9810c16b537SWarner Losh                        samplesSizes, nbSamples,
9820c16b537SWarner Losh                        minRep, notificationLevel);
9830c16b537SWarner Losh 
9840c16b537SWarner Losh     /* display best matches */
9850c16b537SWarner Losh     if (params.zParams.notificationLevel>= 3) {
986*a0483764SConrad Meyer         unsigned const nb = MIN(25, dictList[0].pos);
987*a0483764SConrad Meyer         unsigned const dictContentSize = ZDICT_dictSize(dictList);
988*a0483764SConrad Meyer         unsigned u;
989*a0483764SConrad Meyer         DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
9900c16b537SWarner Losh         DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
9910c16b537SWarner Losh         for (u=1; u<nb; u++) {
992*a0483764SConrad Meyer             unsigned const pos = dictList[u].pos;
993*a0483764SConrad Meyer             unsigned const length = dictList[u].length;
9940c16b537SWarner Losh             U32 const printedLength = MIN(40, length);
9950f743729SConrad Meyer             if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
9960f743729SConrad Meyer                 free(dictList);
9970c16b537SWarner Losh                 return ERROR(GENERIC);   /* should never happen */
9980f743729SConrad Meyer             }
9990c16b537SWarner Losh             DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
1000*a0483764SConrad Meyer                          u, length, pos, (unsigned)dictList[u].savings);
10010c16b537SWarner Losh             ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
10020c16b537SWarner Losh             DISPLAYLEVEL(3, "| \n");
10030c16b537SWarner Losh     }   }
10040c16b537SWarner Losh 
10050c16b537SWarner Losh 
10060c16b537SWarner Losh     /* create dictionary */
1007*a0483764SConrad Meyer     {   unsigned dictContentSize = ZDICT_dictSize(dictList);
10080c16b537SWarner Losh         if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* dictionary content too small */
10090c16b537SWarner Losh         if (dictContentSize < targetDictSize/4) {
1010*a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
10110c16b537SWarner Losh             if (samplesBuffSize < 10 * targetDictSize)
1012*a0483764SConrad Meyer                 DISPLAYLEVEL(2, "!  consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
10130c16b537SWarner Losh             if (minRep > MINRATIO) {
10140c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
10150c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
10160c16b537SWarner Losh             }
10170c16b537SWarner Losh         }
10180c16b537SWarner Losh 
10190c16b537SWarner Losh         if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
1020*a0483764SConrad Meyer             unsigned proposedSelectivity = selectivity-1;
10210c16b537SWarner Losh             while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
1022*a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
10230c16b537SWarner Losh             DISPLAYLEVEL(2, "!  consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
10240c16b537SWarner Losh             DISPLAYLEVEL(2, "!  always test dictionary efficiency on real samples \n");
10250c16b537SWarner Losh         }
10260c16b537SWarner Losh 
10270c16b537SWarner Losh         /* limit dictionary size */
10280c16b537SWarner Losh         {   U32 const max = dictList->pos;   /* convention : nb of useful elts within dictList */
10290c16b537SWarner Losh             U32 currentSize = 0;
10300c16b537SWarner Losh             U32 n; for (n=1; n<max; n++) {
10310c16b537SWarner Losh                 currentSize += dictList[n].length;
10320c16b537SWarner Losh                 if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
10330c16b537SWarner Losh             }
10340c16b537SWarner Losh             dictList->pos = n;
10350c16b537SWarner Losh             dictContentSize = currentSize;
10360c16b537SWarner Losh         }
10370c16b537SWarner Losh 
10380c16b537SWarner Losh         /* build dict content */
10390c16b537SWarner Losh         {   U32 u;
10400c16b537SWarner Losh             BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
10410c16b537SWarner Losh             for (u=1; u<dictList->pos; u++) {
10420c16b537SWarner Losh                 U32 l = dictList[u].length;
10430c16b537SWarner Losh                 ptr -= l;
10440c16b537SWarner Losh                 if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); }   /* should not happen */
10450c16b537SWarner Losh                 memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
10460c16b537SWarner Losh         }   }
10470c16b537SWarner Losh 
10480c16b537SWarner Losh         dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
10490c16b537SWarner Losh                                                              samplesBuffer, samplesSizes, nbSamples,
10500c16b537SWarner Losh                                                              params.zParams);
10510c16b537SWarner Losh     }
10520c16b537SWarner Losh 
10530c16b537SWarner Losh     /* clean up */
10540c16b537SWarner Losh     free(dictList);
10550c16b537SWarner Losh     return dictSize;
10560c16b537SWarner Losh }
10570c16b537SWarner Losh 
10580c16b537SWarner Losh 
105919fcbaf1SConrad Meyer /* ZDICT_trainFromBuffer_legacy() :
106019fcbaf1SConrad Meyer  * issue : samplesBuffer need to be followed by a noisy guard band.
10610c16b537SWarner Losh  * work around : duplicate the buffer, and add the noise */
10620c16b537SWarner Losh size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
10630c16b537SWarner Losh                               const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
10640c16b537SWarner Losh                               ZDICT_legacy_params_t params)
10650c16b537SWarner Losh {
10660c16b537SWarner Losh     size_t result;
10670c16b537SWarner Losh     void* newBuff;
10680c16b537SWarner Losh     size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
10690c16b537SWarner Losh     if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0;   /* not enough content => no dictionary */
10700c16b537SWarner Losh 
10710c16b537SWarner Losh     newBuff = malloc(sBuffSize + NOISELENGTH);
10720c16b537SWarner Losh     if (!newBuff) return ERROR(memory_allocation);
10730c16b537SWarner Losh 
10740c16b537SWarner Losh     memcpy(newBuff, samplesBuffer, sBuffSize);
10750c16b537SWarner Losh     ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH);   /* guard band, for end of buffer condition */
10760c16b537SWarner Losh 
10770c16b537SWarner Losh     result =
10780c16b537SWarner Losh         ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
10790c16b537SWarner Losh                                             samplesSizes, nbSamples, params);
10800c16b537SWarner Losh     free(newBuff);
10810c16b537SWarner Losh     return result;
10820c16b537SWarner Losh }
10830c16b537SWarner Losh 
10840c16b537SWarner Losh 
10850c16b537SWarner Losh size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
10860c16b537SWarner Losh                              const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
10870c16b537SWarner Losh {
10880f743729SConrad Meyer     ZDICT_fastCover_params_t params;
108919fcbaf1SConrad Meyer     DEBUGLOG(3, "ZDICT_trainFromBuffer");
10900c16b537SWarner Losh     memset(&params, 0, sizeof(params));
10910c16b537SWarner Losh     params.d = 8;
10920c16b537SWarner Losh     params.steps = 4;
109319fcbaf1SConrad Meyer     /* Default to level 6 since no compression level information is available */
10940f743729SConrad Meyer     params.zParams.compressionLevel = 3;
10950f743729SConrad Meyer #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
10960f743729SConrad Meyer     params.zParams.notificationLevel = DEBUGLEVEL;
109719fcbaf1SConrad Meyer #endif
10980f743729SConrad Meyer     return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
109919fcbaf1SConrad Meyer                                                samplesBuffer, samplesSizes, nbSamples,
110019fcbaf1SConrad Meyer                                                &params);
11010c16b537SWarner Losh }
11020c16b537SWarner Losh 
11030c16b537SWarner Losh size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
11040c16b537SWarner Losh                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
11050c16b537SWarner Losh {
11060c16b537SWarner Losh     ZDICT_params_t params;
11070c16b537SWarner Losh     memset(&params, 0, sizeof(params));
11080c16b537SWarner Losh     return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
11090c16b537SWarner Losh                                                      samplesBuffer, samplesSizes, nbSamples,
11100c16b537SWarner Losh                                                      params);
11110c16b537SWarner Losh }
1112