Coverage Report

Created: 2026-11-12 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/dictBuilder/cover.c
Line
Count
Source
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
 * Constructs a dictionary using a heuristic based on the following paper:
13
 *
14
 * Liao, Petri, Moffat, Wirth
15
 * Effective Construction of Relative Lempel-Ziv Dictionaries
16
 * Published in WWW 2016.
17
 *
18
 * Adapted from code originally written by @ot (Giuseppe Ottaviano).
19
 ******************************************************************************/
20
21
/*-*************************************
22
*  Dependencies
23
***************************************/
24
/* qsort_r is an extension.
25
 *
26
 * Android NDK does not ship qsort_r().
27
 */
28
#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__CYGWIN__) || defined(__MSYS__)
29
# ifndef _GNU_SOURCE
30
#   define _GNU_SOURCE
31
# endif
32
#endif
33
34
#define __STDC_WANT_LIB_EXT1__ 1 /* request C11 Annex K, which includes qsort_s() */
35
36
#include <stdio.h>  /* fprintf */
37
#include <stdlib.h> /* malloc, free, qsort_r */
38
39
#include <string.h> /* memset */
40
#include <time.h>   /* clock */
41
42
#ifndef ZDICT_STATIC_LINKING_ONLY
43
#  define ZDICT_STATIC_LINKING_ONLY
44
#endif
45
46
#include "../common/debug.h" /* DEBUG_STATIC_ASSERT */
47
#include "../common/mem.h" /* read */
48
#include "../common/pool.h" /* POOL_ctx */
49
#include "../common/threading.h" /* ZSTD_pthread_mutex_t */
50
#include "../common/zstd_internal.h" /* includes zstd.h */
51
#include "../common/bits.h" /* ZSTD_highbit32 */
52
#include "../zdict.h"
53
#include "cover.h"
54
55
/*-*************************************
56
*  Constants
57
***************************************/
58
/**
59
* There are 32bit indexes used to ref samples, so limit samples size to 4GB
60
* on 64bit builds.
61
* For 32bit builds we choose 1 GB.
62
* Most 32bit platforms have 2GB user-mode addressable space and we allocate a large
63
* contiguous buffer, so 1GB is already a high limit.
64
*/
65
0
#define COVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB))
66
0
#define COVER_DEFAULT_SPLITPOINT 1.0
67
68
/**
69
 * Select the qsort() variant used by cover
70
 */
71
#define ZDICT_QSORT_MIN 0
72
#define ZDICT_QSORT_C90 ZDICT_QSORT_MIN
73
#define ZDICT_QSORT_GNU 1
74
#define ZDICT_QSORT_APPLE 2
75
#define ZDICT_QSORT_MSVC 3
76
#define ZDICT_QSORT_C11 ZDICT_QSORT_MAX
77
#define ZDICT_QSORT_MAX 4
78
79
#ifndef ZDICT_QSORT
80
# if defined(__APPLE__)
81
#   define ZDICT_QSORT ZDICT_QSORT_APPLE /* uses qsort_r() with a different order for parameters */
82
# elif (defined(__linux__) && !defined(__ANDROID__)) || defined(__CYGWIN__) || defined(__MSYS__)
83
#   define ZDICT_QSORT ZDICT_QSORT_GNU /* uses qsort_r() */
84
# elif defined(_WIN32) && defined(_MSC_VER)
85
#   define ZDICT_QSORT ZDICT_QSORT_MSVC /* uses qsort_s() with a different order for parameters */
86
# elif defined(STDC_LIB_EXT1) && (STDC_LIB_EXT1 > 0) /* C11 Annex K */
87
#   define ZDICT_QSORT ZDICT_QSORT_C11 /* uses qsort_s() */
88
# else
89
#   define ZDICT_QSORT ZDICT_QSORT_C90 /* uses standard qsort() which is not re-entrant (requires global variable) */
90
# endif
91
#endif
92
93
94
/*-*************************************
95
*  Console display
96
*
97
* Captures the `displayLevel` variable in the local scope.
98
***************************************/
99
#undef  DISPLAY
100
#define DISPLAY(...)                                                           \
101
0
  {                                                                            \
102
0
    fprintf(stderr, __VA_ARGS__);                                              \
103
0
    fflush(stderr);                                                            \
104
0
  }
105
#undef  DISPLAYLEVEL
106
#define DISPLAYLEVEL(l, ...)                                                   \
107
0
  if (displayLevel >= l) {                                                     \
108
0
    DISPLAY(__VA_ARGS__);                                                      \
109
0
  } /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
110
111
#undef  DISPLAYUPDATE
112
#define DISPLAYUPDATE(lastUpdateTime, l, ...)                                  \
113
0
  if (displayLevel >= l) {                                                     \
114
0
    const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100;                     \
115
0
    if ((clock() - lastUpdateTime > refreshRate) || (displayLevel >= 4)) {     \
116
0
      lastUpdateTime = clock();                                                \
117
0
      DISPLAY(__VA_ARGS__);                                                    \
118
0
    }                                                                          \
119
0
  }
120
121
/*-*************************************
122
* Hash table
123
***************************************
124
* A small specialized hash map for storing activeDmers.
125
* The map does not resize, so if it becomes full it will loop forever.
126
* Thus, the map must be large enough to store every value.
127
* The map implements linear probing and keeps its load less than 0.5.
128
*/
129
130
0
#define MAP_EMPTY_VALUE ((U32)-1)
131
typedef struct COVER_map_pair_t_s {
132
  U32 key;
133
  U32 value;
134
} COVER_map_pair_t;
135
136
typedef struct COVER_map_s {
137
  COVER_map_pair_t *data;
138
  U32 sizeLog;
139
  U32 size;
140
  U32 sizeMask;
141
} COVER_map_t;
142
143
/**
144
 * Clear the map.
145
 */
146
0
static void COVER_map_clear(COVER_map_t *map) {
147
0
  memset(map->data, MAP_EMPTY_VALUE, map->size * sizeof(COVER_map_pair_t));
148
0
}
149
150
/**
151
 * Initializes a map of the given size.
152
 * Returns 1 on success and 0 on failure.
153
 * The map must be destroyed with COVER_map_destroy().
154
 * The map is only guaranteed to be large enough to hold size elements.
155
 */
156
0
static int COVER_map_init(COVER_map_t *map, U32 size) {
157
0
  map->sizeLog = ZSTD_highbit32(size) + 2;
158
0
  map->size = (U32)1 << map->sizeLog;
159
0
  map->sizeMask = map->size - 1;
160
0
  map->data = (COVER_map_pair_t *)malloc(map->size * sizeof(COVER_map_pair_t));
161
0
  if (!map->data) {
162
0
    map->sizeLog = 0;
163
0
    map->size = 0;
164
0
    return 0;
165
0
  }
166
0
  COVER_map_clear(map);
167
0
  return 1;
168
0
}
169
170
/**
171
 * Internal hash function
172
 */
173
static const U32 COVER_prime4bytes = 2654435761U;
174
0
static U32 COVER_map_hash(COVER_map_t *map, U32 key) {
175
0
  return (key * COVER_prime4bytes) >> (32 - map->sizeLog);
176
0
}
177
178
/**
179
 * Helper function that returns the index that a key should be placed into.
180
 */
181
0
static U32 COVER_map_index(COVER_map_t *map, U32 key) {
182
0
  const U32 hash = COVER_map_hash(map, key);
183
0
  U32 i;
184
0
  for (i = hash;; i = (i + 1) & map->sizeMask) {
185
0
    COVER_map_pair_t *pos = &map->data[i];
186
0
    if (pos->value == MAP_EMPTY_VALUE) {
187
0
      return i;
188
0
    }
189
0
    if (pos->key == key) {
190
0
      return i;
191
0
    }
192
0
  }
193
0
}
194
195
/**
196
 * Returns the pointer to the value for key.
197
 * If key is not in the map, it is inserted and the value is set to 0.
198
 * The map must not be full.
199
 */
200
0
static U32 *COVER_map_at(COVER_map_t *map, U32 key) {
201
0
  COVER_map_pair_t *pos = &map->data[COVER_map_index(map, key)];
202
0
  if (pos->value == MAP_EMPTY_VALUE) {
203
0
    pos->key = key;
204
0
    pos->value = 0;
205
0
  }
206
0
  return &pos->value;
207
0
}
208
209
/**
210
 * Deletes key from the map if present.
211
 */
212
0
static void COVER_map_remove(COVER_map_t *map, U32 key) {
213
0
  U32 i = COVER_map_index(map, key);
214
0
  COVER_map_pair_t* del = &map->data[i];
215
0
  U32 shift = 1;
216
0
  if (del->value == MAP_EMPTY_VALUE) {
217
0
    return;
218
0
  }
219
0
  for (i = (i + 1) & map->sizeMask;; i = (i + 1) & map->sizeMask) {
220
0
    COVER_map_pair_t *const pos = &map->data[i];
221
    /* If the position is empty we are done */
222
0
    if (pos->value == MAP_EMPTY_VALUE) {
223
0
      del->value = MAP_EMPTY_VALUE;
224
0
      return;
225
0
    }
226
    /* If pos can be moved to del do so */
227
0
    if (((i - COVER_map_hash(map, pos->key)) & map->sizeMask) >= shift) {
228
0
      del->key = pos->key;
229
0
      del->value = pos->value;
230
0
      del = pos;
231
0
      shift = 1;
232
0
    } else {
233
0
      ++shift;
234
0
    }
235
0
  }
236
0
}
237
238
/**
239
 * Destroys a map that is inited with COVER_map_init().
240
 */
241
0
static void COVER_map_destroy(COVER_map_t *map) {
242
0
  if (map->data) {
243
0
    free(map->data);
244
0
  }
245
0
  map->data = NULL;
246
0
  map->size = 0;
247
0
}
248
249
/*-*************************************
250
* Context
251
***************************************/
252
253
typedef struct {
254
  const BYTE *samples;
255
  size_t *offsets;
256
  const size_t *samplesSizes;
257
  size_t nbSamples;
258
  size_t nbTrainSamples;
259
  size_t nbTestSamples;
260
  U32 *suffix;
261
  size_t suffixSize;
262
  U32 *freqs;
263
  U32 *dmerAt;
264
  unsigned d;
265
  int displayLevel;
266
} COVER_ctx_t;
267
268
#if ZDICT_QSORT == ZDICT_QSORT_C90
269
/* Use global context for non-reentrant sort functions */
270
static COVER_ctx_t *g_coverCtx = NULL;
271
#endif
272
273
/*-*************************************
274
*  Helper functions
275
***************************************/
276
277
/**
278
 * Returns the sum of the sample sizes.
279
 */
280
0
size_t COVER_sum(const size_t *samplesSizes, unsigned nbSamples) {
281
0
  size_t sum = 0;
282
0
  unsigned i;
283
0
  for (i = 0; i < nbSamples; ++i) {
284
0
    sum += samplesSizes[i];
285
0
  }
286
0
  return sum;
287
0
}
288
289
/**
290
 * Returns -1 if the dmer at lp is less than the dmer at rp.
291
 * Return 0 if the dmers at lp and rp are equal.
292
 * Returns 1 if the dmer at lp is greater than the dmer at rp.
293
 */
294
0
static int COVER_cmp(COVER_ctx_t *ctx, const void *lp, const void *rp) {
295
0
  U32 const lhs = *(U32 const *)lp;
296
0
  U32 const rhs = *(U32 const *)rp;
297
0
  return memcmp(ctx->samples + lhs, ctx->samples + rhs, ctx->d);
298
0
}
299
/**
300
 * Faster version for d <= 8.
301
 */
302
0
static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) {
303
0
  U64 const mask = (ctx->d == 8) ? (U64)-1 : (((U64)1 << (8 * ctx->d)) - 1);
304
0
  U64 const lhs = MEM_readLE64(ctx->samples + *(U32 const *)lp) & mask;
305
0
  U64 const rhs = MEM_readLE64(ctx->samples + *(U32 const *)rp) & mask;
306
0
  if (lhs < rhs) {
307
0
    return -1;
308
0
  }
309
0
  return (lhs > rhs);
310
0
}
311
312
/**
313
 * Same as COVER_cmp() except ties are broken by the position each element holds
314
 */
315
#if (ZDICT_QSORT == ZDICT_QSORT_MSVC) || (ZDICT_QSORT == ZDICT_QSORT_APPLE)
316
static int WIN_CDECL COVER_strict_cmp(void* g_coverCtx, const void* lp, const void* rp) {
317
#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) || (ZDICT_QSORT == ZDICT_QSORT_C11)
318
0
static int COVER_strict_cmp(const void *lp, const void *rp, void *g_coverCtx) {
319
#else /* C90 fallback.*/
320
static int COVER_strict_cmp(const void *lp, const void *rp) {
321
#endif
322
0
  int result = COVER_cmp((COVER_ctx_t*)g_coverCtx, lp, rp);
323
0
  if (result == 0) {
324
0
    U32 const lpos = *(const U32 *)lp;
325
0
    U32 const rpos = *(const U32 *)rp;
326
0
    result = (lpos < rpos) ? -1 : (lpos > rpos) ? 1 : 0;
327
0
  }
328
0
  return result;
329
0
}
330
/**
331
 * Faster version for d <= 8.
332
 */
333
#if (ZDICT_QSORT == ZDICT_QSORT_MSVC) || (ZDICT_QSORT == ZDICT_QSORT_APPLE)
334
static int WIN_CDECL COVER_strict_cmp8(void* g_coverCtx, const void* lp, const void* rp) {
335
#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) || (ZDICT_QSORT == ZDICT_QSORT_C11)
336
0
static int COVER_strict_cmp8(const void *lp, const void *rp, void *g_coverCtx) {
337
#else /* C90 fallback.*/
338
static int COVER_strict_cmp8(const void *lp, const void *rp) {
339
#endif
340
0
  int result = COVER_cmp8((COVER_ctx_t*)g_coverCtx, lp, rp);
341
0
  if (result == 0) {
342
0
    U32 const lpos = *(const U32 *)lp;
343
0
    U32 const rpos = *(const U32 *)rp;
344
0
    result = (lpos < rpos) ? -1 : (lpos > rpos) ? 1 : 0;
345
0
  }
346
0
  return result;
347
0
}
348
349
/**
350
 * Abstract away divergence of qsort_r() parameters.
351
 * Hopefully when C11 become the norm, we will be able
352
 * to clean it up.
353
 */
354
static void stableSort(COVER_ctx_t *ctx)
355
0
{
356
0
    DEBUG_STATIC_ASSERT(ZDICT_QSORT_MIN <= ZDICT_QSORT && ZDICT_QSORT <= ZDICT_QSORT_MAX);
357
#if (ZDICT_QSORT == ZDICT_QSORT_APPLE)
358
    qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32),
359
            ctx,
360
            (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
361
#elif (ZDICT_QSORT == ZDICT_QSORT_GNU)
362
    qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32),
363
0
            (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp),
364
0
            ctx);
365
#elif (ZDICT_QSORT == ZDICT_QSORT_MSVC)
366
    qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32),
367
            (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp),
368
            ctx);
369
#elif (ZDICT_QSORT == ZDICT_QSORT_C11)
370
    qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32),
371
            (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp),
372
            ctx);
373
#else /* C90 fallback.*/
374
    g_coverCtx = ctx;
375
    /* TODO(cavalcanti): implement a reentrant qsort() when _r is not available. */
376
    qsort(ctx->suffix, ctx->suffixSize, sizeof(U32),
377
          (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
378
#endif
379
0
}
380
381
/**
382
 * Returns the first pointer in [first, last) whose element does not compare
383
 * less than value.  If no such element exists it returns last.
384
 */
385
static const size_t *COVER_lower_bound(const size_t* first, const size_t* last,
386
0
                                       size_t value) {
387
0
  size_t count = (size_t)(last - first);
388
0
  assert(last >= first);
389
0
  while (count != 0) {
390
0
    size_t step = count / 2;
391
0
    const size_t *ptr = first;
392
0
    ptr += step;
393
0
    if (*ptr < value) {
394
0
      first = ++ptr;
395
0
      count -= step + 1;
396
0
    } else {
397
0
      count = step;
398
0
    }
399
0
  }
400
0
  return first;
401
0
}
402
403
/**
404
 * Generic groupBy function.
405
 * Groups an array sorted by cmp into groups with equivalent values.
406
 * Calls grp for each group.
407
 */
408
static void
409
COVER_groupBy(const void *data, size_t count, size_t size, COVER_ctx_t *ctx,
410
              int (*cmp)(COVER_ctx_t *, const void *, const void *),
411
0
              void (*grp)(COVER_ctx_t *, const void *, const void *)) {
412
0
  const BYTE *ptr = (const BYTE *)data;
413
0
  size_t num = 0;
414
0
  while (num < count) {
415
0
    const BYTE *grpEnd = ptr + size;
416
0
    ++num;
417
0
    while (num < count && cmp(ctx, ptr, grpEnd) == 0) {
418
0
      grpEnd += size;
419
0
      ++num;
420
0
    }
421
0
    grp(ctx, ptr, grpEnd);
422
0
    ptr = grpEnd;
423
0
  }
424
0
}
425
426
/*-*************************************
427
*  Cover functions
428
***************************************/
429
430
/**
431
 * Called on each group of positions with the same dmer.
432
 * Counts the frequency of each dmer and saves it in the suffix array.
433
 * Fills `ctx->dmerAt`.
434
 */
435
static void COVER_group(COVER_ctx_t *ctx, const void *group,
436
0
                        const void *groupEnd) {
437
  /* The group consists of all the positions with the same first d bytes. */
438
0
  const U32 *grpPtr = (const U32 *)group;
439
0
  const U32 *grpEnd = (const U32 *)groupEnd;
440
  /* The dmerId is how we will reference this dmer.
441
   * This allows us to map the whole dmer space to a much smaller space, the
442
   * size of the suffix array.
443
   */
444
0
  const U32 dmerId = (U32)(grpPtr - ctx->suffix);
445
  /* Count the number of samples this dmer shows up in */
446
0
  U32 freq = 0;
447
  /* Details */
448
0
  const size_t *curOffsetPtr = ctx->offsets;
449
0
  const size_t *offsetsEnd = ctx->offsets + ctx->nbSamples;
450
  /* Once *grpPtr >= curSampleEnd this occurrence of the dmer is in a
451
   * different sample than the last.
452
   */
453
0
  size_t curSampleEnd = ctx->offsets[0];
454
0
  for (; grpPtr != grpEnd; ++grpPtr) {
455
    /* Save the dmerId for this position so we can get back to it. */
456
0
    ctx->dmerAt[*grpPtr] = dmerId;
457
    /* Dictionaries only help for the first reference to the dmer.
458
     * After that zstd can reference the match from the previous reference.
459
     * So only count each dmer once for each sample it is in.
460
     */
461
0
    if (*grpPtr < curSampleEnd) {
462
0
      continue;
463
0
    }
464
0
    freq += 1;
465
    /* Binary search to find the end of the sample *grpPtr is in.
466
     * In the common case that grpPtr + 1 == grpEnd we can skip the binary
467
     * search because the loop is over.
468
     */
469
0
    if (grpPtr + 1 != grpEnd) {
470
0
      const size_t *sampleEndPtr =
471
0
          COVER_lower_bound(curOffsetPtr, offsetsEnd, *grpPtr);
472
0
      curSampleEnd = *sampleEndPtr;
473
0
      curOffsetPtr = sampleEndPtr + 1;
474
0
    }
475
0
  }
476
  /* At this point we are never going to look at this segment of the suffix
477
   * array again.  We take advantage of this fact to save memory.
478
   * We store the frequency of the dmer in the first position of the group,
479
   * which is dmerId.
480
   */
481
0
  ctx->suffix[dmerId] = freq;
482
0
}
483
484
485
/**
486
 * Selects the best segment in an epoch.
487
 * Segments of are scored according to the function:
488
 *
489
 * Let F(d) be the frequency of dmer d.
490
 * Let S_i be the dmer at position i of segment S which has length k.
491
 *
492
 *     Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
493
 *
494
 * Once the dmer d is in the dictionary we set F(d) = 0.
495
 */
496
static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs,
497
                                           COVER_map_t *activeDmers, U32 begin,
498
                                           U32 end,
499
0
                                           ZDICT_cover_params_t parameters) {
500
  /* Constants */
501
0
  const U32 k = parameters.k;
502
0
  const U32 d = parameters.d;
503
0
  const U32 dmersInK = k - d + 1;
504
  /* Try each segment (activeSegment) and save the best (bestSegment) */
505
0
  COVER_segment_t bestSegment = {0, 0, 0};
506
0
  COVER_segment_t activeSegment;
507
  /* Reset the activeDmers in the segment */
508
0
  COVER_map_clear(activeDmers);
509
  /* The activeSegment starts at the beginning of the epoch. */
510
0
  activeSegment.begin = begin;
511
0
  activeSegment.end = begin;
512
0
  activeSegment.score = 0;
513
  /* Slide the activeSegment through the whole epoch.
514
   * Save the best segment in bestSegment.
515
   */
516
0
  while (activeSegment.end < end) {
517
    /* The dmerId for the dmer at the next position */
518
0
    U32 newDmer = ctx->dmerAt[activeSegment.end];
519
    /* The entry in activeDmers for this dmerId */
520
0
    U32 *newDmerOcc = COVER_map_at(activeDmers, newDmer);
521
    /* If the dmer isn't already present in the segment add its score. */
522
0
    if (*newDmerOcc == 0) {
523
      /* The paper suggest using the L-0.5 norm, but experiments show that it
524
       * doesn't help.
525
       */
526
0
      activeSegment.score += freqs[newDmer];
527
0
    }
528
    /* Add the dmer to the segment */
529
0
    activeSegment.end += 1;
530
0
    *newDmerOcc += 1;
531
532
    /* If the window is now too large, drop the first position */
533
0
    if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
534
0
      U32 delDmer = ctx->dmerAt[activeSegment.begin];
535
0
      U32 *delDmerOcc = COVER_map_at(activeDmers, delDmer);
536
0
      activeSegment.begin += 1;
537
0
      *delDmerOcc -= 1;
538
      /* If this is the last occurrence of the dmer, subtract its score */
539
0
      if (*delDmerOcc == 0) {
540
0
        COVER_map_remove(activeDmers, delDmer);
541
0
        activeSegment.score -= freqs[delDmer];
542
0
      }
543
0
    }
544
545
    /* If this segment is the best so far save it */
546
0
    if (activeSegment.score > bestSegment.score) {
547
0
      bestSegment = activeSegment;
548
0
    }
549
0
  }
550
0
  {
551
    /* Trim off the zero frequency head and tail from the segment. */
552
0
    U32 newBegin = bestSegment.end;
553
0
    U32 newEnd = bestSegment.begin;
554
0
    U32 pos;
555
0
    for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
556
0
      U32 freq = freqs[ctx->dmerAt[pos]];
557
0
      if (freq != 0) {
558
0
        newBegin = MIN(newBegin, pos);
559
0
        newEnd = pos + 1;
560
0
      }
561
0
    }
562
0
    bestSegment.begin = newBegin;
563
0
    bestSegment.end = newEnd;
564
0
  }
565
0
  {
566
    /* Zero out the frequency of each dmer covered by the chosen segment. */
567
0
    U32 pos;
568
0
    for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
569
0
      freqs[ctx->dmerAt[pos]] = 0;
570
0
    }
571
0
  }
572
0
  return bestSegment;
573
0
}
574
575
/**
576
 * Check the validity of the parameters.
577
 * Returns non-zero if the parameters are valid and 0 otherwise.
578
 */
579
static int COVER_checkParameters(ZDICT_cover_params_t parameters,
580
0
                                 size_t maxDictSize) {
581
  /* k and d are required parameters */
582
0
  if (parameters.d == 0 || parameters.k == 0) {
583
0
    return 0;
584
0
  }
585
  /* k <= maxDictSize */
586
0
  if (parameters.k > maxDictSize) {
587
0
    return 0;
588
0
  }
589
  /* d <= k */
590
0
  if (parameters.d > parameters.k) {
591
0
    return 0;
592
0
  }
593
  /* 0 < splitPoint <= 1 */
594
0
  if (parameters.splitPoint <= 0 || parameters.splitPoint > 1){
595
0
    return 0;
596
0
  }
597
0
  return 1;
598
0
}
599
600
/**
601
 * Clean up a context initialized with `COVER_ctx_init()`.
602
 */
603
0
static void COVER_ctx_destroy(COVER_ctx_t *ctx) {
604
0
  if (!ctx) {
605
0
    return;
606
0
  }
607
0
  if (ctx->suffix) {
608
0
    free(ctx->suffix);
609
0
    ctx->suffix = NULL;
610
0
  }
611
0
  if (ctx->freqs) {
612
0
    free(ctx->freqs);
613
0
    ctx->freqs = NULL;
614
0
  }
615
0
  if (ctx->dmerAt) {
616
0
    free(ctx->dmerAt);
617
0
    ctx->dmerAt = NULL;
618
0
  }
619
0
  if (ctx->offsets) {
620
0
    free(ctx->offsets);
621
0
    ctx->offsets = NULL;
622
0
  }
623
0
}
624
625
/**
626
 * Prepare a context for dictionary building.
627
 * The context is only dependent on the parameter `d` and can be used multiple
628
 * times.
629
 * Returns 0 on success or error code on error.
630
 * The context must be destroyed with `COVER_ctx_destroy()`.
631
 */
632
static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer,
633
                          const size_t *samplesSizes, unsigned nbSamples,
634
                          unsigned d, double splitPoint, int displayLevel)
635
0
{
636
0
  const BYTE *const samples = (const BYTE *)samplesBuffer;
637
0
  const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
638
  /* Split samples into testing and training sets */
639
0
  const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
640
0
  const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
641
0
  const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
642
0
  const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
643
0
  const size_t readLength = MAX(d, sizeof(U64));
644
0
  ctx->displayLevel = displayLevel;
645
  /* Checks */
646
0
  if (totalSamplesSize < readLength ||
647
0
      totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) {
648
0
    DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
649
0
                 (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20));
650
0
    return ERROR(srcSize_wrong);
651
0
  }
652
  /* The training set must be large enough for the partial suffix array, whose
653
   * size is `trainingSamplesSize - MAX(d, sizeof(U64)) + 1`. When splitPoint
654
   * < 1.0 the training set is a subset of the corpus, so it can be smaller
655
   * than the total even after the check above. Guard against the size_t
656
   * subtraction underflowing into a huge allocation. */
657
0
  if (trainingSamplesSize < MAX(d, sizeof(U64))) {
658
0
    DISPLAYLEVEL(1, "Training samples size is too small (%u), minimum size is %u\n",
659
0
                 (unsigned)trainingSamplesSize, (unsigned)MAX(d, sizeof(U64)));
660
0
    return ERROR(srcSize_wrong);
661
0
  }
662
  /* Check if there are at least 5 training samples */
663
0
  if (nbTrainSamples < 5) {
664
0
    DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples);
665
0
    return ERROR(srcSize_wrong);
666
0
  }
667
  /* Check if there's testing sample */
668
0
  if (nbTestSamples < 1) {
669
0
    DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.", nbTestSamples);
670
0
    return ERROR(srcSize_wrong);
671
0
  }
672
  /* Zero the context */
673
0
  memset(ctx, 0, sizeof(*ctx));
674
0
  DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
675
0
               (unsigned)trainingSamplesSize);
676
0
  DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
677
0
               (unsigned)testSamplesSize);
678
0
  ctx->samples = samples;
679
0
  ctx->samplesSizes = samplesSizes;
680
0
  ctx->nbSamples = nbSamples;
681
0
  ctx->nbTrainSamples = nbTrainSamples;
682
0
  ctx->nbTestSamples = nbTestSamples;
683
  /* Partial suffix array */
684
0
  ctx->suffixSize = trainingSamplesSize - readLength + 1;
685
0
  ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
686
  /* Maps index to the dmerID */
687
0
  ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
688
  /* The offsets of each file */
689
0
  ctx->offsets = (size_t *)malloc((nbSamples + 1) * sizeof(size_t));
690
0
  if (!ctx->suffix || !ctx->dmerAt || !ctx->offsets) {
691
0
    DISPLAYLEVEL(1, "Failed to allocate scratch buffers\n");
692
0
    COVER_ctx_destroy(ctx);
693
0
    return ERROR(memory_allocation);
694
0
  }
695
0
  ctx->freqs = NULL;
696
0
  ctx->d = d;
697
698
  /* Fill offsets from the samplesSizes */
699
0
  {
700
0
    U32 i;
701
0
    ctx->offsets[0] = 0;
702
0
    for (i = 1; i <= nbSamples; ++i) {
703
0
      ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
704
0
    }
705
0
  }
706
0
  DISPLAYLEVEL(2, "Constructing partial suffix array\n");
707
0
  {
708
    /* suffix is a partial suffix array.
709
     * It only sorts suffixes by their first parameters.d bytes.
710
     * Ties are broken by position, so each group is sorted by input position.
711
     */
712
0
    U32 i;
713
0
    for (i = 0; i < ctx->suffixSize; ++i) {
714
0
      ctx->suffix[i] = i;
715
0
    }
716
0
    stableSort(ctx);
717
0
  }
718
0
  DISPLAYLEVEL(2, "Computing frequencies\n");
719
  /* For each dmer group (group of positions with the same first d bytes):
720
   * 1. For each position we set dmerAt[position] = dmerID.  The dmerID is
721
   *    (groupBeginPtr - suffix).  This allows us to go from position to
722
   *    dmerID so we can look up values in freq.
723
   * 2. We calculate how many samples the dmer occurs in and save it in
724
   *    freqs[dmerId].
725
   */
726
0
  COVER_groupBy(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx,
727
0
                (ctx->d <= 8 ? &COVER_cmp8 : &COVER_cmp), &COVER_group);
728
0
  ctx->freqs = ctx->suffix;
729
0
  ctx->suffix = NULL;
730
0
  return 0;
731
0
}
732
733
void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLevel)
734
0
{
735
0
  const double ratio = (double)nbDmers / (double)maxDictSize;
736
0
  if (ratio >= 10) {
737
0
      return;
738
0
  }
739
0
  DISPLAYLEVEL(1,
740
0
               "WARNING: The maximum dictionary size %u is too large "
741
0
               "compared to the source size %u! "
742
0
               "size(source)/size(dictionary) = %f, but it should be >= "
743
0
               "10! This may lead to a subpar dictionary! We recommend "
744
0
               "training on sources at least 10x, and preferably 100x "
745
0
               "the size of the dictionary! \n", (U32)maxDictSize,
746
0
               (U32)nbDmers, ratio);
747
0
}
748
749
COVER_epoch_info_t COVER_computeEpochs(U32 maxDictSize,
750
                                       U32 nbDmers, U32 k, U32 passes)
751
0
{
752
0
  const U32 minEpochSize = k * 10;
753
0
  COVER_epoch_info_t epochs;
754
0
  epochs.num = MAX(1, maxDictSize / k / passes);
755
0
  epochs.size = nbDmers / epochs.num;
756
0
  if (epochs.size >= minEpochSize) {
757
0
      assert(epochs.size * epochs.num <= nbDmers);
758
0
      return epochs;
759
0
  }
760
0
  epochs.size = MIN(minEpochSize, nbDmers);
761
0
  epochs.num = nbDmers / epochs.size;
762
0
  assert(epochs.size * epochs.num <= nbDmers);
763
0
  return epochs;
764
0
}
765
766
/**
767
 * Given the prepared context build the dictionary.
768
 */
769
static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs,
770
                                    COVER_map_t *activeDmers, void *dictBuffer,
771
                                    size_t dictBufferCapacity,
772
0
                                    ZDICT_cover_params_t parameters) {
773
0
  BYTE *const dict = (BYTE *)dictBuffer;
774
0
  size_t tail = dictBufferCapacity;
775
  /* Divide the data into epochs. We will select one segment from each epoch. */
776
0
  const COVER_epoch_info_t epochs = COVER_computeEpochs(
777
0
      (U32)dictBufferCapacity, (U32)ctx->suffixSize, parameters.k, 4);
778
0
  const size_t maxZeroScoreRun = MAX(10, MIN(100, epochs.num >> 3));
779
0
  size_t zeroScoreRun = 0;
780
0
  size_t epoch;
781
0
  clock_t lastUpdateTime = 0;
782
0
  const int displayLevel = ctx->displayLevel;
783
0
  DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
784
0
                (U32)epochs.num, (U32)epochs.size);
785
  /* Loop through the epochs until there are no more segments or the dictionary
786
   * is full.
787
   */
788
0
  for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
789
0
    const U32 epochBegin = (U32)(epoch * epochs.size);
790
0
    const U32 epochEnd = epochBegin + epochs.size;
791
0
    size_t segmentSize;
792
    /* Select a segment */
793
0
    COVER_segment_t segment = COVER_selectSegment(
794
0
        ctx, freqs, activeDmers, epochBegin, epochEnd, parameters);
795
    /* If the segment covers no dmers, then we are out of content.
796
     * There may be new content in other epochs, for continue for some time.
797
     */
798
0
    if (segment.score == 0) {
799
0
      if (++zeroScoreRun >= maxZeroScoreRun) {
800
0
          break;
801
0
      }
802
0
      continue;
803
0
    }
804
0
    zeroScoreRun = 0;
805
    /* Trim the segment if necessary and if it is too small then we are done */
806
0
    segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
807
0
    if (segmentSize < parameters.d) {
808
0
      break;
809
0
    }
810
    /* We fill the dictionary from the back to allow the best segments to be
811
     * referenced with the smallest offsets.
812
     */
813
0
    tail -= segmentSize;
814
0
    memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
815
0
    DISPLAYUPDATE(
816
0
        lastUpdateTime,
817
0
        2, "\r%u%%       ",
818
0
        (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
819
0
  }
820
0
  DISPLAYLEVEL(2, "\r%79s\r", "");
821
0
  return tail;
822
0
}
823
824
ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover(
825
    void *dictBuffer, size_t dictBufferCapacity,
826
    const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
827
    ZDICT_cover_params_t parameters)
828
0
{
829
0
  BYTE* const dict = (BYTE*)dictBuffer;
830
0
  COVER_ctx_t ctx;
831
0
  COVER_map_t activeDmers;
832
0
  const int displayLevel = (int)parameters.zParams.notificationLevel;
833
0
  parameters.splitPoint = 1.0;
834
  /* Checks */
835
0
  if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
836
0
    DISPLAYLEVEL(1, "Cover parameters incorrect\n");
837
0
    return ERROR(parameter_outOfBound);
838
0
  }
839
0
  if (nbSamples == 0) {
840
0
    DISPLAYLEVEL(1, "Cover must have at least one input file\n");
841
0
    return ERROR(srcSize_wrong);
842
0
  }
843
0
  if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
844
0
    DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
845
0
                 ZDICT_DICTSIZE_MIN);
846
0
    return ERROR(dstSize_tooSmall);
847
0
  }
848
  /* Initialize context and activeDmers */
849
0
  {
850
0
    size_t const initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
851
0
                      parameters.d, parameters.splitPoint, displayLevel);
852
0
    if (ZSTD_isError(initVal)) {
853
0
      return initVal;
854
0
    }
855
0
  }
856
0
  COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel);
857
0
  if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
858
0
    DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
859
0
    COVER_ctx_destroy(&ctx);
860
0
    return ERROR(memory_allocation);
861
0
  }
862
863
0
  DISPLAYLEVEL(2, "Building dictionary\n");
864
0
  {
865
0
    const size_t tail =
866
0
        COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
867
0
                              dictBufferCapacity, parameters);
868
0
    const size_t dictionarySize = ZDICT_finalizeDictionary(
869
0
        dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
870
0
        samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
871
0
    if (!ZSTD_isError(dictionarySize)) {
872
0
      DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
873
0
                   (unsigned)dictionarySize);
874
0
    }
875
0
    COVER_ctx_destroy(&ctx);
876
0
    COVER_map_destroy(&activeDmers);
877
0
    return dictionarySize;
878
0
  }
879
0
}
880
881
882
883
size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters,
884
                                    const size_t *samplesSizes, const BYTE *samples,
885
                                    size_t *offsets,
886
                                    size_t nbTrainSamples, size_t nbSamples,
887
0
                                    BYTE *const dict, size_t dictBufferCapacity) {
888
0
  size_t totalCompressedSize = ERROR(GENERIC);
889
  /* Pointers */
890
0
  ZSTD_CCtx *cctx;
891
0
  ZSTD_CDict *cdict;
892
0
  void *dst;
893
  /* Local variables */
894
0
  size_t dstCapacity;
895
0
  size_t i;
896
  /* Allocate dst with enough space to compress the maximum sized sample */
897
0
  {
898
0
    size_t maxSampleSize = 0;
899
0
    i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
900
0
    for (; i < nbSamples; ++i) {
901
0
      maxSampleSize = MAX(samplesSizes[i], maxSampleSize);
902
0
    }
903
0
    dstCapacity = ZSTD_compressBound(maxSampleSize);
904
0
    dst = malloc(dstCapacity);
905
0
  }
906
  /* Create the cctx and cdict */
907
0
  cctx = ZSTD_createCCtx();
908
0
  cdict = ZSTD_createCDict(dict, dictBufferCapacity,
909
0
                           parameters.zParams.compressionLevel);
910
0
  if (!dst || !cctx || !cdict) {
911
0
    goto _compressCleanup;
912
0
  }
913
  /* Compress each sample and sum their sizes (or error) */
914
0
  totalCompressedSize = dictBufferCapacity;
915
0
  i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
916
0
  for (; i < nbSamples; ++i) {
917
0
    const size_t size = ZSTD_compress_usingCDict(
918
0
        cctx, dst, dstCapacity, samples + offsets[i],
919
0
        samplesSizes[i], cdict);
920
0
    if (ZSTD_isError(size)) {
921
0
      totalCompressedSize = size;
922
0
      goto _compressCleanup;
923
0
    }
924
0
    totalCompressedSize += size;
925
0
  }
926
0
_compressCleanup:
927
0
  ZSTD_freeCCtx(cctx);
928
0
  ZSTD_freeCDict(cdict);
929
0
  if (dst) {
930
0
    free(dst);
931
0
  }
932
0
  return totalCompressedSize;
933
0
}
934
935
936
/**
937
 * Initialize the `COVER_best_t`.
938
 */
939
0
void COVER_best_init(COVER_best_t *best) {
940
0
  if (best==NULL) return; /* compatible with init on NULL */
941
0
  (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);
942
0
  (void)ZSTD_pthread_cond_init(&best->cond, NULL);
943
0
  best->liveJobs = 0;
944
0
  best->dict = NULL;
945
0
  best->dictSize = 0;
946
0
  best->compressedSize = (size_t)-1;
947
0
  memset(&best->parameters, 0, sizeof(best->parameters));
948
0
}
949
950
/**
951
 * Wait until liveJobs == 0.
952
 */
953
0
void COVER_best_wait(COVER_best_t *best) {
954
0
  if (!best) {
955
0
    return;
956
0
  }
957
0
  ZSTD_pthread_mutex_lock(&best->mutex);
958
0
  while (best->liveJobs != 0) {
959
0
    ZSTD_pthread_cond_wait(&best->cond, &best->mutex);
960
0
  }
961
0
  ZSTD_pthread_mutex_unlock(&best->mutex);
962
0
}
963
964
/**
965
 * Call COVER_best_wait() and then destroy the COVER_best_t.
966
 */
967
0
void COVER_best_destroy(COVER_best_t *best) {
968
0
  if (!best) {
969
0
    return;
970
0
  }
971
0
  COVER_best_wait(best);
972
0
  if (best->dict) {
973
0
    free(best->dict);
974
0
  }
975
0
  ZSTD_pthread_mutex_destroy(&best->mutex);
976
0
  ZSTD_pthread_cond_destroy(&best->cond);
977
0
}
978
979
/**
980
 * Called when a thread is about to be launched.
981
 * Increments liveJobs.
982
 */
983
0
void COVER_best_start(COVER_best_t *best) {
984
0
  if (!best) {
985
0
    return;
986
0
  }
987
0
  ZSTD_pthread_mutex_lock(&best->mutex);
988
0
  ++best->liveJobs;
989
0
  ZSTD_pthread_mutex_unlock(&best->mutex);
990
0
}
991
992
/**
993
 * Called when a thread finishes executing, both on error or success.
994
 * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
995
 * If this dictionary is the best so far save it and its parameters.
996
 */
997
void COVER_best_finish(COVER_best_t* best,
998
                      ZDICT_cover_params_t parameters,
999
                      COVER_dictSelection_t selection)
1000
0
{
1001
0
  void* dict = selection.dictContent;
1002
0
  size_t compressedSize = selection.totalCompressedSize;
1003
0
  size_t dictSize = selection.dictSize;
1004
0
  if (!best) {
1005
0
    return;
1006
0
  }
1007
0
  {
1008
0
    size_t liveJobs;
1009
0
    ZSTD_pthread_mutex_lock(&best->mutex);
1010
0
    --best->liveJobs;
1011
0
    liveJobs = best->liveJobs;
1012
    /* If the new dictionary is better */
1013
0
    if (compressedSize < best->compressedSize) {
1014
      /* Allocate space if necessary */
1015
0
      if (!best->dict || best->dictSize < dictSize) {
1016
0
        if (best->dict) {
1017
0
          free(best->dict);
1018
0
        }
1019
0
        best->dict = malloc(dictSize);
1020
0
        if (!best->dict) {
1021
0
          best->compressedSize = ERROR(GENERIC);
1022
0
          best->dictSize = 0;
1023
0
          ZSTD_pthread_cond_signal(&best->cond);
1024
0
          ZSTD_pthread_mutex_unlock(&best->mutex);
1025
0
          return;
1026
0
        }
1027
0
      }
1028
      /* Save the dictionary, parameters, and size */
1029
0
      if (dict) {
1030
0
        memcpy(best->dict, dict, dictSize);
1031
0
        best->dictSize = dictSize;
1032
0
        best->parameters = parameters;
1033
0
        best->compressedSize = compressedSize;
1034
0
      }
1035
0
    }
1036
0
    if (liveJobs == 0) {
1037
0
      ZSTD_pthread_cond_broadcast(&best->cond);
1038
0
    }
1039
0
    ZSTD_pthread_mutex_unlock(&best->mutex);
1040
0
  }
1041
0
}
1042
1043
static COVER_dictSelection_t setDictSelection(BYTE* buf, size_t s, size_t csz)
1044
0
{
1045
0
    COVER_dictSelection_t ds;
1046
0
    ds.dictContent = buf;
1047
0
    ds.dictSize = s;
1048
0
    ds.totalCompressedSize = csz;
1049
0
    return ds;
1050
0
}
1051
1052
0
COVER_dictSelection_t COVER_dictSelectionError(size_t error) {
1053
0
    return setDictSelection(NULL, 0, error);
1054
0
}
1055
1056
0
unsigned COVER_dictSelectionIsError(COVER_dictSelection_t selection) {
1057
0
  return (ZSTD_isError(selection.totalCompressedSize) || !selection.dictContent);
1058
0
}
1059
1060
0
void COVER_dictSelectionFree(COVER_dictSelection_t selection){
1061
0
  free(selection.dictContent);
1062
0
}
1063
1064
COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBufferCapacity,
1065
        size_t dictContentSize, const BYTE* samplesBuffer, const size_t* samplesSizes, unsigned nbFinalizeSamples,
1066
0
        size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t* offsets, size_t totalCompressedSize) {
1067
1068
0
  size_t largestDict = 0;
1069
0
  size_t largestCompressed = 0;
1070
0
  size_t candidateContentSize = 0;
1071
0
  size_t candidateDict = 0;
1072
0
  BYTE* customDictContentEnd = customDictContent + dictContentSize;
1073
1074
0
  BYTE* largestDictbuffer = (BYTE*)malloc(dictBufferCapacity);
1075
0
  BYTE* candidateDictBuffer = (BYTE*)malloc(dictBufferCapacity);
1076
0
  double regressionTolerance = ((double)params.shrinkDictMaxRegression / 100.0) + 1.00;
1077
1078
0
  if (!largestDictbuffer || !candidateDictBuffer) {
1079
0
    free(largestDictbuffer);
1080
0
    free(candidateDictBuffer);
1081
0
    return COVER_dictSelectionError(dictContentSize);
1082
0
  }
1083
1084
  /* Initial dictionary size and compressed size */
1085
0
  memcpy(largestDictbuffer, customDictContent, dictContentSize);
1086
0
  largestDict = ZDICT_finalizeDictionary(
1087
0
    largestDictbuffer, dictBufferCapacity, customDictContent, dictContentSize,
1088
0
    samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
1089
1090
0
  if (ZDICT_isError(largestDict)) {
1091
0
    free(largestDictbuffer);
1092
0
    free(candidateDictBuffer);
1093
0
    return COVER_dictSelectionError(largestDict);
1094
0
  }
1095
1096
0
  totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
1097
0
                                                       samplesBuffer, offsets,
1098
0
                                                       nbCheckSamples, nbSamples,
1099
0
                                                       largestDictbuffer, largestDict);
1100
1101
0
  if (ZSTD_isError(totalCompressedSize)) {
1102
0
    free(largestDictbuffer);
1103
0
    free(candidateDictBuffer);
1104
0
    return COVER_dictSelectionError(totalCompressedSize);
1105
0
  }
1106
1107
0
  if (params.shrinkDict == 0) {
1108
0
    free(candidateDictBuffer);
1109
0
    return setDictSelection(largestDictbuffer, largestDict, totalCompressedSize);
1110
0
  }
1111
1112
0
  largestCompressed = totalCompressedSize;
1113
0
  candidateContentSize = ZDICT_DICTSIZE_MIN;
1114
1115
0
  while (candidateContentSize < dictContentSize) {
1116
0
    memcpy(candidateDictBuffer, largestDictbuffer, largestDict);
1117
0
    candidateDict = ZDICT_finalizeDictionary(
1118
0
      candidateDictBuffer, dictBufferCapacity, customDictContentEnd - candidateContentSize, candidateContentSize,
1119
0
      samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
1120
1121
0
    if (ZDICT_isError(candidateDict)) {
1122
0
      free(largestDictbuffer);
1123
0
      free(candidateDictBuffer);
1124
0
      return COVER_dictSelectionError(candidateDict);
1125
1126
0
    }
1127
1128
0
    totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
1129
0
                                                         samplesBuffer, offsets,
1130
0
                                                         nbCheckSamples, nbSamples,
1131
0
                                                         candidateDictBuffer, candidateDict);
1132
1133
0
    if (ZSTD_isError(totalCompressedSize)) {
1134
0
      free(largestDictbuffer);
1135
0
      free(candidateDictBuffer);
1136
0
      return COVER_dictSelectionError(totalCompressedSize);
1137
0
    }
1138
1139
0
    if ((double)totalCompressedSize <= (double)largestCompressed * regressionTolerance) {
1140
0
      free(largestDictbuffer);
1141
0
      return setDictSelection( candidateDictBuffer, candidateDict, totalCompressedSize );
1142
0
    }
1143
0
    candidateContentSize *= 2;
1144
0
  }
1145
0
  totalCompressedSize = largestCompressed;
1146
0
  free(candidateDictBuffer);
1147
0
  return setDictSelection( largestDictbuffer, largestDict, totalCompressedSize );
1148
0
}
1149
1150
/**
1151
 * Parameters for COVER_tryParameters().
1152
 */
1153
typedef struct COVER_tryParameters_data_s {
1154
  const COVER_ctx_t *ctx;
1155
  COVER_best_t *best;
1156
  size_t dictBufferCapacity;
1157
  ZDICT_cover_params_t parameters;
1158
} COVER_tryParameters_data_t;
1159
1160
/**
1161
 * Tries a set of parameters and updates the COVER_best_t with the results.
1162
 * This function is thread safe if zstd is compiled with multithreaded support.
1163
 * It takes its parameters as an *OWNING* opaque pointer to support threading.
1164
 */
1165
static void COVER_tryParameters(void *opaque)
1166
0
{
1167
  /* Save parameters as local variables */
1168
0
  COVER_tryParameters_data_t *const data = (COVER_tryParameters_data_t*)opaque;
1169
0
  const COVER_ctx_t *const ctx = data->ctx;
1170
0
  const ZDICT_cover_params_t parameters = data->parameters;
1171
0
  size_t dictBufferCapacity = data->dictBufferCapacity;
1172
0
  size_t totalCompressedSize = ERROR(GENERIC);
1173
  /* Allocate space for hash table, dict, and freqs */
1174
0
  COVER_map_t activeDmers;
1175
0
  BYTE* const dict = (BYTE*)malloc(dictBufferCapacity);
1176
0
  COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
1177
0
  U32* const freqs = (U32*)malloc(ctx->suffixSize * sizeof(U32));
1178
0
  const int displayLevel = ctx->displayLevel;
1179
0
  if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
1180
0
    DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
1181
0
    goto _cleanup;
1182
0
  }
1183
0
  if (!dict || !freqs) {
1184
0
    DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
1185
0
    goto _cleanup;
1186
0
  }
1187
  /* Copy the frequencies because we need to modify them */
1188
0
  memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
1189
  /* Build the dictionary */
1190
0
  {
1191
0
    const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
1192
0
                                              dictBufferCapacity, parameters);
1193
0
    selection = COVER_selectDict(dict + tail, dictBufferCapacity, dictBufferCapacity - tail,
1194
0
        ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbTrainSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
1195
0
        totalCompressedSize);
1196
1197
0
    if (COVER_dictSelectionIsError(selection)) {
1198
0
      DISPLAYLEVEL(1, "Failed to select dictionary\n");
1199
0
      goto _cleanup;
1200
0
    }
1201
0
  }
1202
0
_cleanup:
1203
0
  free(dict);
1204
0
  COVER_best_finish(data->best, parameters, selection);
1205
0
  free(data);
1206
0
  COVER_map_destroy(&activeDmers);
1207
0
  COVER_dictSelectionFree(selection);
1208
0
  free(freqs);
1209
0
}
1210
1211
ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover(
1212
    void* dictBuffer, size_t dictBufferCapacity, const void* samplesBuffer,
1213
    const size_t* samplesSizes, unsigned nbSamples,
1214
    ZDICT_cover_params_t* parameters)
1215
0
{
1216
  /* constants */
1217
0
  const unsigned nbThreads = parameters->nbThreads;
1218
0
  const double splitPoint =
1219
0
      parameters->splitPoint <= 0.0 ? COVER_DEFAULT_SPLITPOINT : parameters->splitPoint;
1220
0
  const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
1221
0
  const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
1222
0
  const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
1223
0
  const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
1224
0
  const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
1225
0
  const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
1226
0
  const unsigned kIterations =
1227
0
      (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
1228
0
  const unsigned shrinkDict = 0;
1229
  /* Local variables */
1230
0
  int displayLevel = (int)parameters->zParams.notificationLevel;
1231
0
  unsigned iteration = 1;
1232
0
  unsigned d;
1233
0
  unsigned k;
1234
0
  COVER_best_t best;
1235
0
  POOL_ctx *pool = NULL;
1236
0
  int warned = 0;
1237
0
  clock_t lastUpdateTime = 0;
1238
1239
  /* Checks */
1240
0
  if (splitPoint <= 0 || splitPoint > 1) {
1241
0
    DISPLAYLEVEL(1, "Incorrect parameters\n");
1242
0
    return ERROR(parameter_outOfBound);
1243
0
  }
1244
0
  if (kMinK < kMaxD || kMaxK < kMinK) {
1245
0
    DISPLAYLEVEL(1, "Incorrect parameters\n");
1246
0
    return ERROR(parameter_outOfBound);
1247
0
  }
1248
0
  if (nbSamples == 0) {
1249
0
    DISPLAYLEVEL(1, "Cover must have at least one input file\n");
1250
0
    return ERROR(srcSize_wrong);
1251
0
  }
1252
0
  if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
1253
0
    DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
1254
0
                 ZDICT_DICTSIZE_MIN);
1255
0
    return ERROR(dstSize_tooSmall);
1256
0
  }
1257
0
  if (nbThreads > 1) {
1258
0
    pool = POOL_create(nbThreads, 1);
1259
0
    if (!pool) {
1260
0
      return ERROR(memory_allocation);
1261
0
    }
1262
0
  }
1263
  /* Initialization */
1264
0
  COVER_best_init(&best);
1265
  /* Loop through d first because each new value needs a new context */
1266
0
  DISPLAYLEVEL(2, "Trying %u different sets of parameters\n",
1267
0
                    kIterations);
1268
0
  for (d = kMinD; d <= kMaxD; d += 2) {
1269
    /* Initialize the context for this value of d */
1270
0
    COVER_ctx_t ctx;
1271
0
    DISPLAYLEVEL(3, "d=%u\n", d);
1272
0
    {
1273
      /* Turn down global display level to clean up display at level 2 and below */
1274
0
      const int childDisplayLevel = (displayLevel == 0) ? 0 : displayLevel - 1;
1275
0
      const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, childDisplayLevel);
1276
0
      if (ZSTD_isError(initVal)) {
1277
0
        DISPLAYLEVEL(1, "Failed to initialize context\n");
1278
0
        COVER_best_destroy(&best);
1279
0
        POOL_free(pool);
1280
0
        return initVal;
1281
0
      }
1282
0
    }
1283
0
    if (!warned) {
1284
0
      COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel);
1285
0
      warned = 1;
1286
0
    }
1287
    /* Loop through k reusing the same context */
1288
0
    for (k = kMinK; k <= kMaxK; k += kStepSize) {
1289
      /* Prepare the arguments */
1290
0
      COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc(
1291
0
          sizeof(COVER_tryParameters_data_t));
1292
0
      DISPLAYLEVEL(3, "k=%u\n", k);
1293
0
      if (!data) {
1294
0
        DISPLAYLEVEL(1, "Failed to allocate parameters\n");
1295
0
        COVER_best_destroy(&best);
1296
0
        COVER_ctx_destroy(&ctx);
1297
0
        POOL_free(pool);
1298
0
        return ERROR(memory_allocation);
1299
0
      }
1300
0
      data->ctx = &ctx;
1301
0
      data->best = &best;
1302
0
      data->dictBufferCapacity = dictBufferCapacity;
1303
0
      data->parameters = *parameters;
1304
0
      data->parameters.k = k;
1305
0
      data->parameters.d = d;
1306
0
      data->parameters.splitPoint = splitPoint;
1307
0
      data->parameters.steps = kSteps;
1308
0
      data->parameters.shrinkDict = shrinkDict;
1309
0
      data->parameters.zParams.notificationLevel = (unsigned)ctx.displayLevel;
1310
      /* Check the parameters */
1311
0
      if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
1312
0
        DISPLAYLEVEL(1, "Cover parameters incorrect\n");
1313
0
        free(data);
1314
0
        continue;
1315
0
      }
1316
      /* Call the function and pass ownership of data to it */
1317
0
      COVER_best_start(&best);
1318
0
      if (pool) {
1319
0
        POOL_add(pool, &COVER_tryParameters, data);
1320
0
      } else {
1321
0
        COVER_tryParameters(data);
1322
0
      }
1323
      /* Print status */
1324
0
      DISPLAYUPDATE(lastUpdateTime, 2, "\r%u%%       ",
1325
0
                    (unsigned)((iteration * 100) / kIterations));
1326
0
      ++iteration;
1327
0
    }
1328
0
    COVER_best_wait(&best);
1329
0
    COVER_ctx_destroy(&ctx);
1330
0
  }
1331
0
  DISPLAYLEVEL(2, "\r%79s\r", "");
1332
  /* Fill the output buffer and parameters with output of the best parameters */
1333
0
  {
1334
0
    const size_t dictSize = best.dictSize;
1335
0
    if (ZSTD_isError(best.compressedSize)) {
1336
0
      const size_t compressedSize = best.compressedSize;
1337
0
      COVER_best_destroy(&best);
1338
0
      POOL_free(pool);
1339
0
      return compressedSize;
1340
0
    }
1341
0
    *parameters = best.parameters;
1342
0
    memcpy(dictBuffer, best.dict, dictSize);
1343
0
    COVER_best_destroy(&best);
1344
0
    POOL_free(pool);
1345
0
    return dictSize;
1346
0
  }
1347
0
}