Coverage Report

Created: 2024-09-08 06:32

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