extzstd 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +3 -3
  3. data/contrib/zstd/CHANGELOG +188 -1
  4. data/contrib/zstd/CONTRIBUTING.md +157 -74
  5. data/contrib/zstd/LICENSE +4 -4
  6. data/contrib/zstd/Makefile +81 -58
  7. data/contrib/zstd/Package.swift +36 -0
  8. data/contrib/zstd/README.md +59 -35
  9. data/contrib/zstd/TESTING.md +2 -3
  10. data/contrib/zstd/appveyor.yml +49 -136
  11. data/contrib/zstd/lib/BUCK +5 -7
  12. data/contrib/zstd/lib/Makefile +87 -181
  13. data/contrib/zstd/lib/README.md +23 -6
  14. data/contrib/zstd/lib/common/allocations.h +55 -0
  15. data/contrib/zstd/lib/common/bits.h +200 -0
  16. data/contrib/zstd/lib/common/bitstream.h +33 -59
  17. data/contrib/zstd/lib/common/compiler.h +115 -45
  18. data/contrib/zstd/lib/common/cpu.h +1 -1
  19. data/contrib/zstd/lib/common/debug.c +1 -1
  20. data/contrib/zstd/lib/common/debug.h +1 -1
  21. data/contrib/zstd/lib/common/entropy_common.c +15 -37
  22. data/contrib/zstd/lib/common/error_private.c +9 -2
  23. data/contrib/zstd/lib/common/error_private.h +82 -3
  24. data/contrib/zstd/lib/common/fse.h +9 -85
  25. data/contrib/zstd/lib/common/fse_decompress.c +29 -111
  26. data/contrib/zstd/lib/common/huf.h +84 -172
  27. data/contrib/zstd/lib/common/mem.h +58 -49
  28. data/contrib/zstd/lib/common/pool.c +37 -16
  29. data/contrib/zstd/lib/common/pool.h +9 -3
  30. data/contrib/zstd/lib/common/portability_macros.h +156 -0
  31. data/contrib/zstd/lib/common/threading.c +68 -14
  32. data/contrib/zstd/lib/common/threading.h +5 -10
  33. data/contrib/zstd/lib/common/xxhash.c +7 -809
  34. data/contrib/zstd/lib/common/xxhash.h +5568 -167
  35. data/contrib/zstd/lib/common/zstd_common.c +1 -36
  36. data/contrib/zstd/lib/common/zstd_deps.h +1 -1
  37. data/contrib/zstd/lib/common/zstd_internal.h +64 -150
  38. data/contrib/zstd/lib/common/zstd_trace.h +163 -0
  39. data/contrib/zstd/lib/compress/clevels.h +134 -0
  40. data/contrib/zstd/lib/compress/fse_compress.c +69 -150
  41. data/contrib/zstd/lib/compress/hist.c +1 -1
  42. data/contrib/zstd/lib/compress/hist.h +1 -1
  43. data/contrib/zstd/lib/compress/huf_compress.c +773 -251
  44. data/contrib/zstd/lib/compress/zstd_compress.c +2650 -826
  45. data/contrib/zstd/lib/compress/zstd_compress_internal.h +509 -180
  46. data/contrib/zstd/lib/compress/zstd_compress_literals.c +117 -40
  47. data/contrib/zstd/lib/compress/zstd_compress_literals.h +16 -6
  48. data/contrib/zstd/lib/compress/zstd_compress_sequences.c +28 -19
  49. data/contrib/zstd/lib/compress/zstd_compress_sequences.h +1 -1
  50. data/contrib/zstd/lib/compress/zstd_compress_superblock.c +33 -305
  51. data/contrib/zstd/lib/compress/zstd_compress_superblock.h +1 -1
  52. data/contrib/zstd/lib/compress/zstd_cwksp.h +266 -85
  53. data/contrib/zstd/lib/compress/zstd_double_fast.c +369 -132
  54. data/contrib/zstd/lib/compress/zstd_double_fast.h +3 -2
  55. data/contrib/zstd/lib/compress/zstd_fast.c +722 -258
  56. data/contrib/zstd/lib/compress/zstd_fast.h +3 -2
  57. data/contrib/zstd/lib/compress/zstd_lazy.c +1105 -360
  58. data/contrib/zstd/lib/compress/zstd_lazy.h +41 -1
  59. data/contrib/zstd/lib/compress/zstd_ldm.c +272 -208
  60. data/contrib/zstd/lib/compress/zstd_ldm.h +3 -2
  61. data/contrib/zstd/lib/compress/zstd_ldm_geartab.h +106 -0
  62. data/contrib/zstd/lib/compress/zstd_opt.c +324 -197
  63. data/contrib/zstd/lib/compress/zstd_opt.h +1 -1
  64. data/contrib/zstd/lib/compress/zstdmt_compress.c +109 -53
  65. data/contrib/zstd/lib/compress/zstdmt_compress.h +9 -6
  66. data/contrib/zstd/lib/decompress/huf_decompress.c +1071 -539
  67. data/contrib/zstd/lib/decompress/huf_decompress_amd64.S +576 -0
  68. data/contrib/zstd/lib/decompress/zstd_ddict.c +4 -4
  69. data/contrib/zstd/lib/decompress/zstd_ddict.h +1 -1
  70. data/contrib/zstd/lib/decompress/zstd_decompress.c +507 -82
  71. data/contrib/zstd/lib/decompress/zstd_decompress_block.c +962 -310
  72. data/contrib/zstd/lib/decompress/zstd_decompress_block.h +14 -3
  73. data/contrib/zstd/lib/decompress/zstd_decompress_internal.h +54 -6
  74. data/contrib/zstd/lib/deprecated/zbuff.h +1 -1
  75. data/contrib/zstd/lib/deprecated/zbuff_common.c +1 -1
  76. data/contrib/zstd/lib/deprecated/zbuff_compress.c +24 -4
  77. data/contrib/zstd/lib/deprecated/zbuff_decompress.c +3 -1
  78. data/contrib/zstd/lib/dictBuilder/cover.c +44 -32
  79. data/contrib/zstd/lib/dictBuilder/cover.h +6 -5
  80. data/contrib/zstd/lib/dictBuilder/divsufsort.c +1 -1
  81. data/contrib/zstd/lib/dictBuilder/fastcover.c +24 -16
  82. data/contrib/zstd/lib/dictBuilder/zdict.c +88 -95
  83. data/contrib/zstd/lib/legacy/zstd_legacy.h +8 -1
  84. data/contrib/zstd/lib/legacy/zstd_v01.c +16 -53
  85. data/contrib/zstd/lib/legacy/zstd_v01.h +1 -1
  86. data/contrib/zstd/lib/legacy/zstd_v02.c +24 -69
  87. data/contrib/zstd/lib/legacy/zstd_v02.h +1 -1
  88. data/contrib/zstd/lib/legacy/zstd_v03.c +25 -72
  89. data/contrib/zstd/lib/legacy/zstd_v03.h +1 -1
  90. data/contrib/zstd/lib/legacy/zstd_v04.c +23 -69
  91. data/contrib/zstd/lib/legacy/zstd_v04.h +1 -1
  92. data/contrib/zstd/lib/legacy/zstd_v05.c +35 -85
  93. data/contrib/zstd/lib/legacy/zstd_v05.h +1 -1
  94. data/contrib/zstd/lib/legacy/zstd_v06.c +42 -87
  95. data/contrib/zstd/lib/legacy/zstd_v06.h +1 -1
  96. data/contrib/zstd/lib/legacy/zstd_v07.c +35 -82
  97. data/contrib/zstd/lib/legacy/zstd_v07.h +1 -1
  98. data/contrib/zstd/lib/libzstd.mk +214 -0
  99. data/contrib/zstd/lib/libzstd.pc.in +4 -3
  100. data/contrib/zstd/lib/module.modulemap +35 -0
  101. data/contrib/zstd/lib/{dictBuilder/zdict.h → zdict.h} +202 -33
  102. data/contrib/zstd/lib/zstd.h +922 -293
  103. data/contrib/zstd/lib/{common/zstd_errors.h → zstd_errors.h} +27 -8
  104. data/ext/extconf.rb +7 -6
  105. data/ext/extzstd.c +13 -10
  106. data/ext/libzstd_conf.h +0 -1
  107. data/ext/zstd_decompress_asm.S +1 -0
  108. metadata +16 -5
@@ -1,5 +1,5 @@
1
1
  /*
2
- * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
3
  * All rights reserved.
4
4
  *
5
5
  * This source code is licensed under both the BSD-style license (found in the
@@ -23,6 +23,7 @@
23
23
  #ifdef ZSTD_MULTITHREAD
24
24
  # include "zstdmt_compress.h"
25
25
  #endif
26
+ #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */
26
27
 
27
28
  #if defined (__cplusplus)
28
29
  extern "C" {
@@ -63,7 +64,7 @@ typedef struct {
63
64
  } ZSTD_localDict;
64
65
 
65
66
  typedef struct {
66
- HUF_CElt CTable[HUF_CTABLE_SIZE_U32(255)];
67
+ HUF_CElt CTable[HUF_CTABLE_SIZE_ST(255)];
67
68
  HUF_repeat repeatMode;
68
69
  } ZSTD_hufCTables_t;
69
70
 
@@ -81,8 +82,56 @@ typedef struct {
81
82
  ZSTD_fseCTables_t fse;
82
83
  } ZSTD_entropyCTables_t;
83
84
 
85
+ /***********************************************
86
+ * Entropy buffer statistics structs and funcs *
87
+ ***********************************************/
88
+ /** ZSTD_hufCTablesMetadata_t :
89
+ * Stores Literals Block Type for a super-block in hType, and
90
+ * huffman tree description in hufDesBuffer.
91
+ * hufDesSize refers to the size of huffman tree description in bytes.
92
+ * This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */
84
93
  typedef struct {
85
- U32 off; /* Offset code (offset + ZSTD_REP_MOVE) for the match */
94
+ symbolEncodingType_e hType;
95
+ BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE];
96
+ size_t hufDesSize;
97
+ } ZSTD_hufCTablesMetadata_t;
98
+
99
+ /** ZSTD_fseCTablesMetadata_t :
100
+ * Stores symbol compression modes for a super-block in {ll, ol, ml}Type, and
101
+ * fse tables in fseTablesBuffer.
102
+ * fseTablesSize refers to the size of fse tables in bytes.
103
+ * This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */
104
+ typedef struct {
105
+ symbolEncodingType_e llType;
106
+ symbolEncodingType_e ofType;
107
+ symbolEncodingType_e mlType;
108
+ BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE];
109
+ size_t fseTablesSize;
110
+ size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
111
+ } ZSTD_fseCTablesMetadata_t;
112
+
113
+ typedef struct {
114
+ ZSTD_hufCTablesMetadata_t hufMetadata;
115
+ ZSTD_fseCTablesMetadata_t fseMetadata;
116
+ } ZSTD_entropyCTablesMetadata_t;
117
+
118
+ /** ZSTD_buildBlockEntropyStats() :
119
+ * Builds entropy for the block.
120
+ * @return : 0 on success or error code */
121
+ size_t ZSTD_buildBlockEntropyStats(
122
+ const seqStore_t* seqStorePtr,
123
+ const ZSTD_entropyCTables_t* prevEntropy,
124
+ ZSTD_entropyCTables_t* nextEntropy,
125
+ const ZSTD_CCtx_params* cctxParams,
126
+ ZSTD_entropyCTablesMetadata_t* entropyMetadata,
127
+ void* workspace, size_t wkspSize);
128
+
129
+ /*********************************
130
+ * Compression internals structs *
131
+ *********************************/
132
+
133
+ typedef struct {
134
+ U32 off; /* Offset sumtype code for the match, using ZSTD_storeSeq() format */
86
135
  U32 len; /* Raw length of match */
87
136
  } ZSTD_match_t;
88
137
 
@@ -101,6 +150,12 @@ typedef struct {
101
150
  size_t capacity; /* The capacity starting from `seq` pointer */
102
151
  } rawSeqStore_t;
103
152
 
153
+ typedef struct {
154
+ U32 idx; /* Index in array of ZSTD_Sequence */
155
+ U32 posInSequence; /* Position within sequence at idx */
156
+ size_t posInSrc; /* Number of bytes given by sequences provided so far */
157
+ } ZSTD_sequencePosition;
158
+
104
159
  UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};
105
160
 
106
161
  typedef struct {
@@ -132,7 +187,7 @@ typedef struct {
132
187
  U32 offCodeSumBasePrice; /* to compare to log2(offreq) */
133
188
  ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */
134
189
  const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */
135
- ZSTD_literalCompressionMode_e literalCompressionMode;
190
+ ZSTD_paramSwitch_e literalCompressionMode;
136
191
  } optState_t;
137
192
 
138
193
  typedef struct {
@@ -141,14 +196,23 @@ typedef struct {
141
196
  } ZSTD_compressedBlockState_t;
142
197
 
143
198
  typedef struct {
144
- BYTE const* nextSrc; /* next block here to continue on current prefix */
145
- BYTE const* base; /* All regular indexes relative to this position */
146
- BYTE const* dictBase; /* extDict indexes relative to this position */
147
- U32 dictLimit; /* below that point, need extDict */
148
- U32 lowLimit; /* below that point, no more valid data */
199
+ BYTE const* nextSrc; /* next block here to continue on current prefix */
200
+ BYTE const* base; /* All regular indexes relative to this position */
201
+ BYTE const* dictBase; /* extDict indexes relative to this position */
202
+ U32 dictLimit; /* below that point, need extDict */
203
+ U32 lowLimit; /* below that point, no more valid data */
204
+ U32 nbOverflowCorrections; /* Number of times overflow correction has run since
205
+ * ZSTD_window_init(). Useful for debugging coredumps
206
+ * and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.
207
+ */
149
208
  } ZSTD_window_t;
150
209
 
210
+ #define ZSTD_WINDOW_START_INDEX 2
211
+
151
212
  typedef struct ZSTD_matchState_t ZSTD_matchState_t;
213
+
214
+ #define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */
215
+
152
216
  struct ZSTD_matchState_t {
153
217
  ZSTD_window_t window; /* State for window round buffer management */
154
218
  U32 loadedDictEnd; /* index of end of dictionary, within context's referential.
@@ -160,9 +224,19 @@ struct ZSTD_matchState_t {
160
224
  */
161
225
  U32 nextToUpdate; /* index from which to continue table update */
162
226
  U32 hashLog3; /* dispatch table for matches of len==3 : larger == faster, more memory */
227
+
228
+ U32 rowHashLog; /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/
229
+ BYTE* tagTable; /* For row-based matchFinder: A row-based table containing the hashes and head index. */
230
+ U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */
231
+ U64 hashSalt; /* For row-based matchFinder: salts the hash for re-use of tag table */
232
+ U32 hashSaltEntropy; /* For row-based matchFinder: collects entropy for salt generation */
233
+
163
234
  U32* hashTable;
164
235
  U32* hashTable3;
165
236
  U32* chainTable;
237
+
238
+ U32 forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */
239
+
166
240
  int dedicatedDictSearch; /* Indicates whether this matchState is using the
167
241
  * dedicated dictionary search structure.
168
242
  */
@@ -170,6 +244,18 @@ struct ZSTD_matchState_t {
170
244
  const ZSTD_matchState_t* dictMatchState;
171
245
  ZSTD_compressionParameters cParams;
172
246
  const rawSeqStore_t* ldmSeqStore;
247
+
248
+ /* Controls prefetching in some dictMatchState matchfinders.
249
+ * This behavior is controlled from the cctx ms.
250
+ * This parameter has no effect in the cdict ms. */
251
+ int prefetchCDictTables;
252
+
253
+ /* When == 0, lazy match finders insert every position.
254
+ * When != 0, lazy match finders only insert positions they search.
255
+ * This allows them to skip much faster over incompressible data,
256
+ * at a small cost to compression ratio.
257
+ */
258
+ int lazySkipping;
173
259
  };
174
260
 
175
261
  typedef struct {
@@ -183,17 +269,26 @@ typedef struct {
183
269
  U32 checksum;
184
270
  } ldmEntry_t;
185
271
 
272
+ typedef struct {
273
+ BYTE const* split;
274
+ U32 hash;
275
+ U32 checksum;
276
+ ldmEntry_t* bucket;
277
+ } ldmMatchCandidate_t;
278
+
279
+ #define LDM_BATCH_SIZE 64
280
+
186
281
  typedef struct {
187
282
  ZSTD_window_t window; /* State for the window round buffer management */
188
283
  ldmEntry_t* hashTable;
189
284
  U32 loadedDictEnd;
190
285
  BYTE* bucketOffsets; /* Next position in bucket to insert entry */
191
- U64 hashPower; /* Used to compute the rolling hash.
192
- * Depends on ldmParams.minMatchLength */
286
+ size_t splitIndices[LDM_BATCH_SIZE];
287
+ ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];
193
288
  } ldmState_t;
194
289
 
195
290
  typedef struct {
196
- U32 enableLdm; /* 1 if enable long distance matching */
291
+ ZSTD_paramSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */
197
292
  U32 hashLog; /* Log size of hashTable */
198
293
  U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */
199
294
  U32 minMatchLength; /* Minimum match length */
@@ -224,7 +319,7 @@ struct ZSTD_CCtx_params_s {
224
319
  * There is no guarantee that hint is close to actual source size */
225
320
 
226
321
  ZSTD_dictAttachPref_e attachDictPref;
227
- ZSTD_literalCompressionMode_e literalCompressionMode;
322
+ ZSTD_paramSwitch_e literalCompressionMode;
228
323
 
229
324
  /* Multithreading: used to pass parameters to mtctx */
230
325
  int nbWorkers;
@@ -246,8 +341,35 @@ struct ZSTD_CCtx_params_s {
246
341
  ZSTD_sequenceFormat_e blockDelimiters;
247
342
  int validateSequences;
248
343
 
344
+ /* Block splitting */
345
+ ZSTD_paramSwitch_e useBlockSplitter;
346
+
347
+ /* Param for deciding whether to use row-based matchfinder */
348
+ ZSTD_paramSwitch_e useRowMatchFinder;
349
+
350
+ /* Always load a dictionary in ext-dict mode (not prefix mode)? */
351
+ int deterministicRefPrefix;
352
+
249
353
  /* Internal use, for createCCtxParams() and freeCCtxParams() only */
250
354
  ZSTD_customMem customMem;
355
+
356
+ /* Controls prefetching in some dictMatchState matchfinders */
357
+ ZSTD_paramSwitch_e prefetchCDictTables;
358
+
359
+ /* Controls whether zstd will fall back to an internal matchfinder
360
+ * if the external matchfinder returns an error code. */
361
+ int enableMatchFinderFallback;
362
+
363
+ /* Indicates whether an external matchfinder has been referenced.
364
+ * Users can't set this externally.
365
+ * It is set internally in ZSTD_registerSequenceProducer(). */
366
+ int useSequenceProducer;
367
+
368
+ /* Adjust the max block size*/
369
+ size_t maxBlockSize;
370
+
371
+ /* Controls repcode search in external sequence parsing */
372
+ ZSTD_paramSwitch_e searchForExternalRepcodes;
251
373
  }; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
252
374
 
253
375
  #define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))
@@ -263,13 +385,39 @@ typedef enum {
263
385
  ZSTDb_buffered
264
386
  } ZSTD_buffered_policy_e;
265
387
 
388
+ /**
389
+ * Struct that contains all elements of block splitter that should be allocated
390
+ * in a wksp.
391
+ */
392
+ #define ZSTD_MAX_NB_BLOCK_SPLITS 196
393
+ typedef struct {
394
+ seqStore_t fullSeqStoreChunk;
395
+ seqStore_t firstHalfSeqStore;
396
+ seqStore_t secondHalfSeqStore;
397
+ seqStore_t currSeqStore;
398
+ seqStore_t nextSeqStore;
399
+
400
+ U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];
401
+ ZSTD_entropyCTablesMetadata_t entropyMetadata;
402
+ } ZSTD_blockSplitCtx;
403
+
404
+ /* Context for block-level external matchfinder API */
405
+ typedef struct {
406
+ void* mState;
407
+ ZSTD_sequenceProducer_F* mFinder;
408
+ ZSTD_Sequence* seqBuffer;
409
+ size_t seqBufferCapacity;
410
+ } ZSTD_externalMatchCtx;
411
+
266
412
  struct ZSTD_CCtx_s {
267
413
  ZSTD_compressionStage_e stage;
268
414
  int cParamsChanged; /* == 1 if cParams(except wlog) or compression level are changed in requestedParams. Triggers transmission of new params to ZSTDMT (if available) then reset to 0. */
269
415
  int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
270
416
  ZSTD_CCtx_params requestedParams;
271
417
  ZSTD_CCtx_params appliedParams;
418
+ ZSTD_CCtx_params simpleApiParams; /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */
272
419
  U32 dictID;
420
+ size_t dictContentSize;
273
421
 
274
422
  ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */
275
423
  size_t blockSize;
@@ -292,7 +440,7 @@ struct ZSTD_CCtx_s {
292
440
  ZSTD_blockState_t blockState;
293
441
  U32* entropyWorkspace; /* entropy workspace of ENTROPY_WORKSPACE_SIZE bytes */
294
442
 
295
- /* Wether we are streaming or not */
443
+ /* Whether we are streaming or not */
296
444
  ZSTD_buffered_policy_e bufferedPolicy;
297
445
 
298
446
  /* streaming */
@@ -310,6 +458,7 @@ struct ZSTD_CCtx_s {
310
458
 
311
459
  /* Stable in/out buffer verification */
312
460
  ZSTD_inBuffer expectedInBuffer;
461
+ size_t stableIn_notConsumed; /* nb bytes within stable input buffer that are said to be consumed but are not */
313
462
  size_t expectedOutBufferSize;
314
463
 
315
464
  /* Dictionary */
@@ -321,9 +470,21 @@ struct ZSTD_CCtx_s {
321
470
  #ifdef ZSTD_MULTITHREAD
322
471
  ZSTDMT_CCtx* mtctx;
323
472
  #endif
473
+
474
+ /* Tracing */
475
+ #if ZSTD_TRACE
476
+ ZSTD_TraceCtx traceCtx;
477
+ #endif
478
+
479
+ /* Workspace for block splitter */
480
+ ZSTD_blockSplitCtx blockSplitCtx;
481
+
482
+ /* Workspace for external matchfinder */
483
+ ZSTD_externalMatchCtx externalMatchCtx;
324
484
  };
325
485
 
326
486
  typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
487
+ typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;
327
488
 
328
489
  typedef enum {
329
490
  ZSTD_noDict = 0,
@@ -345,7 +506,7 @@ typedef enum {
345
506
  * In this mode we take both the source size and the dictionary size
346
507
  * into account when selecting and adjusting the parameters.
347
508
  */
348
- ZSTD_cpm_unknown = 3, /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.
509
+ ZSTD_cpm_unknown = 3 /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.
349
510
  * We don't know what these parameters are for. We default to the legacy
350
511
  * behavior of taking both the source size and the dict size into account
351
512
  * when selecting and adjusting parameters.
@@ -355,7 +516,7 @@ typedef enum {
355
516
  typedef size_t (*ZSTD_blockCompressor) (
356
517
  ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
357
518
  void const* src, size_t srcSize);
358
- ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_dictMode_e dictMode);
519
+ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);
359
520
 
360
521
 
361
522
  MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
@@ -389,31 +550,6 @@ MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
389
550
  return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];
390
551
  }
391
552
 
392
- typedef struct repcodes_s {
393
- U32 rep[3];
394
- } repcodes_t;
395
-
396
- MEM_STATIC repcodes_t ZSTD_updateRep(U32 const rep[3], U32 const offset, U32 const ll0)
397
- {
398
- repcodes_t newReps;
399
- if (offset >= ZSTD_REP_NUM) { /* full offset */
400
- newReps.rep[2] = rep[1];
401
- newReps.rep[1] = rep[0];
402
- newReps.rep[0] = offset - ZSTD_REP_MOVE;
403
- } else { /* repcode */
404
- U32 const repCode = offset + ll0;
405
- if (repCode > 0) { /* note : if repCode==0, no change */
406
- U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
407
- newReps.rep[2] = (repCode >= 2) ? rep[1] : rep[2];
408
- newReps.rep[1] = rep[0];
409
- newReps.rep[0] = currentOffset;
410
- } else { /* repCode == 0 */
411
- ZSTD_memcpy(&newReps, rep, sizeof(newReps));
412
- }
413
- }
414
- return newReps;
415
- }
416
-
417
553
  /* ZSTD_cParam_withinBounds:
418
554
  * @return 1 if value is within cParam bounds,
419
555
  * 0 otherwise */
@@ -429,9 +565,11 @@ MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)
429
565
  /* ZSTD_noCompressBlock() :
430
566
  * Writes uncompressed block to dst buffer from given src.
431
567
  * Returns the size of the block */
432
- MEM_STATIC size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
568
+ MEM_STATIC size_t
569
+ ZSTD_noCompressBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
433
570
  {
434
571
  U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);
572
+ DEBUGLOG(5, "ZSTD_noCompressBlock (srcSize=%zu, dstCapacity=%zu)", srcSize, dstCapacity);
435
573
  RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,
436
574
  dstSize_tooSmall, "dst buf too small for uncompressed block");
437
575
  MEM_writeLE24(dst, cBlockHeader24);
@@ -439,7 +577,8 @@ MEM_STATIC size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const voi
439
577
  return ZSTD_blockHeaderSize + srcSize;
440
578
  }
441
579
 
442
- MEM_STATIC size_t ZSTD_rleCompressBlock (void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)
580
+ MEM_STATIC size_t
581
+ ZSTD_rleCompressBlock(void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)
443
582
  {
444
583
  BYTE* const op = (BYTE*)dst;
445
584
  U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);
@@ -458,21 +597,21 @@ MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)
458
597
  {
459
598
  U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
460
599
  ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
461
- assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
600
+ assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
462
601
  return (srcSize >> minlog) + 2;
463
602
  }
464
603
 
465
- MEM_STATIC int ZSTD_disableLiteralsCompression(const ZSTD_CCtx_params* cctxParams)
604
+ MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)
466
605
  {
467
606
  switch (cctxParams->literalCompressionMode) {
468
- case ZSTD_lcm_huffman:
607
+ case ZSTD_ps_enable:
469
608
  return 0;
470
- case ZSTD_lcm_uncompressed:
609
+ case ZSTD_ps_disable:
471
610
  return 1;
472
611
  default:
473
612
  assert(0 /* impossible: pre-validated */);
474
- /* fall-through */
475
- case ZSTD_lcm_auto:
613
+ ZSTD_FALLTHROUGH;
614
+ case ZSTD_ps_auto:
476
615
  return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
477
616
  }
478
617
  }
@@ -482,7 +621,9 @@ MEM_STATIC int ZSTD_disableLiteralsCompression(const ZSTD_CCtx_params* cctxParam
482
621
  * Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single
483
622
  * large copies.
484
623
  */
485
- static void ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w) {
624
+ static void
625
+ ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)
626
+ {
486
627
  assert(iend > ilimit_w);
487
628
  if (ip <= ilimit_w) {
488
629
  ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);
@@ -492,14 +633,28 @@ static void ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const ie
492
633
  while (ip < iend) *op++ = *ip++;
493
634
  }
494
635
 
636
+
637
+ #define REPCODE1_TO_OFFBASE REPCODE_TO_OFFBASE(1)
638
+ #define REPCODE2_TO_OFFBASE REPCODE_TO_OFFBASE(2)
639
+ #define REPCODE3_TO_OFFBASE REPCODE_TO_OFFBASE(3)
640
+ #define REPCODE_TO_OFFBASE(r) (assert((r)>=1), assert((r)<=ZSTD_REP_NUM), (r)) /* accepts IDs 1,2,3 */
641
+ #define OFFSET_TO_OFFBASE(o) (assert((o)>0), o + ZSTD_REP_NUM)
642
+ #define OFFBASE_IS_OFFSET(o) ((o) > ZSTD_REP_NUM)
643
+ #define OFFBASE_IS_REPCODE(o) ( 1 <= (o) && (o) <= ZSTD_REP_NUM)
644
+ #define OFFBASE_TO_OFFSET(o) (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)
645
+ #define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o)) /* returns ID 1,2,3 */
646
+
495
647
  /*! ZSTD_storeSeq() :
496
- * Store a sequence (litlen, litPtr, offCode and mlBase) into seqStore_t.
497
- * `offCode` : distance to match + ZSTD_REP_MOVE (values <= ZSTD_REP_MOVE are repCodes).
498
- * `mlBase` : matchLength - MINMATCH
499
- * Allowed to overread literals up to litLimit.
648
+ * Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t.
649
+ * @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
650
+ * @matchLength : must be >= MINMATCH
651
+ * Allowed to over-read literals up to litLimit.
500
652
  */
501
- HINT_INLINE UNUSED_ATTR
502
- void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const BYTE* literals, const BYTE* litLimit, U32 offCode, size_t mlBase)
653
+ HINT_INLINE UNUSED_ATTR void
654
+ ZSTD_storeSeq(seqStore_t* seqStorePtr,
655
+ size_t litLength, const BYTE* literals, const BYTE* litLimit,
656
+ U32 offBase,
657
+ size_t matchLength)
503
658
  {
504
659
  BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;
505
660
  BYTE const* const litEnd = literals + litLength;
@@ -507,8 +662,8 @@ void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const BYTE* litera
507
662
  static const BYTE* g_start = NULL;
508
663
  if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */
509
664
  { U32 const pos = (U32)((const BYTE*)literals - g_start);
510
- DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offCode%7u",
511
- pos, (U32)litLength, (U32)mlBase+MINMATCH, (U32)offCode);
665
+ DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",
666
+ pos, (U32)litLength, (U32)matchLength, (U32)offBase);
512
667
  }
513
668
  #endif
514
669
  assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
@@ -518,9 +673,9 @@ void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const BYTE* litera
518
673
  assert(literals + litLength <= litLimit);
519
674
  if (litEnd <= litLimit_w) {
520
675
  /* Common case we can use wildcopy.
521
- * First copy 16 bytes, because literals are likely short.
522
- */
523
- assert(WILDCOPY_OVERLENGTH >= 16);
676
+ * First copy 16 bytes, because literals are likely short.
677
+ */
678
+ ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);
524
679
  ZSTD_copy16(seqStorePtr->lit, literals);
525
680
  if (litLength > 16) {
526
681
  ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);
@@ -532,103 +687,70 @@ void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const BYTE* litera
532
687
 
533
688
  /* literal Length */
534
689
  if (litLength>0xFFFF) {
535
- assert(seqStorePtr->longLengthID == 0); /* there can only be a single long length */
536
- seqStorePtr->longLengthID = 1;
690
+ assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
691
+ seqStorePtr->longLengthType = ZSTD_llt_literalLength;
537
692
  seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
538
693
  }
539
694
  seqStorePtr->sequences[0].litLength = (U16)litLength;
540
695
 
541
696
  /* match offset */
542
- seqStorePtr->sequences[0].offset = offCode + 1;
697
+ seqStorePtr->sequences[0].offBase = offBase;
543
698
 
544
699
  /* match Length */
545
- if (mlBase>0xFFFF) {
546
- assert(seqStorePtr->longLengthID == 0); /* there can only be a single long length */
547
- seqStorePtr->longLengthID = 2;
548
- seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
700
+ assert(matchLength >= MINMATCH);
701
+ { size_t const mlBase = matchLength - MINMATCH;
702
+ if (mlBase>0xFFFF) {
703
+ assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
704
+ seqStorePtr->longLengthType = ZSTD_llt_matchLength;
705
+ seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
706
+ }
707
+ seqStorePtr->sequences[0].mlBase = (U16)mlBase;
549
708
  }
550
- seqStorePtr->sequences[0].matchLength = (U16)mlBase;
551
709
 
552
710
  seqStorePtr->sequences++;
553
711
  }
554
712
 
555
-
556
- /*-*************************************
557
- * Match length counter
558
- ***************************************/
559
- static unsigned ZSTD_NbCommonBytes (size_t val)
713
+ /* ZSTD_updateRep() :
714
+ * updates in-place @rep (array of repeat offsets)
715
+ * @offBase : sum-type, using numeric representation of ZSTD_storeSeq()
716
+ */
717
+ MEM_STATIC void
718
+ ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
560
719
  {
561
- if (MEM_isLittleEndian()) {
562
- if (MEM_64bits()) {
563
- # if defined(_MSC_VER) && defined(_WIN64)
564
- # if STATIC_BMI2
565
- return _tzcnt_u64(val) >> 3;
566
- # else
567
- unsigned long r = 0;
568
- return _BitScanForward64( &r, (U64)val ) ? (unsigned)(r >> 3) : 0;
569
- # endif
570
- # elif defined(__GNUC__) && (__GNUC__ >= 4)
571
- return (__builtin_ctzll((U64)val) >> 3);
572
- # else
573
- static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
574
- 0, 3, 1, 3, 1, 4, 2, 7,
575
- 0, 2, 3, 6, 1, 5, 3, 5,
576
- 1, 3, 4, 4, 2, 5, 6, 7,
577
- 7, 0, 1, 2, 3, 3, 4, 6,
578
- 2, 6, 5, 5, 3, 4, 5, 6,
579
- 7, 1, 2, 4, 6, 4, 4, 5,
580
- 7, 2, 6, 5, 7, 6, 7, 7 };
581
- return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
582
- # endif
583
- } else { /* 32 bits */
584
- # if defined(_MSC_VER)
585
- unsigned long r=0;
586
- return _BitScanForward( &r, (U32)val ) ? (unsigned)(r >> 3) : 0;
587
- # elif defined(__GNUC__) && (__GNUC__ >= 3)
588
- return (__builtin_ctz((U32)val) >> 3);
589
- # else
590
- static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
591
- 3, 2, 2, 1, 3, 2, 0, 1,
592
- 3, 3, 1, 2, 2, 2, 2, 0,
593
- 3, 1, 2, 0, 1, 0, 1, 1 };
594
- return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
595
- # endif
720
+ if (OFFBASE_IS_OFFSET(offBase)) { /* full offset */
721
+ rep[2] = rep[1];
722
+ rep[1] = rep[0];
723
+ rep[0] = OFFBASE_TO_OFFSET(offBase);
724
+ } else { /* repcode */
725
+ U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;
726
+ if (repCode > 0) { /* note : if repCode==0, no change */
727
+ U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
728
+ rep[2] = (repCode >= 2) ? rep[1] : rep[2];
729
+ rep[1] = rep[0];
730
+ rep[0] = currentOffset;
731
+ } else { /* repCode == 0 */
732
+ /* nothing to do */
596
733
  }
597
- } else { /* Big Endian CPU */
598
- if (MEM_64bits()) {
599
- # if defined(_MSC_VER) && defined(_WIN64)
600
- # if STATIC_BMI2
601
- return _lzcnt_u64(val) >> 3;
602
- # else
603
- unsigned long r = 0;
604
- return _BitScanReverse64(&r, (U64)val) ? (unsigned)(r >> 3) : 0;
605
- # endif
606
- # elif defined(__GNUC__) && (__GNUC__ >= 4)
607
- return (__builtin_clzll(val) >> 3);
608
- # else
609
- unsigned r;
610
- const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */
611
- if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
612
- if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
613
- r += (!val);
614
- return r;
615
- # endif
616
- } else { /* 32 bits */
617
- # if defined(_MSC_VER)
618
- unsigned long r = 0;
619
- return _BitScanReverse( &r, (unsigned long)val ) ? (unsigned)(r >> 3) : 0;
620
- # elif defined(__GNUC__) && (__GNUC__ >= 3)
621
- return (__builtin_clz((U32)val) >> 3);
622
- # else
623
- unsigned r;
624
- if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
625
- r += (!val);
626
- return r;
627
- # endif
628
- } }
734
+ }
629
735
  }
630
736
 
737
+ typedef struct repcodes_s {
738
+ U32 rep[3];
739
+ } repcodes_t;
740
+
741
+ MEM_STATIC repcodes_t
742
+ ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
743
+ {
744
+ repcodes_t newReps;
745
+ ZSTD_memcpy(&newReps, rep, sizeof(newReps));
746
+ ZSTD_updateRep(newReps.rep, offBase, ll0);
747
+ return newReps;
748
+ }
631
749
 
750
+
751
+ /*-*************************************
752
+ * Match length counter
753
+ ***************************************/
632
754
  MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)
633
755
  {
634
756
  const BYTE* const pStart = pIn;
@@ -674,32 +796,43 @@ ZSTD_count_2segments(const BYTE* ip, const BYTE* match,
674
796
  * Hashes
675
797
  ***************************************/
676
798
  static const U32 prime3bytes = 506832829U;
677
- static U32 ZSTD_hash3(U32 u, U32 h) { return ((u << (32-24)) * prime3bytes) >> (32-h) ; }
678
- MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h); } /* only in zstd_opt.h */
799
+ static U32 ZSTD_hash3(U32 u, U32 h, U32 s) { assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s) >> (32-h) ; }
800
+ MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h, 0); } /* only in zstd_opt.h */
801
+ MEM_STATIC size_t ZSTD_hash3PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash3(MEM_readLE32(ptr), h, s); }
679
802
 
680
803
  static const U32 prime4bytes = 2654435761U;
681
- static U32 ZSTD_hash4(U32 u, U32 h) { return (u * prime4bytes) >> (32-h) ; }
682
- static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_read32(ptr), h); }
804
+ static U32 ZSTD_hash4(U32 u, U32 h, U32 s) { assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }
805
+ static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_readLE32(ptr), h, 0); }
806
+ static size_t ZSTD_hash4PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash4(MEM_readLE32(ptr), h, s); }
683
807
 
684
808
  static const U64 prime5bytes = 889523592379ULL;
685
- static size_t ZSTD_hash5(U64 u, U32 h) { return (size_t)(((u << (64-40)) * prime5bytes) >> (64-h)) ; }
686
- static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h); }
809
+ static size_t ZSTD_hash5(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }
810
+ static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h, 0); }
811
+ static size_t ZSTD_hash5PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash5(MEM_readLE64(p), h, s); }
687
812
 
688
813
  static const U64 prime6bytes = 227718039650203ULL;
689
- static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64-48)) * prime6bytes) >> (64-h)) ; }
690
- static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h); }
814
+ static size_t ZSTD_hash6(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }
815
+ static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h, 0); }
816
+ static size_t ZSTD_hash6PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash6(MEM_readLE64(p), h, s); }
691
817
 
692
818
  static const U64 prime7bytes = 58295818150454627ULL;
693
- static size_t ZSTD_hash7(U64 u, U32 h) { return (size_t)(((u << (64-56)) * prime7bytes) >> (64-h)) ; }
694
- static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h); }
819
+ static size_t ZSTD_hash7(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }
820
+ static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h, 0); }
821
+ static size_t ZSTD_hash7PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash7(MEM_readLE64(p), h, s); }
695
822
 
696
823
  static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
697
- static size_t ZSTD_hash8(U64 u, U32 h) { return (size_t)(((u) * prime8bytes) >> (64-h)) ; }
698
- static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h); }
824
+ static size_t ZSTD_hash8(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u) * prime8bytes) ^ s) >> (64-h)) ; }
825
+ static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }
826
+ static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }
827
+
699
828
 
700
829
  MEM_STATIC FORCE_INLINE_ATTR
701
830
  size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
702
831
  {
832
+ /* Although some of these hashes do support hBits up to 64, some do not.
833
+ * To be on the safe side, always avoid hBits > 32. */
834
+ assert(hBits <= 32);
835
+
703
836
  switch(mls)
704
837
  {
705
838
  default:
@@ -711,6 +844,24 @@ size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
711
844
  }
712
845
  }
713
846
 
847
+ MEM_STATIC FORCE_INLINE_ATTR
848
+ size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {
849
+ /* Although some of these hashes do support hBits up to 64, some do not.
850
+ * To be on the safe side, always avoid hBits > 32. */
851
+ assert(hBits <= 32);
852
+
853
+ switch(mls)
854
+ {
855
+ default:
856
+ case 4: return ZSTD_hash4PtrS(p, hBits, (U32)hashSalt);
857
+ case 5: return ZSTD_hash5PtrS(p, hBits, hashSalt);
858
+ case 6: return ZSTD_hash6PtrS(p, hBits, hashSalt);
859
+ case 7: return ZSTD_hash7PtrS(p, hBits, hashSalt);
860
+ case 8: return ZSTD_hash8PtrS(p, hBits, hashSalt);
861
+ }
862
+ }
863
+
864
+
714
865
  /** ZSTD_ipow() :
715
866
  * Return base^exponent.
716
867
  */
@@ -795,6 +946,13 @@ MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)
795
946
  window->dictLimit = end;
796
947
  }
797
948
 
949
+ MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)
950
+ {
951
+ return window.dictLimit == ZSTD_WINDOW_START_INDEX &&
952
+ window.lowLimit == ZSTD_WINDOW_START_INDEX &&
953
+ (window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;
954
+ }
955
+
798
956
  /**
799
957
  * ZSTD_window_hasExtDict():
800
958
  * Returns non-zero if the window has a non-empty extDict.
@@ -818,15 +976,71 @@ MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)
818
976
  ZSTD_noDict;
819
977
  }
820
978
 
979
+ /* Defining this macro to non-zero tells zstd to run the overflow correction
980
+ * code much more frequently. This is very inefficient, and should only be
981
+ * used for tests and fuzzers.
982
+ */
983
+ #ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY
984
+ # ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
985
+ # define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 1
986
+ # else
987
+ # define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 0
988
+ # endif
989
+ #endif
990
+
991
+ /**
992
+ * ZSTD_window_canOverflowCorrect():
993
+ * Returns non-zero if the indices are large enough for overflow correction
994
+ * to work correctly without impacting compression ratio.
995
+ */
996
+ MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,
997
+ U32 cycleLog,
998
+ U32 maxDist,
999
+ U32 loadedDictEnd,
1000
+ void const* src)
1001
+ {
1002
+ U32 const cycleSize = 1u << cycleLog;
1003
+ U32 const curr = (U32)((BYTE const*)src - window.base);
1004
+ U32 const minIndexToOverflowCorrect = cycleSize
1005
+ + MAX(maxDist, cycleSize)
1006
+ + ZSTD_WINDOW_START_INDEX;
1007
+
1008
+ /* Adjust the min index to backoff the overflow correction frequency,
1009
+ * so we don't waste too much CPU in overflow correction. If this
1010
+ * computation overflows we don't really care, we just need to make
1011
+ * sure it is at least minIndexToOverflowCorrect.
1012
+ */
1013
+ U32 const adjustment = window.nbOverflowCorrections + 1;
1014
+ U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,
1015
+ minIndexToOverflowCorrect);
1016
+ U32 const indexLargeEnough = curr > adjustedIndex;
1017
+
1018
+ /* Only overflow correct early if the dictionary is invalidated already,
1019
+ * so we don't hurt compression ratio.
1020
+ */
1021
+ U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;
1022
+
1023
+ return indexLargeEnough && dictionaryInvalidated;
1024
+ }
1025
+
821
1026
  /**
822
1027
  * ZSTD_window_needOverflowCorrection():
823
1028
  * Returns non-zero if the indices are getting too large and need overflow
824
1029
  * protection.
825
1030
  */
826
1031
  MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
1032
+ U32 cycleLog,
1033
+ U32 maxDist,
1034
+ U32 loadedDictEnd,
1035
+ void const* src,
827
1036
  void const* srcEnd)
828
1037
  {
829
1038
  U32 const curr = (U32)((BYTE const*)srcEnd - window.base);
1039
+ if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
1040
+ if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {
1041
+ return 1;
1042
+ }
1043
+ }
830
1044
  return curr > ZSTD_CURRENT_MAX;
831
1045
  }
832
1046
 
@@ -838,7 +1052,6 @@ MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
838
1052
  *
839
1053
  * The least significant cycleLog bits of the indices must remain the same,
840
1054
  * which may be 0. Every index up to maxDist in the past must be valid.
841
- * NOTE: (maxDist & cycleMask) must be zero.
842
1055
  */
843
1056
  MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
844
1057
  U32 maxDist, void const* src)
@@ -862,32 +1075,52 @@ MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
862
1075
  * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
863
1076
  * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
864
1077
  */
865
- U32 const cycleMask = (1U << cycleLog) - 1;
1078
+ U32 const cycleSize = 1u << cycleLog;
1079
+ U32 const cycleMask = cycleSize - 1;
866
1080
  U32 const curr = (U32)((BYTE const*)src - window->base);
867
- U32 const currentCycle0 = curr & cycleMask;
868
- /* Exclude zero so that newCurrent - maxDist >= 1. */
869
- U32 const currentCycle1 = currentCycle0 == 0 ? (1U << cycleLog) : currentCycle0;
870
- U32 const newCurrent = currentCycle1 + maxDist;
1081
+ U32 const currentCycle = curr & cycleMask;
1082
+ /* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */
1083
+ U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX
1084
+ ? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)
1085
+ : 0;
1086
+ U32 const newCurrent = currentCycle
1087
+ + currentCycleCorrection
1088
+ + MAX(maxDist, cycleSize);
871
1089
  U32 const correction = curr - newCurrent;
872
- assert((maxDist & cycleMask) == 0);
1090
+ /* maxDist must be a power of two so that:
1091
+ * (newCurrent & cycleMask) == (curr & cycleMask)
1092
+ * This is required to not corrupt the chains / binary tree.
1093
+ */
1094
+ assert((maxDist & (maxDist - 1)) == 0);
1095
+ assert((curr & cycleMask) == (newCurrent & cycleMask));
873
1096
  assert(curr > newCurrent);
874
- /* Loose bound, should be around 1<<29 (see above) */
875
- assert(correction > 1<<28);
1097
+ if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
1098
+ /* Loose bound, should be around 1<<29 (see above) */
1099
+ assert(correction > 1<<28);
1100
+ }
876
1101
 
877
1102
  window->base += correction;
878
1103
  window->dictBase += correction;
879
- if (window->lowLimit <= correction) window->lowLimit = 1;
880
- else window->lowLimit -= correction;
881
- if (window->dictLimit <= correction) window->dictLimit = 1;
882
- else window->dictLimit -= correction;
1104
+ if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {
1105
+ window->lowLimit = ZSTD_WINDOW_START_INDEX;
1106
+ } else {
1107
+ window->lowLimit -= correction;
1108
+ }
1109
+ if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {
1110
+ window->dictLimit = ZSTD_WINDOW_START_INDEX;
1111
+ } else {
1112
+ window->dictLimit -= correction;
1113
+ }
883
1114
 
884
1115
  /* Ensure we can still reference the full window. */
885
1116
  assert(newCurrent >= maxDist);
886
- assert(newCurrent - maxDist >= 1);
1117
+ assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);
887
1118
  /* Ensure that lowLimit and dictLimit didn't underflow. */
888
1119
  assert(window->lowLimit <= newCurrent);
889
1120
  assert(window->dictLimit <= newCurrent);
890
1121
 
1122
+ ++window->nbOverflowCorrections;
1123
+
891
1124
  DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,
892
1125
  window->lowLimit);
893
1126
  return correction;
@@ -976,10 +1209,15 @@ ZSTD_checkDictValidity(const ZSTD_window_t* window,
976
1209
  (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
977
1210
  assert(blockEndIdx >= loadedDictEnd);
978
1211
 
979
- if (blockEndIdx > loadedDictEnd + maxDist) {
1212
+ if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {
980
1213
  /* On reaching window size, dictionaries are invalidated.
981
1214
  * For simplification, if window size is reached anywhere within next block,
982
1215
  * the dictionary is invalidated for the full block.
1216
+ *
1217
+ * We also have to invalidate the dictionary if ZSTD_window_update() has detected
1218
+ * non-contiguous segments, which means that loadedDictEnd != window->dictLimit.
1219
+ * loadedDictEnd may be 0, if forceWindow is true, but in that case we never use
1220
+ * dictMatchState, so setting it to NULL is not a problem.
983
1221
  */
984
1222
  DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");
985
1223
  *loadedDictEndPtr = 0;
@@ -992,11 +1230,13 @@ ZSTD_checkDictValidity(const ZSTD_window_t* window,
992
1230
 
993
1231
  MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
994
1232
  ZSTD_memset(window, 0, sizeof(*window));
995
- window->base = (BYTE const*)"";
996
- window->dictBase = (BYTE const*)"";
997
- window->dictLimit = 1; /* start from 1, so that 1st position is valid */
998
- window->lowLimit = 1; /* it ensures first and later CCtx usages compress the same */
999
- window->nextSrc = window->base + 1; /* see issue #1241 */
1233
+ window->base = (BYTE const*)" ";
1234
+ window->dictBase = (BYTE const*)" ";
1235
+ ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */
1236
+ window->dictLimit = ZSTD_WINDOW_START_INDEX; /* start from >0, so that 1st position is valid */
1237
+ window->lowLimit = ZSTD_WINDOW_START_INDEX; /* it ensures first and later CCtx usages compress the same */
1238
+ window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX; /* see issue #1241 */
1239
+ window->nbOverflowCorrections = 0;
1000
1240
  }
1001
1241
 
1002
1242
  /**
@@ -1007,7 +1247,8 @@ MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
1007
1247
  * Returns non-zero if the segment is contiguous.
1008
1248
  */
1009
1249
  MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,
1010
- void const* src, size_t srcSize)
1250
+ void const* src, size_t srcSize,
1251
+ int forceNonContiguous)
1011
1252
  {
1012
1253
  BYTE const* const ip = (BYTE const*)src;
1013
1254
  U32 contiguous = 1;
@@ -1017,7 +1258,7 @@ MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,
1017
1258
  assert(window->base != NULL);
1018
1259
  assert(window->dictBase != NULL);
1019
1260
  /* Check if blocks follow each other */
1020
- if (src != window->nextSrc) {
1261
+ if (src != window->nextSrc || forceNonContiguous) {
1021
1262
  /* not contiguous */
1022
1263
  size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);
1023
1264
  DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);
@@ -1047,15 +1288,15 @@ MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,
1047
1288
  */
1048
1289
  MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)
1049
1290
  {
1050
- U32 const maxDistance = 1U << windowLog;
1051
- U32 const lowestValid = ms->window.lowLimit;
1052
- U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
1053
- U32 const isDictionary = (ms->loadedDictEnd != 0);
1291
+ U32 const maxDistance = 1U << windowLog;
1292
+ U32 const lowestValid = ms->window.lowLimit;
1293
+ U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
1294
+ U32 const isDictionary = (ms->loadedDictEnd != 0);
1054
1295
  /* When using a dictionary the entire dictionary is valid if a single byte of the dictionary
1055
1296
  * is within the window. We invalidate the dictionary (and set loadedDictEnd to 0) when it isn't
1056
1297
  * valid for the entire block. So this check is sufficient to find the lowest valid match index.
1057
1298
  */
1058
- U32 const matchLowest = isDictionary ? lowestValid : withinWindow;
1299
+ U32 const matchLowest = isDictionary ? lowestValid : withinWindow;
1059
1300
  return matchLowest;
1060
1301
  }
1061
1302
 
@@ -1108,6 +1349,42 @@ MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)
1108
1349
 
1109
1350
  #endif
1110
1351
 
1352
+ /* Short Cache */
1353
+
1354
+ /* Normally, zstd matchfinders follow this flow:
1355
+ * 1. Compute hash at ip
1356
+ * 2. Load index from hashTable[hash]
1357
+ * 3. Check if *ip == *(base + index)
1358
+ * In dictionary compression, loading *(base + index) is often an L2 or even L3 miss.
1359
+ *
1360
+ * Short cache is an optimization which allows us to avoid step 3 most of the time
1361
+ * when the data doesn't actually match. With short cache, the flow becomes:
1362
+ * 1. Compute (hash, currentTag) at ip. currentTag is an 8-bit independent hash at ip.
1363
+ * 2. Load (index, matchTag) from hashTable[hash]. See ZSTD_writeTaggedIndex to understand how this works.
1364
+ * 3. Only if currentTag == matchTag, check *ip == *(base + index). Otherwise, continue.
1365
+ *
1366
+ * Currently, short cache is only implemented in CDict hashtables. Thus, its use is limited to
1367
+ * dictMatchState matchfinders.
1368
+ */
1369
+ #define ZSTD_SHORT_CACHE_TAG_BITS 8
1370
+ #define ZSTD_SHORT_CACHE_TAG_MASK ((1u << ZSTD_SHORT_CACHE_TAG_BITS) - 1)
1371
+
1372
+ /* Helper function for ZSTD_fillHashTable and ZSTD_fillDoubleHashTable.
1373
+ * Unpacks hashAndTag into (hash, tag), then packs (index, tag) into hashTable[hash]. */
1374
+ MEM_STATIC void ZSTD_writeTaggedIndex(U32* const hashTable, size_t hashAndTag, U32 index) {
1375
+ size_t const hash = hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;
1376
+ U32 const tag = (U32)(hashAndTag & ZSTD_SHORT_CACHE_TAG_MASK);
1377
+ assert(index >> (32 - ZSTD_SHORT_CACHE_TAG_BITS) == 0);
1378
+ hashTable[hash] = (index << ZSTD_SHORT_CACHE_TAG_BITS) | tag;
1379
+ }
1380
+
1381
+ /* Helper function for short cache matchfinders.
1382
+ * Unpacks tag1 and tag2 from lower bits of packedTag1 and packedTag2, then checks if the tags match. */
1383
+ MEM_STATIC int ZSTD_comparePackedTags(size_t packedTag1, size_t packedTag2) {
1384
+ U32 const tag1 = packedTag1 & ZSTD_SHORT_CACHE_TAG_MASK;
1385
+ U32 const tag2 = packedTag2 & ZSTD_SHORT_CACHE_TAG_MASK;
1386
+ return tag1 == tag2;
1387
+ }
1111
1388
 
1112
1389
  #if defined (__cplusplus)
1113
1390
  }
@@ -1200,4 +1477,56 @@ size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSe
1200
1477
  * condition for correct operation : hashLog > 1 */
1201
1478
  U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);
1202
1479
 
1480
+ /** ZSTD_CCtx_trace() :
1481
+ * Trace the end of a compression call.
1482
+ */
1483
+ void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);
1484
+
1485
+ /* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of
1486
+ * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.
1487
+ * Note that the block delimiter must include the last literals of the block.
1488
+ */
1489
+ size_t
1490
+ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,
1491
+ ZSTD_sequencePosition* seqPos,
1492
+ const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
1493
+ const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
1494
+
1495
+ /* Returns the number of bytes to move the current read position back by.
1496
+ * Only non-zero if we ended up splitting a sequence.
1497
+ * Otherwise, it may return a ZSTD error if something went wrong.
1498
+ *
1499
+ * This function will attempt to scan through blockSize bytes
1500
+ * represented by the sequences in @inSeqs,
1501
+ * storing any (partial) sequences.
1502
+ *
1503
+ * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
1504
+ * avoid splitting a match, or to avoid splitting a match such that it would produce a match
1505
+ * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
1506
+ */
1507
+ size_t
1508
+ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
1509
+ const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
1510
+ const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
1511
+
1512
+
1513
+ /* ===============================================================
1514
+ * Deprecated definitions that are still used internally to avoid
1515
+ * deprecation warnings. These functions are exactly equivalent to
1516
+ * their public variants, but avoid the deprecation warnings.
1517
+ * =============================================================== */
1518
+
1519
+ size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
1520
+
1521
+ size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
1522
+ void* dst, size_t dstCapacity,
1523
+ const void* src, size_t srcSize);
1524
+
1525
+ size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
1526
+ void* dst, size_t dstCapacity,
1527
+ const void* src, size_t srcSize);
1528
+
1529
+ size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
1530
+
1531
+
1203
1532
  #endif /* ZSTD_COMPRESS_H */