Coverage Report

Created: 2025-07-12 06:30

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