1 /*
2  * Copyright (c) Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  * You may select, at your option, one of the above-listed licenses.
9  */
10 
11 
12 /*-**************************************
13 *  Tuning parameters
14 ****************************************/
15 #define MINRATIO 4   /* minimum nb of apparition to be selected in dictionary */
16 #define ZDICT_MAX_SAMPLES_SIZE (2000U << 20)
17 #define ZDICT_MIN_SAMPLES_SIZE (ZDICT_CONTENTSIZE_MIN * MINRATIO)
18 
19 
20 /*-**************************************
21 *  Compiler Options
22 ****************************************/
23 /* Unix Large Files support (>4GB) */
24 #define _FILE_OFFSET_BITS 64
25 #if (defined(__sun__) && (!defined(__LP64__)))   /* Sun Solaris 32-bits requires specific definitions */
26 #  ifndef _LARGEFILE_SOURCE
27 #  define _LARGEFILE_SOURCE
28 #  endif
29 #elif ! defined(__LP64__)                        /* No point defining Large file for 64 bit */
30 #  ifndef _LARGEFILE64_SOURCE
31 #  define _LARGEFILE64_SOURCE
32 #  endif
33 #endif
34 
35 
36 /*-*************************************
37 *  Dependencies
38 ***************************************/
39 #include <stdlib.h>        /* malloc, free */
40 #include <string.h>        /* memset */
41 #include <stdio.h>         /* fprintf, fopen, ftello64 */
42 #include <time.h>          /* clock */
43 
44 #ifndef ZDICT_STATIC_LINKING_ONLY
45 #  define ZDICT_STATIC_LINKING_ONLY
46 #endif
47 #define HUF_STATIC_LINKING_ONLY
48 
49 #include "../common/mem.h"           /* read */
50 #include "../common/fse.h"           /* FSE_normalizeCount, FSE_writeNCount */
51 #include "../common/huf.h"           /* HUF_buildCTable, HUF_writeCTable */
52 #include "../common/zstd_internal.h" /* includes zstd.h */
53 #include "../common/xxhash.h"        /* XXH64 */
54 #include "../compress/zstd_compress_internal.h" /* ZSTD_loadCEntropy() */
55 #include "../zdict.h"
56 #include "divsufsort.h"
57 
58 
59 /*-*************************************
60 *  Constants
61 ***************************************/
62 #define KB *(1 <<10)
63 #define MB *(1 <<20)
64 #define GB *(1U<<30)
65 
66 #define DICTLISTSIZE_DEFAULT 10000
67 
68 #define NOISELENGTH 32
69 
70 static const U32 g_selectivity_default = 9;
71 
72 
73 /*-*************************************
74 *  Console display
75 ***************************************/
76 #undef  DISPLAY
77 #define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
78 #undef  DISPLAYLEVEL
79 #define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); }    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
80 
ZDICT_clockSpan(clock_t nPrevious)81 static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
82 
ZDICT_printHex(const void * ptr,size_t length)83 static void ZDICT_printHex(const void* ptr, size_t length)
84 {
85     const BYTE* const b = (const BYTE*)ptr;
86     size_t u;
87     for (u=0; u<length; u++) {
88         BYTE c = b[u];
89         if (c<32 || c>126) c = '.';   /* non-printable char */
90         DISPLAY("%c", c);
91     }
92 }
93 
94 
95 /*-********************************************************
96 *  Helper functions
97 **********************************************************/
ZDICT_isError(size_t errorCode)98 unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
99 
ZDICT_getErrorName(size_t errorCode)100 const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
101 
ZDICT_getDictID(const void * dictBuffer,size_t dictSize)102 unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
103 {
104     if (dictSize < 8) return 0;
105     if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
106     return MEM_readLE32((const char*)dictBuffer + 4);
107 }
108 
ZDICT_getDictHeaderSize(const void * dictBuffer,size_t dictSize)109 size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)
110 {
111     size_t headerSize;
112     if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);
113 
114     {   ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));
115         U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);
116         if (!bs || !wksp) {
117             headerSize = ERROR(memory_allocation);
118         } else {
119             ZSTD_reset_compressedBlockState(bs);
120             headerSize = ZSTD_loadCEntropy(bs, wksp, dictBuffer, dictSize);
121         }
122 
123         free(bs);
124         free(wksp);
125     }
126 
127     return headerSize;
128 }
129 
130 /*-********************************************************
131 *  Dictionary training functions
132 **********************************************************/
ZDICT_NbCommonBytes(size_t val)133 static unsigned ZDICT_NbCommonBytes (size_t val)
134 {
135     if (MEM_isLittleEndian()) {
136         if (MEM_64bits()) {
137 #       if defined(_MSC_VER) && defined(_WIN64)
138             unsigned long r = 0;
139             _BitScanForward64( &r, (U64)val );
140             return (unsigned)(r>>3);
141 #       elif defined(__GNUC__) && (__GNUC__ >= 3)
142             return (__builtin_ctzll((U64)val) >> 3);
143 #       else
144             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 };
145             return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
146 #       endif
147         } else { /* 32 bits */
148 #       if defined(_MSC_VER)
149             unsigned long r=0;
150             _BitScanForward( &r, (U32)val );
151             return (unsigned)(r>>3);
152 #       elif defined(__GNUC__) && (__GNUC__ >= 3)
153             return (__builtin_ctz((U32)val) >> 3);
154 #       else
155             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 };
156             return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
157 #       endif
158         }
159     } else {  /* Big Endian CPU */
160         if (MEM_64bits()) {
161 #       if defined(_MSC_VER) && defined(_WIN64)
162             unsigned long r = 0;
163             _BitScanReverse64( &r, val );
164             return (unsigned)(r>>3);
165 #       elif defined(__GNUC__) && (__GNUC__ >= 3)
166             return (__builtin_clzll(val) >> 3);
167 #       else
168             unsigned r;
169             const unsigned n32 = sizeof(size_t)*4;   /* calculate this way due to compiler complaining in 32-bits mode */
170             if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
171             if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
172             r += (!val);
173             return r;
174 #       endif
175         } else { /* 32 bits */
176 #       if defined(_MSC_VER)
177             unsigned long r = 0;
178             _BitScanReverse( &r, (unsigned long)val );
179             return (unsigned)(r>>3);
180 #       elif defined(__GNUC__) && (__GNUC__ >= 3)
181             return (__builtin_clz((U32)val) >> 3);
182 #       else
183             unsigned r;
184             if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
185             r += (!val);
186             return r;
187 #       endif
188     }   }
189 }
190 
191 
192 /*! ZDICT_count() :
193     Count the nb of common bytes between 2 pointers.
194     Note : this function presumes end of buffer followed by noisy guard band.
195 */
ZDICT_count(const void * pIn,const void * pMatch)196 static size_t ZDICT_count(const void* pIn, const void* pMatch)
197 {
198     const char* const pStart = (const char*)pIn;
199     for (;;) {
200         size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
201         if (!diff) {
202             pIn = (const char*)pIn+sizeof(size_t);
203             pMatch = (const char*)pMatch+sizeof(size_t);
204             continue;
205         }
206         pIn = (const char*)pIn+ZDICT_NbCommonBytes(diff);
207         return (size_t)((const char*)pIn - pStart);
208     }
209 }
210 
211 
212 typedef struct {
213     U32 pos;
214     U32 length;
215     U32 savings;
216 } dictItem;
217 
ZDICT_initDictItem(dictItem * d)218 static void ZDICT_initDictItem(dictItem* d)
219 {
220     d->pos = 1;
221     d->length = 0;
222     d->savings = (U32)(-1);
223 }
224 
225 
226 #define LLIMIT 64          /* heuristic determined experimentally */
227 #define MINMATCHLENGTH 7   /* heuristic determined experimentally */
ZDICT_analyzePos(BYTE * doneMarks,const int * suffix,U32 start,const void * buffer,U32 minRatio,U32 notificationLevel)228 static dictItem ZDICT_analyzePos(
229                        BYTE* doneMarks,
230                        const int* suffix, U32 start,
231                        const void* buffer, U32 minRatio, U32 notificationLevel)
232 {
233     U32 lengthList[LLIMIT] = {0};
234     U32 cumulLength[LLIMIT] = {0};
235     U32 savings[LLIMIT] = {0};
236     const BYTE* b = (const BYTE*)buffer;
237     size_t maxLength = LLIMIT;
238     size_t pos = suffix[start];
239     U32 end = start;
240     dictItem solution;
241 
242     /* init */
243     memset(&solution, 0, sizeof(solution));
244     doneMarks[pos] = 1;
245 
246     /* trivial repetition cases */
247     if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
248        ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
249        ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
250         /* skip and mark segment */
251         U16 const pattern16 = MEM_read16(b+pos+4);
252         U32 u, patternEnd = 6;
253         while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
254         if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
255         for (u=1; u<patternEnd; u++)
256             doneMarks[pos+u] = 1;
257         return solution;
258     }
259 
260     /* look forward */
261     {   size_t length;
262         do {
263             end++;
264             length = ZDICT_count(b + pos, b + suffix[end]);
265         } while (length >= MINMATCHLENGTH);
266     }
267 
268     /* look backward */
269     {   size_t length;
270         do {
271             length = ZDICT_count(b + pos, b + *(suffix+start-1));
272             if (length >=MINMATCHLENGTH) start--;
273         } while(length >= MINMATCHLENGTH);
274     }
275 
276     /* exit if not found a minimum nb of repetitions */
277     if (end-start < minRatio) {
278         U32 idx;
279         for(idx=start; idx<end; idx++)
280             doneMarks[suffix[idx]] = 1;
281         return solution;
282     }
283 
284     {   int i;
285         U32 mml;
286         U32 refinedStart = start;
287         U32 refinedEnd = end;
288 
289         DISPLAYLEVEL(4, "\n");
290         DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u  ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
291         DISPLAYLEVEL(4, "\n");
292 
293         for (mml = MINMATCHLENGTH ; ; mml++) {
294             BYTE currentChar = 0;
295             U32 currentCount = 0;
296             U32 currentID = refinedStart;
297             U32 id;
298             U32 selectedCount = 0;
299             U32 selectedID = currentID;
300             for (id =refinedStart; id < refinedEnd; id++) {
301                 if (b[suffix[id] + mml] != currentChar) {
302                     if (currentCount > selectedCount) {
303                         selectedCount = currentCount;
304                         selectedID = currentID;
305                     }
306                     currentID = id;
307                     currentChar = b[ suffix[id] + mml];
308                     currentCount = 0;
309                 }
310                 currentCount ++;
311             }
312             if (currentCount > selectedCount) {  /* for last */
313                 selectedCount = currentCount;
314                 selectedID = currentID;
315             }
316 
317             if (selectedCount < minRatio)
318                 break;
319             refinedStart = selectedID;
320             refinedEnd = refinedStart + selectedCount;
321         }
322 
323         /* evaluate gain based on new dict */
324         start = refinedStart;
325         pos = suffix[refinedStart];
326         end = start;
327         memset(lengthList, 0, sizeof(lengthList));
328 
329         /* look forward */
330         {   size_t length;
331             do {
332                 end++;
333                 length = ZDICT_count(b + pos, b + suffix[end]);
334                 if (length >= LLIMIT) length = LLIMIT-1;
335                 lengthList[length]++;
336             } while (length >=MINMATCHLENGTH);
337         }
338 
339         /* look backward */
340         {   size_t length = MINMATCHLENGTH;
341             while ((length >= MINMATCHLENGTH) & (start > 0)) {
342                 length = ZDICT_count(b + pos, b + suffix[start - 1]);
343                 if (length >= LLIMIT) length = LLIMIT - 1;
344                 lengthList[length]++;
345                 if (length >= MINMATCHLENGTH) start--;
346             }
347         }
348 
349         /* largest useful length */
350         memset(cumulLength, 0, sizeof(cumulLength));
351         cumulLength[maxLength-1] = lengthList[maxLength-1];
352         for (i=(int)(maxLength-2); i>=0; i--)
353             cumulLength[i] = cumulLength[i+1] + lengthList[i];
354 
355         for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
356         maxLength = i;
357 
358         /* reduce maxLength in case of final into repetitive data */
359         {   U32 l = (U32)maxLength;
360             BYTE const c = b[pos + maxLength-1];
361             while (b[pos+l-2]==c) l--;
362             maxLength = l;
363         }
364         if (maxLength < MINMATCHLENGTH) return solution;   /* skip : no long-enough solution */
365 
366         /* calculate savings */
367         savings[5] = 0;
368         for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
369             savings[i] = savings[i-1] + (lengthList[i] * (i-3));
370 
371         DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f)  \n",
372                      (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / maxLength);
373 
374         solution.pos = (U32)pos;
375         solution.length = (U32)maxLength;
376         solution.savings = savings[maxLength];
377 
378         /* mark positions done */
379         {   U32 id;
380             for (id=start; id<end; id++) {
381                 U32 p, pEnd, length;
382                 U32 const testedPos = suffix[id];
383                 if (testedPos == pos)
384                     length = solution.length;
385                 else {
386                     length = (U32)ZDICT_count(b+pos, b+testedPos);
387                     if (length > solution.length) length = solution.length;
388                 }
389                 pEnd = (U32)(testedPos + length);
390                 for (p=testedPos; p<pEnd; p++)
391                     doneMarks[p] = 1;
392     }   }   }
393 
394     return solution;
395 }
396 
397 
isIncluded(const void * in,const void * container,size_t length)398 static int isIncluded(const void* in, const void* container, size_t length)
399 {
400     const char* const ip = (const char*) in;
401     const char* const into = (const char*) container;
402     size_t u;
403 
404     for (u=0; u<length; u++) {  /* works because end of buffer is a noisy guard band */
405         if (ip[u] != into[u]) break;
406     }
407 
408     return u==length;
409 }
410 
411 /*! ZDICT_tryMerge() :
412     check if dictItem can be merged, do it if possible
413     @return : id of destination elt, 0 if not merged
414 */
ZDICT_tryMerge(dictItem * table,dictItem elt,U32 eltNbToSkip,const void * buffer)415 static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
416 {
417     const U32 tableSize = table->pos;
418     const U32 eltEnd = elt.pos + elt.length;
419     const char* const buf = (const char*) buffer;
420 
421     /* tail overlap */
422     U32 u; for (u=1; u<tableSize; u++) {
423         if (u==eltNbToSkip) continue;
424         if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) {  /* overlap, existing > new */
425             /* append */
426             U32 const addedLength = table[u].pos - elt.pos;
427             table[u].length += addedLength;
428             table[u].pos = elt.pos;
429             table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
430             table[u].savings += elt.length / 8;    /* rough approx bonus */
431             elt = table[u];
432             /* sort : improve rank */
433             while ((u>1) && (table[u-1].savings < elt.savings))
434             table[u] = table[u-1], u--;
435             table[u] = elt;
436             return u;
437     }   }
438 
439     /* front overlap */
440     for (u=1; u<tableSize; u++) {
441         if (u==eltNbToSkip) continue;
442 
443         if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) {  /* overlap, existing < new */
444             /* append */
445             int const addedLength = (int)eltEnd - (table[u].pos + table[u].length);
446             table[u].savings += elt.length / 8;    /* rough approx bonus */
447             if (addedLength > 0) {   /* otherwise, elt fully included into existing */
448                 table[u].length += addedLength;
449                 table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
450             }
451             /* sort : improve rank */
452             elt = table[u];
453             while ((u>1) && (table[u-1].savings < elt.savings))
454                 table[u] = table[u-1], u--;
455             table[u] = elt;
456             return u;
457         }
458 
459         if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
460             if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
461                 size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
462                 table[u].pos = elt.pos;
463                 table[u].savings += (U32)(elt.savings * addedLength / elt.length);
464                 table[u].length = MIN(elt.length, table[u].length + 1);
465                 return u;
466             }
467         }
468     }
469 
470     return 0;
471 }
472 
473 
ZDICT_removeDictItem(dictItem * table,U32 id)474 static void ZDICT_removeDictItem(dictItem* table, U32 id)
475 {
476     /* convention : table[0].pos stores nb of elts */
477     U32 const max = table[0].pos;
478     U32 u;
479     if (!id) return;   /* protection, should never happen */
480     for (u=id; u<max-1; u++)
481         table[u] = table[u+1];
482     table->pos--;
483 }
484 
485 
ZDICT_insertDictItem(dictItem * table,U32 maxSize,dictItem elt,const void * buffer)486 static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
487 {
488     /* merge if possible */
489     U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
490     if (mergeId) {
491         U32 newMerge = 1;
492         while (newMerge) {
493             newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
494             if (newMerge) ZDICT_removeDictItem(table, mergeId);
495             mergeId = newMerge;
496         }
497         return;
498     }
499 
500     /* insert */
501     {   U32 current;
502         U32 nextElt = table->pos;
503         if (nextElt >= maxSize) nextElt = maxSize-1;
504         current = nextElt-1;
505         while (table[current].savings < elt.savings) {
506             table[current+1] = table[current];
507             current--;
508         }
509         table[current+1] = elt;
510         table->pos = nextElt+1;
511     }
512 }
513 
514 
ZDICT_dictSize(const dictItem * dictList)515 static U32 ZDICT_dictSize(const dictItem* dictList)
516 {
517     U32 u, dictSize = 0;
518     for (u=1; u<dictList[0].pos; u++)
519         dictSize += dictList[u].length;
520     return dictSize;
521 }
522 
523 
ZDICT_trainBuffer_legacy(dictItem * dictList,U32 dictListSize,const void * const buffer,size_t bufferSize,const size_t * fileSizes,unsigned nbFiles,unsigned minRatio,U32 notificationLevel)524 static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
525                             const void* const buffer, size_t bufferSize,   /* buffer must end with noisy guard band */
526                             const size_t* fileSizes, unsigned nbFiles,
527                             unsigned minRatio, U32 notificationLevel)
528 {
529     int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
530     int* const suffix = suffix0+1;
531     U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
532     BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks));   /* +16 for overflow security */
533     U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
534     size_t result = 0;
535     clock_t displayClock = 0;
536     clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
537 
538 #   undef  DISPLAYUPDATE
539 #   define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
540             if (ZDICT_clockSpan(displayClock) > refreshRate)  \
541             { displayClock = clock(); DISPLAY(__VA_ARGS__); \
542             if (notificationLevel>=4) fflush(stderr); } }
543 
544     /* init */
545     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
546     if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
547         result = ERROR(memory_allocation);
548         goto _cleanup;
549     }
550     if (minRatio < MINRATIO) minRatio = MINRATIO;
551     memset(doneMarks, 0, bufferSize+16);
552 
553     /* limit sample set size (divsufsort limitation)*/
554     if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
555     while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
556 
557     /* sort */
558     DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
559     {   int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
560         if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
561     }
562     suffix[bufferSize] = (int)bufferSize;   /* leads into noise */
563     suffix0[0] = (int)bufferSize;           /* leads into noise */
564     /* build reverse suffix sort */
565     {   size_t pos;
566         for (pos=0; pos < bufferSize; pos++)
567             reverseSuffix[suffix[pos]] = (U32)pos;
568         /* note filePos tracks borders between samples.
569            It's not used at this stage, but planned to become useful in a later update */
570         filePos[0] = 0;
571         for (pos=1; pos<nbFiles; pos++)
572             filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
573     }
574 
575     DISPLAYLEVEL(2, "finding patterns ... \n");
576     DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
577 
578     {   U32 cursor; for (cursor=0; cursor < bufferSize; ) {
579             dictItem solution;
580             if (doneMarks[cursor]) { cursor++; continue; }
581             solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
582             if (solution.length==0) { cursor++; continue; }
583             ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
584             cursor += solution.length;
585             DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / bufferSize * 100);
586     }   }
587 
588 _cleanup:
589     free(suffix0);
590     free(reverseSuffix);
591     free(doneMarks);
592     free(filePos);
593     return result;
594 }
595 
596 
ZDICT_fillNoise(void * buffer,size_t length)597 static void ZDICT_fillNoise(void* buffer, size_t length)
598 {
599     unsigned const prime1 = 2654435761U;
600     unsigned const prime2 = 2246822519U;
601     unsigned acc = prime1;
602     size_t p=0;
603     for (p=0; p<length; p++) {
604         acc *= prime2;
605         ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
606     }
607 }
608 
609 
610 typedef struct
611 {
612     ZSTD_CDict* dict;    /* dictionary */
613     ZSTD_CCtx* zc;     /* working context */
614     void* workPlace;   /* must be ZSTD_BLOCKSIZE_MAX allocated */
615 } EStats_ress_t;
616 
617 #define MAXREPOFFSET 1024
618 
ZDICT_countEStats(EStats_ress_t esr,const ZSTD_parameters * params,unsigned * countLit,unsigned * offsetcodeCount,unsigned * matchlengthCount,unsigned * litlengthCount,U32 * repOffsets,const void * src,size_t srcSize,U32 notificationLevel)619 static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,
620                               unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
621                               const void* src, size_t srcSize,
622                               U32 notificationLevel)
623 {
624     size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
625     size_t cSize;
626 
627     if (srcSize > blockSizeMax) srcSize = blockSizeMax;   /* protection vs large samples */
628     {   size_t const errorCode = ZSTD_compressBegin_usingCDict(esr.zc, esr.dict);
629         if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
630 
631     }
632     cSize = ZSTD_compressBlock(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
633     if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
634 
635     if (cSize) {  /* if == 0; block is not compressible */
636         const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
637 
638         /* literals stats */
639         {   const BYTE* bytePtr;
640             for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
641                 countLit[*bytePtr]++;
642         }
643 
644         /* seqStats */
645         {   U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
646             ZSTD_seqToCodes(seqStorePtr);
647 
648             {   const BYTE* codePtr = seqStorePtr->ofCode;
649                 U32 u;
650                 for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
651             }
652 
653             {   const BYTE* codePtr = seqStorePtr->mlCode;
654                 U32 u;
655                 for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
656             }
657 
658             {   const BYTE* codePtr = seqStorePtr->llCode;
659                 U32 u;
660                 for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
661             }
662 
663             if (nbSeq >= 2) { /* rep offsets */
664                 const seqDef* const seq = seqStorePtr->sequencesStart;
665                 U32 offset1 = seq[0].offset - 3;
666                 U32 offset2 = seq[1].offset - 3;
667                 if (offset1 >= MAXREPOFFSET) offset1 = 0;
668                 if (offset2 >= MAXREPOFFSET) offset2 = 0;
669                 repOffsets[offset1] += 3;
670                 repOffsets[offset2] += 1;
671     }   }   }
672 }
673 
ZDICT_totalSampleSize(const size_t * fileSizes,unsigned nbFiles)674 static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
675 {
676     size_t total=0;
677     unsigned u;
678     for (u=0; u<nbFiles; u++) total += fileSizes[u];
679     return total;
680 }
681 
682 typedef struct { U32 offset; U32 count; } offsetCount_t;
683 
ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1],U32 val,U32 count)684 static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
685 {
686     U32 u;
687     table[ZSTD_REP_NUM].offset = val;
688     table[ZSTD_REP_NUM].count = count;
689     for (u=ZSTD_REP_NUM; u>0; u--) {
690         offsetCount_t tmp;
691         if (table[u-1].count >= table[u].count) break;
692         tmp = table[u-1];
693         table[u-1] = table[u];
694         table[u] = tmp;
695     }
696 }
697 
698 /* ZDICT_flatLit() :
699  * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
700  * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
701  */
ZDICT_flatLit(unsigned * countLit)702 static void ZDICT_flatLit(unsigned* countLit)
703 {
704     int u;
705     for (u=1; u<256; u++) countLit[u] = 2;
706     countLit[0]   = 4;
707     countLit[253] = 1;
708     countLit[254] = 1;
709 }
710 
711 #define OFFCODE_MAX 30  /* only applicable to first block */
ZDICT_analyzeEntropy(void * dstBuffer,size_t maxDstSize,int compressionLevel,const void * srcBuffer,const size_t * fileSizes,unsigned nbFiles,const void * dictBuffer,size_t dictBufferSize,unsigned notificationLevel)712 static size_t ZDICT_analyzeEntropy(void*  dstBuffer, size_t maxDstSize,
713                                    int compressionLevel,
714                              const void*  srcBuffer, const size_t* fileSizes, unsigned nbFiles,
715                              const void* dictBuffer, size_t  dictBufferSize,
716                                    unsigned notificationLevel)
717 {
718     unsigned countLit[256];
719     HUF_CREATE_STATIC_CTABLE(hufTable, 255);
720     unsigned offcodeCount[OFFCODE_MAX+1];
721     short offcodeNCount[OFFCODE_MAX+1];
722     U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
723     unsigned matchLengthCount[MaxML+1];
724     short matchLengthNCount[MaxML+1];
725     unsigned litLengthCount[MaxLL+1];
726     short litLengthNCount[MaxLL+1];
727     U32 repOffset[MAXREPOFFSET];
728     offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
729     EStats_ress_t esr = { NULL, NULL, NULL };
730     ZSTD_parameters params;
731     U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
732     size_t pos = 0, errorCode;
733     size_t eSize = 0;
734     size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
735     size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
736     BYTE* dstPtr = (BYTE*)dstBuffer;
737 
738     /* init */
739     DEBUGLOG(4, "ZDICT_analyzeEntropy");
740     if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; }   /* too large dictionary */
741     for (u=0; u<256; u++) countLit[u] = 1;   /* any character must be described */
742     for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
743     for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
744     for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
745     memset(repOffset, 0, sizeof(repOffset));
746     repOffset[1] = repOffset[4] = repOffset[8] = 1;
747     memset(bestRepOffset, 0, sizeof(bestRepOffset));
748     if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;
749     params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
750 
751     esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
752     esr.zc = ZSTD_createCCtx();
753     esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
754     if (!esr.dict || !esr.zc || !esr.workPlace) {
755         eSize = ERROR(memory_allocation);
756         DISPLAYLEVEL(1, "Not enough memory \n");
757         goto _cleanup;
758     }
759 
760     /* collect stats on all samples */
761     for (u=0; u<nbFiles; u++) {
762         ZDICT_countEStats(esr, &params,
763                           countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
764                          (const char*)srcBuffer + pos, fileSizes[u],
765                           notificationLevel);
766         pos += fileSizes[u];
767     }
768 
769     /* analyze, build stats, starting with literals */
770     {   size_t maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
771         if (HUF_isError(maxNbBits)) {
772             eSize = maxNbBits;
773             DISPLAYLEVEL(1, " HUF_buildCTable error \n");
774             goto _cleanup;
775         }
776         if (maxNbBits==8) {  /* not compressible : will fail on HUF_writeCTable() */
777             DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
778             ZDICT_flatLit(countLit);  /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
779             maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
780             assert(maxNbBits==9);
781         }
782         huffLog = (U32)maxNbBits;
783     }
784 
785     /* looking for most common first offsets */
786     {   U32 offset;
787         for (offset=1; offset<MAXREPOFFSET; offset++)
788             ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
789     }
790     /* note : the result of this phase should be used to better appreciate the impact on statistics */
791 
792     total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
793     errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);
794     if (FSE_isError(errorCode)) {
795         eSize = errorCode;
796         DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
797         goto _cleanup;
798     }
799     Offlog = (U32)errorCode;
800 
801     total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
802     errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);
803     if (FSE_isError(errorCode)) {
804         eSize = errorCode;
805         DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
806         goto _cleanup;
807     }
808     mlLog = (U32)errorCode;
809 
810     total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
811     errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);
812     if (FSE_isError(errorCode)) {
813         eSize = errorCode;
814         DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
815         goto _cleanup;
816     }
817     llLog = (U32)errorCode;
818 
819     /* write result to buffer */
820     {   size_t const hhSize = HUF_writeCTable(dstPtr, maxDstSize, hufTable, 255, huffLog);
821         if (HUF_isError(hhSize)) {
822             eSize = hhSize;
823             DISPLAYLEVEL(1, "HUF_writeCTable error \n");
824             goto _cleanup;
825         }
826         dstPtr += hhSize;
827         maxDstSize -= hhSize;
828         eSize += hhSize;
829     }
830 
831     {   size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
832         if (FSE_isError(ohSize)) {
833             eSize = ohSize;
834             DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
835             goto _cleanup;
836         }
837         dstPtr += ohSize;
838         maxDstSize -= ohSize;
839         eSize += ohSize;
840     }
841 
842     {   size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
843         if (FSE_isError(mhSize)) {
844             eSize = mhSize;
845             DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
846             goto _cleanup;
847         }
848         dstPtr += mhSize;
849         maxDstSize -= mhSize;
850         eSize += mhSize;
851     }
852 
853     {   size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
854         if (FSE_isError(lhSize)) {
855             eSize = lhSize;
856             DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
857             goto _cleanup;
858         }
859         dstPtr += lhSize;
860         maxDstSize -= lhSize;
861         eSize += lhSize;
862     }
863 
864     if (maxDstSize<12) {
865         eSize = ERROR(dstSize_tooSmall);
866         DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
867         goto _cleanup;
868     }
869 # if 0
870     MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
871     MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
872     MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
873 #else
874     /* at this stage, we don't use the result of "most common first offset",
875        as the impact of statistics is not properly evaluated */
876     MEM_writeLE32(dstPtr+0, repStartValue[0]);
877     MEM_writeLE32(dstPtr+4, repStartValue[1]);
878     MEM_writeLE32(dstPtr+8, repStartValue[2]);
879 #endif
880     eSize += 12;
881 
882 _cleanup:
883     ZSTD_freeCDict(esr.dict);
884     ZSTD_freeCCtx(esr.zc);
885     free(esr.workPlace);
886 
887     return eSize;
888 }
889 
890 
891 
ZDICT_finalizeDictionary(void * dictBuffer,size_t dictBufferCapacity,const void * customDictContent,size_t dictContentSize,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_params_t params)892 size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
893                           const void* customDictContent, size_t dictContentSize,
894                           const void* samplesBuffer, const size_t* samplesSizes,
895                           unsigned nbSamples, ZDICT_params_t params)
896 {
897     size_t hSize;
898 #define HBUFFSIZE 256   /* should prove large enough for all entropy headers */
899     BYTE header[HBUFFSIZE];
900     int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
901     U32 const notificationLevel = params.notificationLevel;
902 
903     /* check conditions */
904     DEBUGLOG(4, "ZDICT_finalizeDictionary");
905     if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
906     if (dictContentSize < ZDICT_CONTENTSIZE_MIN) return ERROR(srcSize_wrong);
907     if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
908 
909     /* dictionary header */
910     MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
911     {   U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
912         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
913         U32 const dictID = params.dictID ? params.dictID : compliantID;
914         MEM_writeLE32(header+4, dictID);
915     }
916     hSize = 8;
917 
918     /* entropy tables */
919     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
920     DISPLAYLEVEL(2, "statistics ... \n");
921     {   size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
922                                   compressionLevel,
923                                   samplesBuffer, samplesSizes, nbSamples,
924                                   customDictContent, dictContentSize,
925                                   notificationLevel);
926         if (ZDICT_isError(eSize)) return eSize;
927         hSize += eSize;
928     }
929 
930     /* copy elements in final buffer ; note : src and dst buffer can overlap */
931     if (hSize + dictContentSize > dictBufferCapacity) dictContentSize = dictBufferCapacity - hSize;
932     {   size_t const dictSize = hSize + dictContentSize;
933         char* dictEnd = (char*)dictBuffer + dictSize;
934         memmove(dictEnd - dictContentSize, customDictContent, dictContentSize);
935         memcpy(dictBuffer, header, hSize);
936         return dictSize;
937     }
938 }
939 
940 
ZDICT_addEntropyTablesFromBuffer_advanced(void * dictBuffer,size_t dictContentSize,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_params_t params)941 static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
942         void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
943         const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
944         ZDICT_params_t params)
945 {
946     int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
947     U32 const notificationLevel = params.notificationLevel;
948     size_t hSize = 8;
949 
950     /* calculate entropy tables */
951     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
952     DISPLAYLEVEL(2, "statistics ... \n");
953     {   size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
954                                   compressionLevel,
955                                   samplesBuffer, samplesSizes, nbSamples,
956                                   (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
957                                   notificationLevel);
958         if (ZDICT_isError(eSize)) return eSize;
959         hSize += eSize;
960     }
961 
962     /* add dictionary header (after entropy tables) */
963     MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
964     {   U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
965         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
966         U32 const dictID = params.dictID ? params.dictID : compliantID;
967         MEM_writeLE32((char*)dictBuffer+4, dictID);
968     }
969 
970     if (hSize + dictContentSize < dictBufferCapacity)
971         memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
972     return MIN(dictBufferCapacity, hSize+dictContentSize);
973 }
974 
975 /*! ZDICT_trainFromBuffer_unsafe_legacy() :
976 *   Warning : `samplesBuffer` must be followed by noisy guard band !!!
977 *   @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
978 */
ZDICT_trainFromBuffer_unsafe_legacy(void * dictBuffer,size_t maxDictSize,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_legacy_params_t params)979 static size_t ZDICT_trainFromBuffer_unsafe_legacy(
980                             void* dictBuffer, size_t maxDictSize,
981                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
982                             ZDICT_legacy_params_t params)
983 {
984     U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
985     dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
986     unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
987     unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
988     size_t const targetDictSize = maxDictSize;
989     size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
990     size_t dictSize = 0;
991     U32 const notificationLevel = params.zParams.notificationLevel;
992 
993     /* checks */
994     if (!dictList) return ERROR(memory_allocation);
995     if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); }   /* requested dictionary size is too small */
996     if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* not enough source to create dictionary */
997 
998     /* init */
999     ZDICT_initDictItem(dictList);
1000 
1001     /* build dictionary */
1002     ZDICT_trainBuffer_legacy(dictList, dictListSize,
1003                        samplesBuffer, samplesBuffSize,
1004                        samplesSizes, nbSamples,
1005                        minRep, notificationLevel);
1006 
1007     /* display best matches */
1008     if (params.zParams.notificationLevel>= 3) {
1009         unsigned const nb = MIN(25, dictList[0].pos);
1010         unsigned const dictContentSize = ZDICT_dictSize(dictList);
1011         unsigned u;
1012         DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
1013         DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
1014         for (u=1; u<nb; u++) {
1015             unsigned const pos = dictList[u].pos;
1016             unsigned const length = dictList[u].length;
1017             U32 const printedLength = MIN(40, length);
1018             if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
1019                 free(dictList);
1020                 return ERROR(GENERIC);   /* should never happen */
1021             }
1022             DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
1023                          u, length, pos, (unsigned)dictList[u].savings);
1024             ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
1025             DISPLAYLEVEL(3, "| \n");
1026     }   }
1027 
1028 
1029     /* create dictionary */
1030     {   unsigned dictContentSize = ZDICT_dictSize(dictList);
1031         if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* dictionary content too small */
1032         if (dictContentSize < targetDictSize/4) {
1033             DISPLAYLEVEL(2, "!  warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
1034             if (samplesBuffSize < 10 * targetDictSize)
1035                 DISPLAYLEVEL(2, "!  consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
1036             if (minRep > MINRATIO) {
1037                 DISPLAYLEVEL(2, "!  consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
1038                 DISPLAYLEVEL(2, "!  note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
1039             }
1040         }
1041 
1042         if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
1043             unsigned proposedSelectivity = selectivity-1;
1044             while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
1045             DISPLAYLEVEL(2, "!  note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
1046             DISPLAYLEVEL(2, "!  consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
1047             DISPLAYLEVEL(2, "!  always test dictionary efficiency on real samples \n");
1048         }
1049 
1050         /* limit dictionary size */
1051         {   U32 const max = dictList->pos;   /* convention : nb of useful elts within dictList */
1052             U32 currentSize = 0;
1053             U32 n; for (n=1; n<max; n++) {
1054                 currentSize += dictList[n].length;
1055                 if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
1056             }
1057             dictList->pos = n;
1058             dictContentSize = currentSize;
1059         }
1060 
1061         /* build dict content */
1062         {   U32 u;
1063             BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
1064             for (u=1; u<dictList->pos; u++) {
1065                 U32 l = dictList[u].length;
1066                 ptr -= l;
1067                 if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); }   /* should not happen */
1068                 memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
1069         }   }
1070 
1071         dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
1072                                                              samplesBuffer, samplesSizes, nbSamples,
1073                                                              params.zParams);
1074     }
1075 
1076     /* clean up */
1077     free(dictList);
1078     return dictSize;
1079 }
1080 
1081 
1082 /* ZDICT_trainFromBuffer_legacy() :
1083  * issue : samplesBuffer need to be followed by a noisy guard band.
1084  * work around : duplicate the buffer, and add the noise */
ZDICT_trainFromBuffer_legacy(void * dictBuffer,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_legacy_params_t params)1085 size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
1086                               const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
1087                               ZDICT_legacy_params_t params)
1088 {
1089     size_t result;
1090     void* newBuff;
1091     size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
1092     if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0;   /* not enough content => no dictionary */
1093 
1094     newBuff = malloc(sBuffSize + NOISELENGTH);
1095     if (!newBuff) return ERROR(memory_allocation);
1096 
1097     memcpy(newBuff, samplesBuffer, sBuffSize);
1098     ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH);   /* guard band, for end of buffer condition */
1099 
1100     result =
1101         ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
1102                                             samplesSizes, nbSamples, params);
1103     free(newBuff);
1104     return result;
1105 }
1106 
1107 
ZDICT_trainFromBuffer(void * dictBuffer,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples)1108 size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
1109                              const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
1110 {
1111     ZDICT_fastCover_params_t params;
1112     DEBUGLOG(3, "ZDICT_trainFromBuffer");
1113     memset(&params, 0, sizeof(params));
1114     params.d = 8;
1115     params.steps = 4;
1116     /* Use default level since no compression level information is available */
1117     params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
1118 #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
1119     params.zParams.notificationLevel = DEBUGLEVEL;
1120 #endif
1121     return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
1122                                                samplesBuffer, samplesSizes, nbSamples,
1123                                                &params);
1124 }
1125 
ZDICT_addEntropyTablesFromBuffer(void * dictBuffer,size_t dictContentSize,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples)1126 size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
1127                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
1128 {
1129     ZDICT_params_t params;
1130     memset(&params, 0, sizeof(params));
1131     return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
1132                                                      samplesBuffer, samplesSizes, nbSamples,
1133                                                      params);
1134 }
1135