multi_compress 0.6.0 → 0.7.0

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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +51 -0
  3. data/GET_STARTED.md +5 -3
  4. data/README.md +2 -2
  5. data/THIRD_PARTY_NOTICES.md +3 -3
  6. data/ext/multi_compress/exports.darwin +1 -0
  7. data/ext/multi_compress/exports.map +4 -0
  8. data/ext/multi_compress/extconf.rb +20 -0
  9. data/ext/multi_compress/multi_compress.c +352 -149
  10. data/ext/multi_compress/vendor/.vendored +2 -2
  11. data/ext/multi_compress/vendor/brotli/c/common/version.h +2 -2
  12. data/ext/multi_compress/vendor/brotli/c/dec/decode.c +59 -30
  13. data/ext/multi_compress/vendor/brotli/c/include/brotli/decode.h +1 -3
  14. data/ext/multi_compress/vendor/zstd/lib/BUCK +10 -5
  15. data/ext/multi_compress/vendor/zstd/lib/README.md +25 -5
  16. data/ext/multi_compress/vendor/zstd/lib/common/allocations.h +6 -2
  17. data/ext/multi_compress/vendor/zstd/lib/common/bits.h +1 -1
  18. data/ext/multi_compress/vendor/zstd/lib/common/bitstream.h +3 -3
  19. data/ext/multi_compress/vendor/zstd/lib/common/bmi2.h +40 -0
  20. data/ext/multi_compress/vendor/zstd/lib/common/compiler.h +37 -11
  21. data/ext/multi_compress/vendor/zstd/lib/common/entropy_common.c +7 -6
  22. data/ext/multi_compress/vendor/zstd/lib/common/fse_decompress.c +4 -3
  23. data/ext/multi_compress/vendor/zstd/lib/common/pool.c +16 -19
  24. data/ext/multi_compress/vendor/zstd/lib/common/portability_macros.h +31 -0
  25. data/ext/multi_compress/vendor/zstd/lib/common/threading.c +16 -2
  26. data/ext/multi_compress/vendor/zstd/lib/common/zstd_common.c +9 -0
  27. data/ext/multi_compress/vendor/zstd/lib/common/zstd_internal.h +4 -2
  28. data/ext/multi_compress/vendor/zstd/lib/compress/hist.c +300 -3
  29. data/ext/multi_compress/vendor/zstd/lib/compress/hist.h +4 -0
  30. data/ext/multi_compress/vendor/zstd/lib/compress/huf_compress.c +4 -1
  31. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress.c +775 -214
  32. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress_internal.h +35 -6
  33. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress_sequences.c +9 -5
  34. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress_superblock.c +14 -5
  35. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_double_fast.c +2 -2
  36. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_fast.c +2 -2
  37. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_lazy.c +49 -5
  38. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_ldm.c +11 -11
  39. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_ldm.h +11 -0
  40. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_opt.c +16 -18
  41. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_preSplit.c +3 -3
  42. data/ext/multi_compress/vendor/zstd/lib/compress/zstdmt_compress.c +64 -39
  43. data/ext/multi_compress/vendor/zstd/lib/compress/zstdmt_compress.h +30 -2
  44. data/ext/multi_compress/vendor/zstd/lib/decompress/huf_decompress.c +78 -64
  45. data/ext/multi_compress/vendor/zstd/lib/decompress/huf_decompress_amd64.S +182 -18
  46. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_ddict.c +59 -27
  47. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_ddict.h +11 -0
  48. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_decompress.c +194 -93
  49. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_decompress_block.c +225 -85
  50. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_decompress_internal.h +19 -2
  51. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/cover.c +136 -91
  52. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/divsufsort.c +77 -77
  53. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/fastcover.c +48 -42
  54. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/zdict.c +18 -14
  55. data/ext/multi_compress/vendor/zstd/lib/dll/example/build_package.bat +66 -20
  56. data/ext/multi_compress/vendor/zstd/lib/dll/example/fullbench-dll.vcxproj +10 -6
  57. data/ext/multi_compress/vendor/zstd/lib/install_oses.mk +17 -0
  58. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v01.c +10 -8
  59. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v02.c +5 -364
  60. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v03.c +4 -5
  61. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v04.c +7 -3
  62. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v05.c +8 -5
  63. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v06.c +3 -3
  64. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v07.c +1 -0
  65. data/ext/multi_compress/vendor/zstd/lib/libzstd.mk +8 -7
  66. data/ext/multi_compress/vendor/zstd/lib/libzstd.pc.in +1 -0
  67. data/ext/multi_compress/vendor/zstd/lib/module.modulemap +0 -21
  68. data/ext/multi_compress/vendor/zstd/lib/zstd.h +209 -112
  69. data/lib/multi_compress/active_record.rb +11 -5
  70. data/lib/multi_compress/codec.rb +164 -94
  71. data/lib/multi_compress/database/api.rb +42 -0
  72. data/lib/multi_compress/database/decoding.rb +42 -0
  73. data/lib/multi_compress/database/dictionary.rb +72 -0
  74. data/lib/multi_compress/database/encoding.rb +31 -0
  75. data/lib/multi_compress/database/header.rb +71 -0
  76. data/lib/multi_compress/database/operations.rb +73 -0
  77. data/lib/multi_compress/database/validation.rb +95 -0
  78. data/lib/multi_compress/database.rb +10 -282
  79. data/lib/multi_compress/db_deployment/bundle_archiver.rb +70 -0
  80. data/lib/multi_compress/db_deployment/bundle_metadata.rb +56 -0
  81. data/lib/multi_compress/db_deployment/bundle_stager.rb +62 -0
  82. data/lib/multi_compress/db_deployment/commands.rb +309 -0
  83. data/lib/multi_compress/db_deployment/deployment_bundle.rb +80 -0
  84. data/lib/multi_compress/db_deployment/deterministic_tar_writer.rb +76 -0
  85. data/lib/multi_compress/db_deployment/dictionary_registry.rb +244 -0
  86. data/lib/multi_compress/db_deployment/readable_view.rb +112 -0
  87. data/lib/multi_compress/db_deployment/readable_view_options.rb +51 -0
  88. data/lib/multi_compress/db_deployment/sql_identifiers.rb +45 -0
  89. data/lib/multi_compress/db_deployment.rb +10 -844
  90. data/lib/multi_compress/reader/buffer_operations.rb +57 -0
  91. data/lib/multi_compress/reader/read_operations.rb +69 -0
  92. data/lib/multi_compress/reader.rb +97 -0
  93. data/lib/multi_compress/stream_io.rb +13 -0
  94. data/lib/multi_compress/version.rb +1 -1
  95. data/lib/multi_compress/writer.rb +85 -0
  96. data/lib/multi_compress.rb +42 -333
  97. data/multi_compress.gemspec +2 -0
  98. data/mysql_udf/Makefile +12 -5
  99. data/mysql_udf/multi_compress_mysql.exports +6 -0
  100. data/postgres_extension/Makefile +2 -1
  101. data/postgres_extension/test/run_e2e.sh +28 -10
  102. metadata +30 -10
  103. data/ext/multi_compress/vendor/lz4/lib/Makefile +0 -244
  104. data/ext/multi_compress/vendor/lz4/lib/dll/example/Makefile +0 -63
  105. data/ext/multi_compress/vendor/zstd/lib/Makefile +0 -389
  106. data/ext/multi_compress/vendor/zstd/lib/dll/example/Makefile +0 -48
@@ -13,6 +13,7 @@
13
13
  ***************************************/
14
14
  #include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
15
15
  #include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */
16
+ #include "../common/bmi2.h"
16
17
  #include "../common/mem.h"
17
18
  #include "../common/error_private.h"
18
19
  #include "hist.h" /* HIST_countFast_wksp */
@@ -56,6 +57,14 @@
56
57
  # define ZSTD_HASHLOG3_MAX 17
57
58
  #endif
58
59
 
60
+
61
+ /*-*************************************
62
+ * Forward declarations
63
+ ***************************************/
64
+ size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs,
65
+ size_t nbSequences);
66
+
67
+
59
68
  /*-*************************************
60
69
  * Helper functions
61
70
  ***************************************/
@@ -104,7 +113,9 @@ static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
104
113
  assert(cctx != NULL);
105
114
  ZSTD_memset(cctx, 0, sizeof(*cctx));
106
115
  cctx->customMem = memManager;
107
- cctx->bmi2 = ZSTD_cpuSupportsBmi2();
116
+ #if DYNAMIC_BMI2
117
+ ZSTD_SET_BMI2(cctx->bmi2, ZSTD_cpuSupportsBmi2());
118
+ #endif
108
119
  { size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
109
120
  assert(!ZSTD_isError(err));
110
121
  (void)err;
@@ -144,7 +155,9 @@ ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
144
155
  cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
145
156
  cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE);
146
157
  cctx->tmpWkspSize = TMP_WORKSPACE_SIZE;
147
- cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
158
+ #if DYNAMIC_BMI2
159
+ ZSTD_SET_BMI2(cctx->bmi2, ZSTD_cpuSupportsBmi2());
160
+ #endif
148
161
  return cctx;
149
162
  }
150
163
 
@@ -171,10 +184,10 @@ static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
171
184
  {
172
185
  assert(cctx != NULL);
173
186
  assert(cctx->staticSize == 0);
174
- ZSTD_clearAllDicts(cctx);
175
187
  #ifdef ZSTD_MULTITHREAD
176
- ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
188
+ ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL; /* pending jobs may use the dictionary */
177
189
  #endif
190
+ ZSTD_clearAllDicts(cctx);
178
191
  ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
179
192
  }
180
193
 
@@ -237,10 +250,18 @@ static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_Para
237
250
  /* Returns row matchfinder usage given an initial mode and cParams */
238
251
  static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,
239
252
  const ZSTD_compressionParameters* const cParams) {
253
+ #ifdef ZSTD_LINUX_KERNEL
254
+ /* The Linux Kernel does not use SIMD, and 128KB is a very common size, e.g. in BtrFS.
255
+ * The row match finder is slower for this size without SIMD, so disable it.
256
+ */
257
+ const unsigned kWindowLogLowerBound = 17;
258
+ #else
259
+ const unsigned kWindowLogLowerBound = 14;
260
+ #endif
240
261
  if (mode != ZSTD_ps_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */
241
262
  mode = ZSTD_ps_disable;
242
263
  if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;
243
- if (cParams->windowLog > 14) mode = ZSTD_ps_enable;
264
+ if (cParams->windowLog > kWindowLogLowerBound) mode = ZSTD_ps_enable;
244
265
  return mode;
245
266
  }
246
267
 
@@ -1243,6 +1264,13 @@ static int ZSTD_dedicatedDictSearch_isSupported(
1243
1264
  const ZSTD_compressionParameters* cParams);
1244
1265
  static void ZSTD_dedicatedDictSearch_revertCParams(
1245
1266
  ZSTD_compressionParameters* cParams);
1267
+ static size_t ZSTD_createCDict_advanced2_internal(
1268
+ ZSTD_CDict** cdictPtr,
1269
+ const void* dict, size_t dictSize,
1270
+ ZSTD_dictLoadMethod_e dictLoadMethod,
1271
+ ZSTD_dictContentType_e dictContentType,
1272
+ const ZSTD_CCtx_params* originalCctxParams,
1273
+ ZSTD_customMem customMem);
1246
1274
 
1247
1275
  /**
1248
1276
  * Initializes the local dictionary using requested parameters.
@@ -1268,14 +1296,14 @@ static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
1268
1296
  assert(cctx->cdict == NULL);
1269
1297
  assert(cctx->prefixDict.dict == NULL);
1270
1298
 
1271
- dl->cdict = ZSTD_createCDict_advanced2(
1299
+ FORWARD_IF_ERROR(ZSTD_createCDict_advanced2_internal(
1300
+ &dl->cdict,
1272
1301
  dl->dict,
1273
1302
  dl->dictSize,
1274
1303
  ZSTD_dlm_byRef,
1275
1304
  dl->dictContentType,
1276
1305
  &cctx->requestedParams,
1277
- cctx->customMem);
1278
- RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
1306
+ cctx->customMem), "");
1279
1307
  cctx->cdict = dl->cdict;
1280
1308
  return 0;
1281
1309
  }
@@ -1339,6 +1367,15 @@ size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)
1339
1367
  {
1340
1368
  RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1341
1369
  "Can't ref a pool when ctx not in init stage.");
1370
+ #ifdef ZSTD_MULTITHREAD
1371
+ if (pool != cctx->pool) {
1372
+ /* The MT context, created by the first multi-threaded frame and then reused,
1373
+ * runs its jobs on the pool it was created with : without this, the next frames
1374
+ * would still use the previous pool, which the caller may free. No job is running :
1375
+ * the stage is zcss_init, and ZSTDMT_freeCCtx() waits for pending jobs. */
1376
+ ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
1377
+ }
1378
+ #endif
1342
1379
  cctx->pool = pool;
1343
1380
  return 0;
1344
1381
  }
@@ -1368,8 +1405,13 @@ size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
1368
1405
  {
1369
1406
  if ( (reset == ZSTD_reset_session_only)
1370
1407
  || (reset == ZSTD_reset_session_and_parameters) ) {
1408
+ #ifdef ZSTD_MULTITHREAD
1409
+ /* jobs of an abandoned frame may still reference the dictionary */
1410
+ if (cctx->mtctx != NULL) ZSTDMT_waitForPendingJobs(cctx->mtctx);
1411
+ #endif
1371
1412
  cctx->streamStage = zcss_init;
1372
1413
  cctx->pledgedSrcSizePlusOne = 0;
1414
+ cctx->stableIn_notConsumed = 0; /* input pending in the abandoned frame */
1373
1415
  }
1374
1416
  if ( (reset == ZSTD_reset_parameters)
1375
1417
  || (reset == ZSTD_reset_session_and_parameters) ) {
@@ -1755,15 +1797,19 @@ size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1755
1797
  {
1756
1798
  ZSTD_compressionParameters const cParams =
1757
1799
  ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1800
+ ldmParams_t ldmParams = params->ldmParams;
1758
1801
  ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
1759
1802
  &cParams);
1760
1803
 
1761
1804
  RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1805
+ if (ldmParams.enableLdm == ZSTD_ps_enable) {
1806
+ ZSTD_ldm_adjustParameters(&ldmParams, &cParams);
1807
+ }
1762
1808
  /* estimateCCtxSize is for one-shot compression. So no buffers should
1763
1809
  * be needed. However, we still allocate two 0-sized buffers, which can
1764
1810
  * take space under ASAN. */
1765
1811
  return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1766
- &cParams, &params->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1812
+ &cParams, &ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1767
1813
  }
1768
1814
 
1769
1815
  size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
@@ -1813,6 +1859,7 @@ size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1813
1859
  RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1814
1860
  { ZSTD_compressionParameters const cParams =
1815
1861
  ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1862
+ ldmParams_t ldmParams = params->ldmParams;
1816
1863
  size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(params->maxBlockSize), (size_t)1 << cParams.windowLog);
1817
1864
  size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)
1818
1865
  ? ((size_t)1 << cParams.windowLog) + blockSize
@@ -1822,8 +1869,11 @@ size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1822
1869
  : 0;
1823
1870
  ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, &params->cParams);
1824
1871
 
1872
+ if (ldmParams.enableLdm == ZSTD_ps_enable) {
1873
+ ZSTD_ldm_adjustParameters(&ldmParams, &cParams);
1874
+ }
1825
1875
  return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1826
- &cParams, &params->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
1876
+ &cParams, &ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
1827
1877
  ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1828
1878
  }
1829
1879
  }
@@ -2321,6 +2371,20 @@ static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
2321
2371
  * handled in _enforceMaxDist */
2322
2372
  }
2323
2373
 
2374
+ /* Check against the addressable content, which may be smaller than the full
2375
+ * dictionary when only a suffix is loaded. */
2376
+ static size_t ZSTD_checkDictionaryRepCodes(const U32 rep[ZSTD_REP_NUM], size_t dictContentSize)
2377
+ {
2378
+ U32 u;
2379
+ for (u = 0; u < ZSTD_REP_NUM; ++u) {
2380
+ RETURN_ERROR_IF(rep[u] == 0 || rep[u] > dictContentSize,
2381
+ dictionary_corrupted,
2382
+ "repcode %u exceeds dictionary content (%zu bytes)",
2383
+ rep[u], dictContentSize);
2384
+ }
2385
+ return 0;
2386
+ }
2387
+
2324
2388
  static size_t
2325
2389
  ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
2326
2390
  const ZSTD_CDict* cdict,
@@ -2360,6 +2424,9 @@ ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
2360
2424
  /* don't even attach dictionaries with no contents */
2361
2425
  DEBUGLOG(4, "skipping attaching empty dictionary");
2362
2426
  } else {
2427
+ /* Enforce the dictMatchState block compressors' repcode bounds
2428
+ * before allowing them to search this dictionary. */
2429
+ FORWARD_IF_ERROR(ZSTD_checkDictionaryRepCodes(cdict->cBlockState.rep, cdictLen), "");
2363
2430
  DEBUGLOG(4, "attaching dictionary into context");
2364
2431
  cctx->blockState.matchState.dictMatchState = &cdict->matchState;
2365
2432
 
@@ -2503,105 +2570,6 @@ static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
2503
2570
  }
2504
2571
  }
2505
2572
 
2506
- /*! ZSTD_copyCCtx_internal() :
2507
- * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2508
- * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2509
- * The "context", in this case, refers to the hash and chain tables,
2510
- * entropy tables, and dictionary references.
2511
- * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
2512
- * @return : 0, or an error code */
2513
- static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
2514
- const ZSTD_CCtx* srcCCtx,
2515
- ZSTD_frameParameters fParams,
2516
- U64 pledgedSrcSize,
2517
- ZSTD_buffered_policy_e zbuff)
2518
- {
2519
- RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
2520
- "Can't copy a ctx that's not in init stage.");
2521
- DEBUGLOG(5, "ZSTD_copyCCtx_internal");
2522
- ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
2523
- { ZSTD_CCtx_params params = dstCCtx->requestedParams;
2524
- /* Copy only compression parameters related to tables. */
2525
- params.cParams = srcCCtx->appliedParams.cParams;
2526
- assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto);
2527
- assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto);
2528
- assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto);
2529
- params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
2530
- params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter;
2531
- params.ldmParams = srcCCtx->appliedParams.ldmParams;
2532
- params.fParams = fParams;
2533
- params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize;
2534
- ZSTD_resetCCtx_internal(dstCCtx, &params, pledgedSrcSize,
2535
- /* loadedDictSize */ 0,
2536
- ZSTDcrp_leaveDirty, zbuff);
2537
- assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
2538
- assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
2539
- assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
2540
- assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
2541
- assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
2542
- }
2543
-
2544
- ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
2545
-
2546
- /* copy tables */
2547
- { size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
2548
- srcCCtx->appliedParams.useRowMatchFinder,
2549
- 0 /* forDDSDict */)
2550
- ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
2551
- : 0;
2552
- size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
2553
- U32 const h3log = srcCCtx->blockState.matchState.hashLog3;
2554
- size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2555
-
2556
- ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
2557
- srcCCtx->blockState.matchState.hashTable,
2558
- hSize * sizeof(U32));
2559
- ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
2560
- srcCCtx->blockState.matchState.chainTable,
2561
- chainSize * sizeof(U32));
2562
- ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
2563
- srcCCtx->blockState.matchState.hashTable3,
2564
- h3Size * sizeof(U32));
2565
- }
2566
-
2567
- ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
2568
-
2569
- /* copy dictionary offsets */
2570
- {
2571
- const ZSTD_MatchState_t* srcMatchState = &srcCCtx->blockState.matchState;
2572
- ZSTD_MatchState_t* dstMatchState = &dstCCtx->blockState.matchState;
2573
- dstMatchState->window = srcMatchState->window;
2574
- dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2575
- dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2576
- }
2577
- dstCCtx->dictID = srcCCtx->dictID;
2578
- dstCCtx->dictContentSize = srcCCtx->dictContentSize;
2579
-
2580
- /* copy block state */
2581
- ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
2582
-
2583
- return 0;
2584
- }
2585
-
2586
- /*! ZSTD_copyCCtx() :
2587
- * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2588
- * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2589
- * pledgedSrcSize==0 means "unknown".
2590
- * @return : 0, or an error code */
2591
- size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
2592
- {
2593
- ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
2594
- ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy;
2595
- ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
2596
- if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
2597
- fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
2598
-
2599
- return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
2600
- fParams, pledgedSrcSize,
2601
- zbuff);
2602
- }
2603
-
2604
-
2605
2573
  #define ZSTD_ROWSIZE 16
2606
2574
  /*! ZSTD_reduceTable() :
2607
2575
  * reduce table indexes by `reducerValue`, or squash to zero.
@@ -3998,7 +3966,7 @@ static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore)
3998
3966
  /* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).
3999
3967
  * Stores the result in resultSeqStore.
4000
3968
  */
4001
- static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
3969
+ void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
4002
3970
  const SeqStore_t* originalSeqStore,
4003
3971
  size_t startIdx, size_t endIdx)
4004
3972
  {
@@ -4010,7 +3978,7 @@ static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
4010
3978
 
4011
3979
  /* Move longLengthPos into the correct position if necessary */
4012
3980
  if (originalSeqStore->longLengthType != ZSTD_llt_none) {
4013
- if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {
3981
+ if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos >= endIdx) {
4014
3982
  resultSeqStore->longLengthType = ZSTD_llt_none;
4015
3983
  } else {
4016
3984
  resultSeqStore->longLengthPos -= (U32)startIdx;
@@ -4128,7 +4096,7 @@ ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc,
4128
4096
  op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
4129
4097
  srcSize,
4130
4098
  zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
4131
- zc->bmi2);
4099
+ ZSTD_CCtx_get_bmi2(zc));
4132
4100
  FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
4133
4101
 
4134
4102
  if (!zc->isFirstBlock &&
@@ -4190,8 +4158,8 @@ typedef struct {
4190
4158
  * In practice, recursion depth usually doesn't go beyond 4.
4191
4159
  *
4192
4160
  * Furthermore, the number of splits is capped by ZSTD_MAX_NB_BLOCK_SPLITS.
4193
- * At ZSTD_MAX_NB_BLOCK_SPLITS == 196 with the current existing blockSize
4194
- * maximum of 128 KB, this value is actually impossible to reach.
4161
+ * A 128 KiB block containing many 3-byte matches can have enough sequences
4162
+ * for more splits than this limit allows.
4195
4163
  */
4196
4164
  static void
4197
4165
  ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx,
@@ -4225,6 +4193,8 @@ ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t end
4225
4193
  if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {
4226
4194
  DEBUGLOG(5, "split decided at seqNb:%zu", midIdx);
4227
4195
  ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);
4196
+ if (splits->idx >= ZSTD_MAX_NB_BLOCK_SPLITS)
4197
+ return;
4228
4198
  splits->splitLocations[splits->idx] = (U32)midIdx;
4229
4199
  splits->idx++;
4230
4200
  ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);
@@ -4247,6 +4217,7 @@ static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq)
4247
4217
  return 0;
4248
4218
  }
4249
4219
  ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore);
4220
+ assert(splits.idx <= ZSTD_MAX_NB_BLOCK_SPLITS);
4250
4221
  splits.splitLocations[splits.idx] = nbSeq;
4251
4222
  DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1);
4252
4223
  return splits.idx;
@@ -4268,7 +4239,7 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc,
4268
4239
  BYTE* op = (BYTE*)dst;
4269
4240
  size_t i = 0;
4270
4241
  size_t srcBytesTotal = 0;
4271
- U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */
4242
+ U32* const partitions = zc->blockSplitCtx.partitions; /* includes the final block boundary */
4272
4243
  SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore;
4273
4244
  SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore;
4274
4245
  size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
@@ -4418,7 +4389,7 @@ ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
4418
4389
  dst, dstCapacity,
4419
4390
  srcSize,
4420
4391
  zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
4421
- zc->bmi2);
4392
+ ZSTD_CCtx_get_bmi2(zc));
4422
4393
 
4423
4394
  if (frame &&
4424
4395
  /* We don't want to emit our first block as a RLE even if it qualifies because
@@ -5101,9 +5072,11 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
5101
5072
  size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
5102
5073
  RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
5103
5074
  RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
5075
+ /* The optimal parser reads every symbol's cost, including absent ones.
5076
+ * FSE_readNCount() zero-fills the omitted normalized counts. */
5104
5077
  RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5105
5078
  bs->entropy.fse.matchlengthCTable,
5106
- matchlengthNCount, matchlengthMaxValue, matchlengthLog,
5079
+ matchlengthNCount, MaxML, matchlengthLog,
5107
5080
  workspace, HUF_WORKSPACE_SIZE)),
5108
5081
  dictionary_corrupted, "");
5109
5082
  bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
@@ -5115,9 +5088,10 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
5115
5088
  size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
5116
5089
  RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
5117
5090
  RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
5091
+ /* As above, initialize costs for the full symbol range. */
5118
5092
  RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5119
5093
  bs->entropy.fse.litlengthCTable,
5120
- litlengthNCount, litlengthMaxValue, litlengthLog,
5094
+ litlengthNCount, MaxLL, litlengthLog,
5121
5095
  workspace, HUF_WORKSPACE_SIZE)),
5122
5096
  dictionary_corrupted, "");
5123
5097
  bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
@@ -5139,12 +5113,9 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
5139
5113
  /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
5140
5114
  bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
5141
5115
 
5142
- /* All repCodes must be <= dictContentSize and != 0 */
5143
- { U32 u;
5144
- for (u=0; u<3; u++) {
5145
- RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
5146
- RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
5147
- } } }
5116
+ /* The format permits nonzero repcodes up to the full content size. */
5117
+ FORWARD_IF_ERROR(ZSTD_checkDictionaryRepCodes(bs->rep, dictContentSize), "");
5118
+ }
5148
5119
 
5149
5120
  return (size_t)(dictPtr - (const BYTE*)dict);
5150
5121
  }
@@ -5154,7 +5125,8 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
5154
5125
  * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
5155
5126
  */
5156
5127
  /*! ZSTD_loadZstdDictionary() :
5157
- * @return : dictID, or an error code
5128
+ * @return : 0 on success, or an error code (check with ZSTD_isError()).
5129
+ * On success, the dictionary's ID is written into @dictIDPtr.
5158
5130
  * assumptions : magic number supposed already checked
5159
5131
  * dictSize supposed >= 8
5160
5132
  */
@@ -5165,11 +5137,12 @@ static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
5165
5137
  const void* dict, size_t dictSize,
5166
5138
  ZSTD_dictTableLoadMethod_e dtlm,
5167
5139
  ZSTD_tableFillPurpose_e tfp,
5168
- void* workspace)
5140
+ void* workspace,
5141
+ U32* dictIDPtr)
5169
5142
  {
5170
5143
  const BYTE* dictPtr = (const BYTE*)dict;
5171
5144
  const BYTE* const dictEnd = dictPtr + dictSize;
5172
- size_t dictID;
5145
+ U32 dictID;
5173
5146
  size_t eSize;
5174
5147
  ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
5175
5148
  assert(dictSize >= 8);
@@ -5185,11 +5158,26 @@ static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
5185
5158
  FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
5186
5159
  ms, NULL, ws, params, dictPtr, dictContentSize, dtlm, tfp), "");
5187
5160
  }
5188
- return dictID;
5161
+ if (tfp == ZSTD_tfp_forCDict) {
5162
+ /* The matchfinder may retain only a suffix of a large dictionary.
5163
+ * In particular, short-cache CDicts retain at most (1 << 24) - 2
5164
+ * bytes. Recheck the repcodes against the actual window so that
5165
+ * dictMatchState searches cannot underflow their match indices. */
5166
+ U32 const loadedDictSize = (U32)(ms->window.nextSrc - ms->window.base) - ms->window.lowLimit;
5167
+ assert((U32)(ms->window.nextSrc - ms->window.base) >= ms->window.lowLimit);
5168
+ FORWARD_IF_ERROR(ZSTD_checkDictionaryRepCodes(bs->rep, loadedDictSize), "");
5169
+ }
5170
+ *dictIDPtr = dictID;
5171
+ return 0;
5189
5172
  }
5190
5173
 
5191
5174
  /** ZSTD_compress_insertDictionary() :
5192
- * @return : dictID, or an error code */
5175
+ * @return : 0 on success, or an error code (check with ZSTD_isError()).
5176
+ * @dictIDPtr is always written: with the dictionary's ID on success,
5177
+ * or 0 if there is no ID (or on error).
5178
+ * The ID is reported through @dictIDPtr rather than the return value,
5179
+ * because any value close to (size_t)-1 is interpreted as an error code,
5180
+ * which would reject valid 32-bit dictIDs on 32-bit builds. */
5193
5181
  static size_t
5194
5182
  ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
5195
5183
  ZSTD_MatchState_t* ms,
@@ -5200,9 +5188,11 @@ ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
5200
5188
  ZSTD_dictContentType_e dictContentType,
5201
5189
  ZSTD_dictTableLoadMethod_e dtlm,
5202
5190
  ZSTD_tableFillPurpose_e tfp,
5203
- void* workspace)
5191
+ void* workspace,
5192
+ U32* dictIDPtr)
5204
5193
  {
5205
5194
  DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
5195
+ *dictIDPtr = 0;
5206
5196
  if ((dict==NULL) || (dictSize<8)) {
5207
5197
  RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
5208
5198
  return 0;
@@ -5226,7 +5216,7 @@ ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
5226
5216
 
5227
5217
  /* dict as full zstd dictionary */
5228
5218
  return ZSTD_loadZstdDictionary(
5229
- bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace);
5219
+ bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace, dictIDPtr);
5230
5220
  }
5231
5221
 
5232
5222
  #define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
@@ -5264,19 +5254,19 @@ static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
5264
5254
  FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
5265
5255
  dictContentSize,
5266
5256
  ZSTDcrp_makeClean, zbuff) , "");
5267
- { size_t const dictID = cdict ?
5257
+ { U32 dictID = 0;
5258
+ size_t const dictStatus = cdict ?
5268
5259
  ZSTD_compress_insertDictionary(
5269
5260
  cctx->blockState.prevCBlock, &cctx->blockState.matchState,
5270
5261
  &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
5271
5262
  cdict->dictContentSize, cdict->dictContentType, dtlm,
5272
- ZSTD_tfp_forCCtx, cctx->tmpWorkspace)
5263
+ ZSTD_tfp_forCCtx, cctx->tmpWorkspace, &dictID)
5273
5264
  : ZSTD_compress_insertDictionary(
5274
5265
  cctx->blockState.prevCBlock, &cctx->blockState.matchState,
5275
5266
  &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
5276
- dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace);
5277
- FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
5278
- assert(dictID <= UINT_MAX);
5279
- cctx->dictID = (U32)dictID;
5267
+ dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace, &dictID);
5268
+ FORWARD_IF_ERROR(dictStatus, "ZSTD_compress_insertDictionary failed");
5269
+ cctx->dictID = dictID;
5280
5270
  cctx->dictContentSize = dictContentSize;
5281
5271
  }
5282
5272
  return 0;
@@ -5516,6 +5506,29 @@ size_t ZSTD_compress(void* dst, size_t dstCapacity,
5516
5506
 
5517
5507
  /* ===== Dictionary API ===== */
5518
5508
 
5509
+ /* Returns the CDict workspace size, or an error if the dictionary copy would
5510
+ * overflow while rounding, adding sanitizer redzones, or adding the workspace
5511
+ * overhead. All by-copy CDict creation paths must use this calculation before
5512
+ * reserving or copying the dictionary. */
5513
+ static size_t ZSTD_estimateCDictSize_internal(size_t dictSize,
5514
+ size_t matchStateSize,
5515
+ ZSTD_dictLoadMethod_e dictLoadMethod)
5516
+ {
5517
+ size_t const baseSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5518
+ + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5519
+ + matchStateSize;
5520
+ if (dictLoadMethod == ZSTD_dlm_byRef) return baseSize;
5521
+ {
5522
+ size_t const alignedDictSize = ZSTD_cwksp_align(dictSize, sizeof(void*));
5523
+ size_t const dictAllocSize = ZSTD_cwksp_alloc_size(alignedDictSize);
5524
+ RETURN_ERROR_IF(alignedDictSize < dictSize || dictAllocSize < alignedDictSize,
5525
+ memory_allocation, "CDict size overflow");
5526
+ RETURN_ERROR_IF(dictAllocSize > (size_t)-1 - baseSize,
5527
+ memory_allocation, "CDict workspace size overflow");
5528
+ return baseSize + dictAllocSize;
5529
+ }
5530
+ }
5531
+
5519
5532
  /*! ZSTD_estimateCDictSize_advanced() :
5520
5533
  * Estimate amount of memory that will be needed to create a dictionary with following arguments */
5521
5534
  size_t ZSTD_estimateCDictSize_advanced(
@@ -5523,14 +5536,12 @@ size_t ZSTD_estimateCDictSize_advanced(
5523
5536
  ZSTD_dictLoadMethod_e dictLoadMethod)
5524
5537
  {
5525
5538
  DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
5526
- return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5527
- + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5528
- /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
5529
- * in case we are using DDS with row-hash. */
5530
- + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams),
5531
- /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)
5532
- + (dictLoadMethod == ZSTD_dlm_byRef ? 0
5533
- : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
5539
+ /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
5540
+ * in case we are using DDS with row-hash. */
5541
+ return ZSTD_estimateCDictSize_internal(dictSize,
5542
+ ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams),
5543
+ /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0),
5544
+ dictLoadMethod);
5534
5545
  }
5535
5546
 
5536
5547
  size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
@@ -5588,13 +5599,14 @@ static size_t ZSTD_initCDict_internal(
5588
5599
  */
5589
5600
  { params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
5590
5601
  params.fParams.contentSizeFlag = 1;
5591
- { size_t const dictID = ZSTD_compress_insertDictionary(
5602
+ { U32 dictID = 0;
5603
+ size_t const dictStatus = ZSTD_compress_insertDictionary(
5592
5604
  &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
5593
5605
  &params, cdict->dictContent, cdict->dictContentSize,
5594
- dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace);
5595
- FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
5596
- assert(dictID <= (size_t)(U32)-1);
5597
- cdict->dictID = (U32)dictID;
5606
+ dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace,
5607
+ &dictID);
5608
+ FORWARD_IF_ERROR(dictStatus, "ZSTD_compress_insertDictionary failed");
5609
+ cdict->dictID = dictID;
5598
5610
  }
5599
5611
  }
5600
5612
 
@@ -5612,16 +5624,15 @@ ZSTD_createCDict_advanced_internal(size_t dictSize,
5612
5624
  if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
5613
5625
  DEBUGLOG(3, "ZSTD_createCDict_advanced_internal (dictSize=%u)", (unsigned)dictSize);
5614
5626
 
5615
- { size_t const workspaceSize =
5616
- ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
5617
- ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
5618
- ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
5619
- (dictLoadMethod == ZSTD_dlm_byRef ? 0
5620
- : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
5621
- void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
5627
+ { size_t const workspaceSize = ZSTD_estimateCDictSize_internal(dictSize,
5628
+ ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0),
5629
+ dictLoadMethod);
5630
+ void* workspace;
5622
5631
  ZSTD_cwksp ws;
5623
5632
  ZSTD_CDict* cdict;
5624
5633
 
5634
+ if (ZSTD_isError(workspaceSize)) return NULL;
5635
+ workspace = ZSTD_customMalloc(workspaceSize, customMem);
5625
5636
  if (!workspace) {
5626
5637
  ZSTD_customFree(workspace, customMem);
5627
5638
  return NULL;
@@ -5657,7 +5668,10 @@ ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
5657
5668
  &cctxParams, customMem);
5658
5669
  }
5659
5670
 
5660
- ZSTD_CDict* ZSTD_createCDict_advanced2(
5671
+ /* Preserve initialization errors for internal callers. The public constructors
5672
+ * retain their pointer-or-NULL API. On failure, *cdictPtr remains NULL. */
5673
+ static size_t ZSTD_createCDict_advanced2_internal(
5674
+ ZSTD_CDict** cdictPtr,
5661
5675
  const void* dict, size_t dictSize,
5662
5676
  ZSTD_dictLoadMethod_e dictLoadMethod,
5663
5677
  ZSTD_dictContentType_e dictContentType,
@@ -5668,8 +5682,10 @@ ZSTD_CDict* ZSTD_createCDict_advanced2(
5668
5682
  ZSTD_compressionParameters cParams;
5669
5683
  ZSTD_CDict* cdict;
5670
5684
 
5685
+ *cdictPtr = NULL;
5671
5686
  DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
5672
- if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
5687
+ RETURN_ERROR_IF((!customMem.customAlloc) ^ (!customMem.customFree),
5688
+ parameter_combination_unsupported, "Invalid custom allocator");
5673
5689
 
5674
5690
  if (cctxParams.enableDedicatedDictSearch) {
5675
5691
  cParams = ZSTD_dedicatedDictSearch_getCParams(
@@ -5696,14 +5712,33 @@ ZSTD_CDict* ZSTD_createCDict_advanced2(
5696
5712
  cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
5697
5713
  customMem);
5698
5714
 
5699
- if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict,
5700
- dict, dictSize,
5701
- dictLoadMethod, dictContentType,
5702
- cctxParams) )) {
5703
- ZSTD_freeCDict(cdict);
5704
- return NULL;
5715
+ RETURN_ERROR_IF(!cdict, memory_allocation, "Could not allocate CDict");
5716
+ { size_t const err = ZSTD_initCDict_internal(cdict,
5717
+ dict, dictSize,
5718
+ dictLoadMethod, dictContentType,
5719
+ cctxParams);
5720
+ if (ZSTD_isError(err)) {
5721
+ ZSTD_freeCDict(cdict);
5722
+ return err;
5723
+ }
5705
5724
  }
5706
5725
 
5726
+ *cdictPtr = cdict;
5727
+ return 0;
5728
+ }
5729
+
5730
+ ZSTD_CDict* ZSTD_createCDict_advanced2(
5731
+ const void* dict, size_t dictSize,
5732
+ ZSTD_dictLoadMethod_e dictLoadMethod,
5733
+ ZSTD_dictContentType_e dictContentType,
5734
+ const ZSTD_CCtx_params* originalCctxParams,
5735
+ ZSTD_customMem customMem)
5736
+ {
5737
+ ZSTD_CDict* cdict;
5738
+ size_t const err = ZSTD_createCDict_advanced2_internal(
5739
+ &cdict, dict, dictSize, dictLoadMethod, dictContentType,
5740
+ originalCctxParams, customMem);
5741
+ if (ZSTD_isError(err)) return NULL;
5707
5742
  return cdict;
5708
5743
  }
5709
5744
 
@@ -5765,16 +5800,13 @@ const ZSTD_CDict* ZSTD_initStaticCDict(
5765
5800
  ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams);
5766
5801
  /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
5767
5802
  size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
5768
- size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5769
- + (dictLoadMethod == ZSTD_dlm_byRef ? 0
5770
- : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
5771
- + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5772
- + matchStateSize;
5803
+ size_t const neededSize = ZSTD_estimateCDictSize_internal(dictSize, matchStateSize, dictLoadMethod);
5773
5804
  ZSTD_CDict* cdict;
5774
5805
  ZSTD_CCtx_params params;
5775
5806
 
5776
5807
  DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize);
5777
5808
  if ((size_t)workspace & 7) return NULL; /* 8-aligned */
5809
+ if (ZSTD_isError(neededSize) || workspaceSize < neededSize) return NULL;
5778
5810
 
5779
5811
  {
5780
5812
  ZSTD_cwksp ws;
@@ -5784,8 +5816,6 @@ const ZSTD_CDict* ZSTD_initStaticCDict(
5784
5816
  ZSTD_cwksp_move(&cdict->workspace, &ws);
5785
5817
  }
5786
5818
 
5787
- if (workspaceSize < neededSize) return NULL;
5788
-
5789
5819
  ZSTD_CCtxParams_init(&params, 0);
5790
5820
  params.cParams = cParams;
5791
5821
  params.useRowMatchFinder = useRowMatchFinder;
@@ -6460,14 +6490,15 @@ size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
6460
6490
  if (cctx->streamStage == zcss_init) {
6461
6491
  size_t const inputSize = input->size - input->pos; /* no obligation to start from pos==0 */
6462
6492
  size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed;
6493
+ if (cctx->stableIn_notConsumed) { /* not the first time */
6494
+ /* check stable source guarantees, including when this call starts compression */
6495
+ RETURN_ERROR_IF(cctx->requestedParams.inBufferMode != ZSTD_bm_stable, stabilityCondition_notRespected, "stableInBuffer condition not respected: disabled while input is pending");
6496
+ RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");
6497
+ RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");
6498
+ }
6463
6499
  if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */
6464
6500
  && (endOp == ZSTD_e_continue) /* no flush requested, more input to come */
6465
6501
  && (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) { /* not even reached one block yet */
6466
- if (cctx->stableIn_notConsumed) { /* not the first time */
6467
- /* check stable source guarantees */
6468
- RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");
6469
- RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");
6470
- }
6471
6502
  /* pretend input was consumed, to give a sense forward progress */
6472
6503
  input->pos = input->size;
6473
6504
  /* save stable inBuffer, for later control, and flush/end */
@@ -6487,6 +6518,21 @@ size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
6487
6518
  #ifdef ZSTD_MULTITHREAD
6488
6519
  if (cctx->appliedParams.nbWorkers > 0) {
6489
6520
  size_t flushMin;
6521
+ /* control src size before handing input to workers :
6522
+ * once a job is posted, its output can no longer be withheld.
6523
+ * Once the frame is ended, remaining input belongs to the next frame. */
6524
+ if ( (cctx->pledgedSrcSizePlusOne != 0)
6525
+ && (!ZSTDMT_isFrameEnded(cctx->mtctx)) ) {
6526
+ U64 const srcSizeIfAllConsumed = cctx->consumedSrcSize + cctx->stableIn_notConsumed + (U64)(input->size - input->pos);
6527
+ ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
6528
+ RETURN_ERROR_IF(
6529
+ (srcSizeIfAllConsumed+1 > cctx->pledgedSrcSizePlusOne)
6530
+ || ((endOp == ZSTD_e_end) && (srcSizeIfAllConsumed+1 != cctx->pledgedSrcSizePlusOne)),
6531
+ srcSize_wrong,
6532
+ "error : pledgedSrcSize = %u, while realSrcSize = %u",
6533
+ (unsigned)cctx->pledgedSrcSizePlusOne-1,
6534
+ (unsigned)srcSizeIfAllConsumed);
6535
+ }
6490
6536
  if (cctx->cParamsChanged) {
6491
6537
  ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
6492
6538
  cctx->cParamsChanged = 0;
@@ -6506,8 +6552,11 @@ size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
6506
6552
  cctx->producedCSize += (U64)(output->pos - opos);
6507
6553
  if ( ZSTD_isError(flushMin)
6508
6554
  || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
6509
- if (flushMin == 0)
6555
+ if (flushMin == 0) {
6556
+ /* src size was controlled before handing input to workers */
6557
+ assert(cctx->pledgedSrcSizePlusOne == 0 || cctx->pledgedSrcSizePlusOne == cctx->consumedSrcSize+1);
6510
6558
  ZSTD_CCtx_trace(cctx, 0);
6559
+ }
6511
6560
  ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
6512
6561
  }
6513
6562
  FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
@@ -6749,8 +6798,8 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6749
6798
  ZSTD_ParamSwitch_e externalRepSearch)
6750
6799
  {
6751
6800
  U32 idx = seqPos->idx;
6752
- U32 startPosInSequence = seqPos->posInSequence;
6753
- U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
6801
+ U64 startPosInSequence = seqPos->posInSequence;
6802
+ U64 endPosInSequence = seqPos->posInSequence + blockSize;
6754
6803
  size_t dictSize;
6755
6804
  const BYTE* const istart = (const BYTE*)(src);
6756
6805
  const BYTE* ip = istart;
@@ -6769,40 +6818,41 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6769
6818
  } else {
6770
6819
  dictSize = 0;
6771
6820
  }
6772
- DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
6821
+ DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %llu blockSize: %zu", idx, (unsigned long long)startPosInSequence, blockSize);
6773
6822
  DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
6774
6823
  ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
6775
6824
  while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
6776
6825
  const ZSTD_Sequence currSeq = inSeqs[idx];
6777
6826
  U32 litLength = currSeq.litLength;
6778
6827
  U32 matchLength = currSeq.matchLength;
6828
+ U64 const sequenceLength = (U64)litLength + matchLength;
6779
6829
  U32 const rawOffset = currSeq.offset;
6780
6830
  U32 offBase;
6781
6831
 
6782
6832
  /* Modify the sequence depending on where endPosInSequence lies */
6783
- if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
6833
+ if (endPosInSequence >= sequenceLength) {
6784
6834
  if (startPosInSequence >= litLength) {
6785
6835
  startPosInSequence -= litLength;
6786
6836
  litLength = 0;
6787
- matchLength -= startPosInSequence;
6837
+ matchLength -= (U32)startPosInSequence;
6788
6838
  } else {
6789
- litLength -= startPosInSequence;
6839
+ litLength -= (U32)startPosInSequence;
6790
6840
  }
6791
6841
  /* Move to the next sequence */
6792
- endPosInSequence -= currSeq.litLength + currSeq.matchLength;
6842
+ endPosInSequence -= sequenceLength;
6793
6843
  startPosInSequence = 0;
6794
6844
  } else {
6795
6845
  /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
6796
6846
  does not reach the end of the match. So, we have to split the sequence */
6797
- DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
6798
- currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
6847
+ DEBUGLOG(6, "Require a split: diff: %llu, idx: %u PIS: %llu",
6848
+ (unsigned long long)(sequenceLength - endPosInSequence), idx, (unsigned long long)endPosInSequence);
6799
6849
  if (endPosInSequence > litLength) {
6800
6850
  U32 firstHalfMatchLength;
6801
- litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
6802
- firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
6851
+ litLength = startPosInSequence >= litLength ? 0 : litLength - (U32)startPosInSequence;
6852
+ firstHalfMatchLength = (U32)(endPosInSequence - startPosInSequence) - litLength;
6803
6853
  if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
6804
6854
  /* Only ever split the match if it is larger than the block size */
6805
- U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
6855
+ U32 secondHalfMatchLength = (U32)(sequenceLength - endPosInSequence);
6806
6856
  if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
6807
6857
  /* Move the endPosInSequence backward so that it creates match of minMatch length */
6808
6858
  endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
@@ -6819,7 +6869,7 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6819
6869
  * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
6820
6870
  * would cause the first half of the match to be too small
6821
6871
  */
6822
- bytesAdjustment = endPosInSequence - currSeq.litLength;
6872
+ bytesAdjustment = (U32)(endPosInSequence - currSeq.litLength);
6823
6873
  endPosInSequence = currSeq.litLength;
6824
6874
  break;
6825
6875
  }
@@ -6828,6 +6878,8 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6828
6878
  break;
6829
6879
  }
6830
6880
  }
6881
+ /* The sequence now fits in this block, so its lengths can be added in U32. */
6882
+ assert((U64)litLength + matchLength <= blockSize);
6831
6883
  /* Check if this offset can be represented with a repcode */
6832
6884
  { U32 const ll0 = (litLength == 0);
6833
6885
  offBase = ZSTD_finalizeOffBase(rawOffset, updatedRepcodes.rep, ll0);
@@ -6849,7 +6901,7 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6849
6901
  idx++; /* Next Sequence */
6850
6902
  }
6851
6903
  DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
6852
- assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
6904
+ assert(idx == inSeqsSize || endPosInSequence <= (U64)inSeqs[idx].litLength + inSeqs[idx].matchLength);
6853
6905
  seqPos->idx = idx;
6854
6906
  seqPos->posInSequence = endPosInSequence;
6855
6907
  ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
@@ -6896,13 +6948,15 @@ static size_t
6896
6948
  blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos)
6897
6949
  {
6898
6950
  int end = 0;
6899
- size_t blockSize = 0;
6951
+ U64 blockSize = 0;
6900
6952
  size_t spos = seqPos.idx;
6901
6953
  DEBUGLOG(6, "blockSize_explicitDelimiter : seq %zu / %zu", spos, inSeqsSize);
6902
6954
  assert(spos <= inSeqsSize);
6903
6955
  while (spos < inSeqsSize) {
6904
6956
  end = (inSeqs[spos].offset == 0);
6905
- blockSize += inSeqs[spos].litLength + inSeqs[spos].matchLength;
6957
+ blockSize += (U64)inSeqs[spos].litLength + inSeqs[spos].matchLength;
6958
+ RETURN_ERROR_IF(blockSize > ZSTD_BLOCKSIZE_MAX, externalSequences_invalid,
6959
+ "sequences incorrectly define a too large block");
6906
6960
  if (end) {
6907
6961
  if (inSeqs[spos].matchLength != 0)
6908
6962
  RETURN_ERROR(externalSequences_invalid, "delimiter format error : both matchlength and offset must be == 0");
@@ -6912,7 +6966,7 @@ blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD
6912
6966
  }
6913
6967
  if (!end)
6914
6968
  RETURN_ERROR(externalSequences_invalid, "Reached end of sequences without finding a block delimiter");
6915
- return blockSize;
6969
+ return (size_t)blockSize;
6916
6970
  }
6917
6971
 
6918
6972
  static size_t determine_blockSize(ZSTD_SequenceFormat_e mode,
@@ -7005,7 +7059,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
7005
7059
  op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
7006
7060
  blockSize,
7007
7061
  cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
7008
- cctx->bmi2);
7062
+ ZSTD_CCtx_get_bmi2(cctx));
7009
7063
  FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
7010
7064
  DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
7011
7065
 
@@ -7076,6 +7130,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
7076
7130
  /* Begin writing output, starting with frame header */
7077
7131
  { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
7078
7132
  &cctx->appliedParams, srcSize, cctx->dictID);
7133
+ FORWARD_IF_ERROR(frameHeaderSize, "ZSTD_writeFrameHeader failed");
7079
7134
  op += frameHeaderSize;
7080
7135
  assert(frameHeaderSize <= dstCapacity);
7081
7136
  dstCapacity -= frameHeaderSize;
@@ -7110,7 +7165,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
7110
7165
  }
7111
7166
 
7112
7167
 
7113
- #if defined(__AVX2__)
7168
+ #if defined(ZSTD_ARCH_X86_AVX2)
7114
7169
 
7115
7170
  #include <immintrin.h> /* AVX2 intrinsics */
7116
7171
 
@@ -7130,7 +7185,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
7130
7185
  * @returns > 0 if there is one long length (> 65535),
7131
7186
  * indicating the position, and type.
7132
7187
  */
7133
- static size_t convertSequences_noRepcodes(
7188
+ size_t convertSequences_noRepcodes(
7134
7189
  SeqDef* dstSeqs,
7135
7190
  const ZSTD_Sequence* inSeqs,
7136
7191
  size_t nbSequences)
@@ -7276,13 +7331,378 @@ static size_t convertSequences_noRepcodes(
7276
7331
  return longLen;
7277
7332
  }
7278
7333
 
7334
+ #elif defined (ZSTD_ARCH_RISCV_RVV)
7335
+ #include <riscv_vector.h>
7336
+ /*
7337
+ * Convert `vl` sequences per iteration, using RVV intrinsics:
7338
+ * - offset -> offBase = offset + 2
7339
+ * - litLength -> (U16) litLength
7340
+ * - matchLength -> (U16)(matchLength - 3)
7341
+ * - rep is ignored
7342
+ * Store only 8 bytes per SeqDef (offBase[4], litLength[2], mlBase[2]).
7343
+ *
7344
+ * @returns 0 on succes, with no long length detected
7345
+ * @returns > 0 if there is one long length (> 65535),
7346
+ * indicating the position, and type.
7347
+ */
7348
+ size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) {
7349
+ size_t longLen = 0;
7350
+ size_t vl = 0;
7351
+ typedef uint32_t __attribute__((may_alias)) aliased_u32;
7352
+ /* RVV depends on the specific definition of target structures */
7353
+ ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7354
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7355
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7356
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7357
+ ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7358
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7359
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7360
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7361
+
7362
+ for (size_t i = 0; i < nbSequences; i += vl) {
7363
+
7364
+ vl = __riscv_vsetvl_e32m2(nbSequences-i);
7365
+ {
7366
+ // Loading structure member variables
7367
+ vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4(
7368
+ (const aliased_u32*)((const void*)&inSeqs[i]),
7369
+ vl
7370
+ );
7371
+ vuint32m2_t v_offset = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 0);
7372
+ vuint32m2_t v_lit = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 1);
7373
+ vuint32m2_t v_match = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 2);
7374
+ // offset + ZSTD_REP_NUM
7375
+ vuint32m2_t v_offBase = __riscv_vadd_vx_u32m2(v_offset, ZSTD_REP_NUM, vl);
7376
+ // Check for integer overflow
7377
+ // Cast to a 16-bit variable
7378
+ vbool16_t lit_overflow = __riscv_vmsgtu_vx_u32m2_b16(v_lit, 65535, vl);
7379
+ vuint16m1_t v_lit_clamped = __riscv_vncvt_x_x_w_u16m1(v_lit, vl);
7380
+
7381
+ vbool16_t ml_overflow = __riscv_vmsgtu_vx_u32m2_b16(v_match, 65535+MINMATCH, vl);
7382
+ vuint16m1_t v_ml_clamped = __riscv_vncvt_x_x_w_u16m1(__riscv_vsub_vx_u32m2(v_match, MINMATCH, vl), vl);
7383
+
7384
+ // Pack two 16-bit fields into a 32-bit value (little-endian)
7385
+ // The lower 16 bits contain litLength, and the upper 16 bits contain mlBase
7386
+ vuint32m2_t v_lit_ml_combined = __riscv_vsll_vx_u32m2(
7387
+ __riscv_vwcvtu_x_x_v_u32m2(v_ml_clamped, vl), // Convert matchLength to 32-bit
7388
+ 16,
7389
+ vl
7390
+ );
7391
+ v_lit_ml_combined = __riscv_vor_vv_u32m2(
7392
+ v_lit_ml_combined,
7393
+ __riscv_vwcvtu_x_x_v_u32m2(v_lit_clamped, vl),
7394
+ vl
7395
+ );
7396
+ {
7397
+ // Create a vector of SeqDef structures
7398
+ // Store the offBase, litLength, and mlBase in a vector of SeqDef
7399
+ vuint32m2x2_t store_data = __riscv_vcreate_v_u32m2x2(
7400
+ v_offBase,
7401
+ v_lit_ml_combined
7402
+ );
7403
+ __riscv_vsseg2e32_v_u32m2x2(
7404
+ (aliased_u32*)((void*)&dstSeqs[i]),
7405
+ store_data,
7406
+ vl
7407
+ );
7408
+ }
7409
+ {
7410
+ // Find the first index where an overflow occurs
7411
+ int first_ml = __riscv_vfirst_m_b16(ml_overflow, vl);
7412
+ int first_lit = __riscv_vfirst_m_b16(lit_overflow, vl);
7413
+
7414
+ if (UNLIKELY(first_ml != -1)) {
7415
+ assert(longLen == 0);
7416
+ longLen = i + first_ml + 1;
7417
+ }
7418
+ if (UNLIKELY(first_lit != -1)) {
7419
+ assert(longLen == 0);
7420
+ longLen = i + first_lit + 1 + nbSequences;
7421
+ }
7422
+ }
7423
+ }
7424
+ }
7425
+ return longLen;
7426
+ }
7427
+
7279
7428
  /* the vector implementation could also be ported to SSSE3,
7280
7429
  * but since this implementation is targeting modern systems (>= Sapphire Rapid),
7281
7430
  * it's not useful to develop and maintain code for older pre-AVX2 platforms */
7282
7431
 
7283
- #else /* no AVX2 */
7432
+ #elif defined(ZSTD_ARCH_ARM_SVE2)
7433
+
7434
+ /*
7435
+ * Checks if any active element in a signed 8-bit integer vector is greater
7436
+ * than zero.
7437
+ *
7438
+ * @param g Governing predicate selecting active lanes.
7439
+ * @param a Input vector of signed 8-bit integers.
7440
+ *
7441
+ * @return True if any active element in `a` is > 0, false otherwise.
7442
+ */
7443
+ FORCE_INLINE_TEMPLATE int cmpgtz_any_s8(svbool_t g, svint8_t a)
7444
+ {
7445
+ svbool_t ptest = svcmpgt_n_s8(g, a, 0);
7446
+ return svptest_any(ptest, ptest);
7447
+ }
7284
7448
 
7285
- static size_t convertSequences_noRepcodes(
7449
+ size_t convertSequences_noRepcodes(
7450
+ SeqDef* dstSeqs,
7451
+ const ZSTD_Sequence* inSeqs,
7452
+ size_t nbSequences)
7453
+ {
7454
+ /* Process the input with `8 * VL / element` lanes. */
7455
+ const size_t lanes = 8 * svcntb() / sizeof(ZSTD_Sequence);
7456
+ size_t longLen = 0;
7457
+ size_t n = 0;
7458
+
7459
+ /* SVE permutation depends on the specific definition of target structures. */
7460
+ ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7461
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7462
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7463
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7464
+ ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7465
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7466
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7467
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7468
+
7469
+ if (nbSequences >= lanes) {
7470
+ const svbool_t ptrue = svptrue_b8();
7471
+ /* 16-bit of {ZSTD_REP_NUM, 0, -MINMATCH, 0} extended to 32-bit lanes. */
7472
+ const svuint32_t vaddition = svreinterpret_u32(
7473
+ svunpklo_s32(svreinterpret_s16(svdup_n_u64(ZSTD_REP_NUM | (((U64)(U16)-MINMATCH) << 32)))));
7474
+ /* For permutation of 16-bit units: 0, 1, 2, 4, 8, 9, 10, 12, ... */
7475
+ const svuint16_t vmask = svreinterpret_u16(
7476
+ svindex_u64(0x0004000200010000, 0x0008000800080008));
7477
+ /* Upper bytes of `litLength` and `matchLength` will be packed into the
7478
+ * middle of overflow check vector. */
7479
+ const svbool_t pmid = svcmpne_n_u8(
7480
+ ptrue, svreinterpret_u8(svdup_n_u64(0x0000FFFFFFFF0000)), 0);
7481
+
7482
+ do {
7483
+ /* Load `lanes` number of `ZSTD_Sequence` into 8 vectors. */
7484
+ const svuint32_t vin0 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 0);
7485
+ const svuint32_t vin1 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 1);
7486
+ const svuint32_t vin2 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 2);
7487
+ const svuint32_t vin3 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 3);
7488
+ const svuint32_t vin4 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 4);
7489
+ const svuint32_t vin5 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 5);
7490
+ const svuint32_t vin6 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 6);
7491
+ const svuint32_t vin7 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 7);
7492
+
7493
+ /* Add {ZSTD_REP_NUM, 0, -MINMATCH, 0} to each structures. */
7494
+ const svuint16x2_t vadd01 = svcreate2_u16(
7495
+ svreinterpret_u16(svadd_u32_x(ptrue, vin0, vaddition)),
7496
+ svreinterpret_u16(svadd_u32_x(ptrue, vin1, vaddition)));
7497
+ const svuint16x2_t vadd23 = svcreate2_u16(
7498
+ svreinterpret_u16(svadd_u32_x(ptrue, vin2, vaddition)),
7499
+ svreinterpret_u16(svadd_u32_x(ptrue, vin3, vaddition)));
7500
+ const svuint16x2_t vadd45 = svcreate2_u16(
7501
+ svreinterpret_u16(svadd_u32_x(ptrue, vin4, vaddition)),
7502
+ svreinterpret_u16(svadd_u32_x(ptrue, vin5, vaddition)));
7503
+ const svuint16x2_t vadd67 = svcreate2_u16(
7504
+ svreinterpret_u16(svadd_u32_x(ptrue, vin6, vaddition)),
7505
+ svreinterpret_u16(svadd_u32_x(ptrue, vin7, vaddition)));
7506
+
7507
+ /* Shuffle and pack bytes so each vector contains SeqDef structures. */
7508
+ const svuint16_t vout01 = svtbl2_u16(vadd01, vmask);
7509
+ const svuint16_t vout23 = svtbl2_u16(vadd23, vmask);
7510
+ const svuint16_t vout45 = svtbl2_u16(vadd45, vmask);
7511
+ const svuint16_t vout67 = svtbl2_u16(vadd67, vmask);
7512
+
7513
+ /* Pack the upper 16-bits of 32-bit lanes for overflow check. */
7514
+ const svuint16_t voverflow01 = svuzp2_u16(svget2_u16(vadd01, 0),
7515
+ svget2_u16(vadd01, 1));
7516
+ const svuint16_t voverflow23 = svuzp2_u16(svget2_u16(vadd23, 0),
7517
+ svget2_u16(vadd23, 1));
7518
+ const svuint16_t voverflow45 = svuzp2_u16(svget2_u16(vadd45, 0),
7519
+ svget2_u16(vadd45, 1));
7520
+ const svuint16_t voverflow67 = svuzp2_u16(svget2_u16(vadd67, 0),
7521
+ svget2_u16(vadd67, 1));
7522
+
7523
+ /* We don't need the whole 16 bits of the overflow part. Only 1 bit
7524
+ * is needed, so we pack tightly and merge multiple vectors to be
7525
+ * able to use a single comparison to handle the overflow case.
7526
+ * However, we also need to handle the possible negative values of
7527
+ * matchLength parts, so we use signed comparison later. */
7528
+ const svint8_t voverflow =
7529
+ svmax_s8_x(pmid,
7530
+ svtrn1_s8(svreinterpret_s8(voverflow01),
7531
+ svreinterpret_s8(voverflow23)),
7532
+ svtrn1_s8(svreinterpret_s8(voverflow45),
7533
+ svreinterpret_s8(voverflow67)));
7534
+
7535
+ /* Store `lanes` number of `SeqDef` structures from 4 vectors. */
7536
+ svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 0, svreinterpret_u32(vout01));
7537
+ svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 1, svreinterpret_u32(vout23));
7538
+ svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 2, svreinterpret_u32(vout45));
7539
+ svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 3, svreinterpret_u32(vout67));
7540
+
7541
+ /* Check if any enabled lanes of the overflow vector is larger than
7542
+ * zero, only one such may happen. */
7543
+ if (UNLIKELY(cmpgtz_any_s8(pmid, voverflow))) {
7544
+ /* Scalar search for long match is needed because we merged
7545
+ * multiple overflow bytes with `max`. */
7546
+ size_t i;
7547
+ for (i = n; i < n + lanes; i++) {
7548
+ if (inSeqs[i].matchLength > 65535 + MINMATCH) {
7549
+ assert(longLen == 0);
7550
+ longLen = i + 1;
7551
+ }
7552
+ if (inSeqs[i].litLength > 65535) {
7553
+ assert(longLen == 0);
7554
+ longLen = i + nbSequences + 1;
7555
+ }
7556
+ }
7557
+ }
7558
+
7559
+ n += lanes;
7560
+ } while(n <= nbSequences - lanes);
7561
+ }
7562
+
7563
+ /* Handle remaining elements. */
7564
+ for (; n < nbSequences; n++) {
7565
+ dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);
7566
+ dstSeqs[n].litLength = (U16)inSeqs[n].litLength;
7567
+ dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);
7568
+ /* Check for long length > 65535. */
7569
+ if (UNLIKELY(inSeqs[n].matchLength > 65535 + MINMATCH)) {
7570
+ assert(longLen == 0);
7571
+ longLen = n + 1;
7572
+ }
7573
+ if (UNLIKELY(inSeqs[n].litLength > 65535)) {
7574
+ assert(longLen == 0);
7575
+ longLen = n + nbSequences + 1;
7576
+ }
7577
+ }
7578
+ return longLen;
7579
+ }
7580
+
7581
+ #elif defined(ZSTD_ARCH_ARM_NEON) && (defined(__aarch64__) || defined(_M_ARM64))
7582
+
7583
+ size_t convertSequences_noRepcodes(
7584
+ SeqDef* dstSeqs,
7585
+ const ZSTD_Sequence* inSeqs,
7586
+ size_t nbSequences)
7587
+ {
7588
+ size_t longLen = 0;
7589
+ size_t n = 0;
7590
+
7591
+ /* Neon permutation depends on the specific definition of target structures. */
7592
+ ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7593
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7594
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7595
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7596
+ ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7597
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7598
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7599
+ ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7600
+
7601
+ if (nbSequences > 3) {
7602
+ static const ZSTD_ALIGNED(16) U32 constAddition[4] = {
7603
+ ZSTD_REP_NUM, 0, -MINMATCH, 0
7604
+ };
7605
+ static const ZSTD_ALIGNED(16) U8 constMask[16] = {
7606
+ 0, 1, 2, 3, 4, 5, 8, 9, 16, 17, 18, 19, 20, 21, 24, 25
7607
+ };
7608
+ static const ZSTD_ALIGNED(16) U16 constCounter[8] = {
7609
+ 1, 1, 1, 1, 2, 2, 2, 2
7610
+ };
7611
+
7612
+ const uint32x4_t vaddition = vld1q_u32(constAddition);
7613
+ const uint8x16_t vmask = vld1q_u8(constMask);
7614
+ uint16x8_t vcounter = vld1q_u16(constCounter);
7615
+ uint16x8_t vindex01 = vdupq_n_u16(0);
7616
+ uint16x8_t vindex23 = vdupq_n_u16(0);
7617
+
7618
+ do {
7619
+ /* Load 4 ZSTD_Sequence (64 bytes). */
7620
+ const uint32x4_t vin0 = vld1q_u32(&inSeqs[n + 0].offset);
7621
+ const uint32x4_t vin1 = vld1q_u32(&inSeqs[n + 1].offset);
7622
+ const uint32x4_t vin2 = vld1q_u32(&inSeqs[n + 2].offset);
7623
+ const uint32x4_t vin3 = vld1q_u32(&inSeqs[n + 3].offset);
7624
+
7625
+ /* Add {ZSTD_REP_NUM, 0, -MINMATCH, 0} to each vector. */
7626
+ const uint8x16x2_t vadd01 = { {
7627
+ vreinterpretq_u8_u32(vaddq_u32(vin0, vaddition)),
7628
+ vreinterpretq_u8_u32(vaddq_u32(vin1, vaddition)),
7629
+ } };
7630
+ const uint8x16x2_t vadd23 = { {
7631
+ vreinterpretq_u8_u32(vaddq_u32(vin2, vaddition)),
7632
+ vreinterpretq_u8_u32(vaddq_u32(vin3, vaddition)),
7633
+ } };
7634
+
7635
+ /* Shuffle and pack bytes so each vector contains 2 SeqDef structures. */
7636
+ const uint8x16_t vout01 = vqtbl2q_u8(vadd01, vmask);
7637
+ const uint8x16_t vout23 = vqtbl2q_u8(vadd23, vmask);
7638
+
7639
+ /* Pack the upper 16-bits of 32-bit lanes for overflow check. */
7640
+ uint16x8_t voverflow01 = vuzp2q_u16(vreinterpretq_u16_u8(vadd01.val[0]),
7641
+ vreinterpretq_u16_u8(vadd01.val[1]));
7642
+ uint16x8_t voverflow23 = vuzp2q_u16(vreinterpretq_u16_u8(vadd23.val[0]),
7643
+ vreinterpretq_u16_u8(vadd23.val[1]));
7644
+
7645
+ /* Store 4 SeqDef structures. */
7646
+ vst1q_u32(&dstSeqs[n + 0].offBase, vreinterpretq_u32_u8(vout01));
7647
+ vst1q_u32(&dstSeqs[n + 2].offBase, vreinterpretq_u32_u8(vout23));
7648
+
7649
+ /* Create masks in case of overflow. */
7650
+ voverflow01 = vcgtzq_s16(vreinterpretq_s16_u16(voverflow01));
7651
+ voverflow23 = vcgtzq_s16(vreinterpretq_s16_u16(voverflow23));
7652
+
7653
+ /* Update overflow indices. */
7654
+ vindex01 = vbslq_u16(voverflow01, vcounter, vindex01);
7655
+ vindex23 = vbslq_u16(voverflow23, vcounter, vindex23);
7656
+
7657
+ /* Update counter for overflow check. */
7658
+ vcounter = vaddq_u16(vcounter, vdupq_n_u16(4));
7659
+
7660
+ n += 4;
7661
+ } while(n < nbSequences - 3);
7662
+
7663
+ /* Fixup indices in the second vector, we saved an additional counter
7664
+ in the loop to update the second overflow index, we need to add 2
7665
+ here when the indices are not 0. */
7666
+ { uint16x8_t nonzero = vtstq_u16(vindex23, vindex23);
7667
+ vindex23 = vsubq_u16(vindex23, nonzero);
7668
+ vindex23 = vsubq_u16(vindex23, nonzero);
7669
+ }
7670
+
7671
+ /* Merge indices in the vectors, maximums are needed. */
7672
+ vindex01 = vmaxq_u16(vindex01, vindex23);
7673
+ vindex01 = vmaxq_u16(vindex01, vextq_u16(vindex01, vindex01, 4));
7674
+
7675
+ /* Compute `longLen`, maximums of matchLength and litLength
7676
+ with a preference on litLength. */
7677
+ { U64 maxLitMatchIndices = vgetq_lane_u64(vreinterpretq_u64_u16(vindex01), 0);
7678
+ size_t maxLitIndex = (maxLitMatchIndices >> 16) & 0xFFFF;
7679
+ size_t maxMatchIndex = (maxLitMatchIndices >> 32) & 0xFFFF;
7680
+ longLen = maxLitIndex > maxMatchIndex ? maxLitIndex + nbSequences
7681
+ : maxMatchIndex;
7682
+ }
7683
+ }
7684
+
7685
+ /* Handle remaining elements. */
7686
+ for (; n < nbSequences; n++) {
7687
+ dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);
7688
+ dstSeqs[n].litLength = (U16)inSeqs[n].litLength;
7689
+ dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);
7690
+ /* Check for long length > 65535. */
7691
+ if (UNLIKELY(inSeqs[n].matchLength > 65535 + MINMATCH)) {
7692
+ assert(longLen == 0);
7693
+ longLen = n + 1;
7694
+ }
7695
+ if (UNLIKELY(inSeqs[n].litLength > 65535)) {
7696
+ assert(longLen == 0);
7697
+ longLen = n + nbSequences + 1;
7698
+ }
7699
+ }
7700
+ return longLen;
7701
+ }
7702
+
7703
+ #else /* No vectorization. */
7704
+
7705
+ size_t convertSequences_noRepcodes(
7286
7706
  SeqDef* dstSeqs,
7287
7707
  const ZSTD_Sequence* inSeqs,
7288
7708
  size_t nbSequences)
@@ -7293,7 +7713,7 @@ static size_t convertSequences_noRepcodes(
7293
7713
  dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);
7294
7714
  dstSeqs[n].litLength = (U16)inSeqs[n].litLength;
7295
7715
  dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);
7296
- /* check for long length > 65535 */
7716
+ /* Check for long length > 65535. */
7297
7717
  if (UNLIKELY(inSeqs[n].matchLength > 65535+MINMATCH)) {
7298
7718
  assert(longLen == 0);
7299
7719
  longLen = n + 1;
@@ -7443,34 +7863,172 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7443
7863
  }
7444
7864
  }
7445
7865
 
7446
- #else
7866
+ #elif defined (ZSTD_ARCH_RISCV_RVV)
7447
7867
 
7448
7868
  BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7449
7869
  {
7450
7870
  size_t totalMatchSize = 0;
7451
7871
  size_t litSize = 0;
7452
- size_t n;
7453
- assert(seqs);
7454
- for (n=0; n<nbSeqs; n++) {
7455
- totalMatchSize += seqs[n].matchLength;
7456
- litSize += seqs[n].litLength;
7457
- if (seqs[n].matchLength == 0) {
7458
- assert(seqs[n].offset == 0);
7872
+ size_t i = 0;
7873
+ int found_terminator = 0;
7874
+ size_t vl_max = __riscv_vsetvlmax_e32m1();
7875
+ typedef uint32_t __attribute__((may_alias)) aliased_u32;
7876
+ vuint32m1_t v_lit_sum = __riscv_vmv_v_x_u32m1(0, vl_max);
7877
+ vuint32m1_t v_match_sum = __riscv_vmv_v_x_u32m1(0, vl_max);
7878
+
7879
+ for (; i < nbSeqs; ) {
7880
+ size_t vl = __riscv_vsetvl_e32m2(nbSeqs - i);
7881
+
7882
+ vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4(
7883
+ (const aliased_u32*)((const void*)&seqs[i]),
7884
+ vl
7885
+ );
7886
+ vuint32m2_t v_lit = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 1);
7887
+ vuint32m2_t v_match = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 2);
7888
+
7889
+ // Check if any element has a matchLength of 0
7890
+ vbool16_t mask = __riscv_vmseq_vx_u32m2_b16(v_match, 0, vl);
7891
+ int first_zero = __riscv_vfirst_m_b16(mask, vl);
7892
+
7893
+ if (first_zero >= 0) {
7894
+ // Find the first zero byte and set the effective length to that index + 1 to
7895
+ // recompute the cumulative vector length of literals and matches
7896
+ vl = first_zero + 1;
7897
+
7898
+ // recompute the cumulative vector length of literals and matches
7899
+ v_lit_sum = __riscv_vredsum_vs_u32m2_u32m1(__riscv_vslidedown_vx_u32m2(v_lit, 0, vl), v_lit_sum, vl);
7900
+ v_match_sum = __riscv_vredsum_vs_u32m2_u32m1(__riscv_vslidedown_vx_u32m2(v_match, 0, vl), v_match_sum, vl);
7901
+
7902
+ i += vl;
7903
+ found_terminator = 1;
7904
+ assert(seqs[i - 1].offset == 0);
7459
7905
  break;
7906
+ } else {
7907
+
7908
+ v_lit_sum = __riscv_vredsum_vs_u32m2_u32m1(v_lit, v_lit_sum, vl);
7909
+ v_match_sum = __riscv_vredsum_vs_u32m2_u32m1(v_match, v_match_sum, vl);
7910
+ i += vl;
7460
7911
  }
7461
7912
  }
7462
- if (n==nbSeqs) {
7913
+ litSize = __riscv_vmv_x_s_u32m1_u32(v_lit_sum);
7914
+ totalMatchSize = __riscv_vmv_x_s_u32m1_u32(v_match_sum);
7915
+
7916
+ if (!found_terminator && i==nbSeqs) {
7463
7917
  BlockSummary bs;
7464
7918
  bs.nbSequences = ERROR(externalSequences_invalid);
7465
7919
  return bs;
7466
7920
  }
7467
7921
  { BlockSummary bs;
7468
- bs.nbSequences = n+1;
7922
+ bs.nbSequences = i;
7469
7923
  bs.blockSize = litSize + totalMatchSize;
7470
7924
  bs.litSize = litSize;
7471
7925
  return bs;
7472
7926
  }
7473
7927
  }
7928
+
7929
+ #else
7930
+
7931
+ /*
7932
+ * The function assumes `litMatchLength` is a packed 64-bit value where the
7933
+ * lower 32 bits represent the match length. The check varies based on the
7934
+ * system's endianness:
7935
+ * - On little-endian systems, it verifies if the entire 64-bit value is at most
7936
+ * 0xFFFFFFFF, indicating the match length (lower 32 bits) is zero.
7937
+ * - On big-endian systems, it directly checks if the lower 32 bits are zero.
7938
+ *
7939
+ * @returns 1 if the match length is zero, 0 otherwise.
7940
+ */
7941
+ FORCE_INLINE_TEMPLATE int matchLengthHalfIsZero(U64 litMatchLength)
7942
+ {
7943
+ if (MEM_isLittleEndian()) {
7944
+ return litMatchLength <= 0xFFFFFFFFULL;
7945
+ } else {
7946
+ return (U32)litMatchLength == 0;
7947
+ }
7948
+ }
7949
+
7950
+ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7951
+ {
7952
+ /* Use multiple accumulators for efficient use of wide out-of-order machines. */
7953
+ U64 litMatchSize0 = 0;
7954
+ U64 litMatchSize1 = 0;
7955
+ U64 litMatchSize2 = 0;
7956
+ U64 litMatchSize3 = 0;
7957
+ size_t n = 0;
7958
+
7959
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) + 4 == offsetof(ZSTD_Sequence, matchLength));
7960
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) + 4 == offsetof(ZSTD_Sequence, rep));
7961
+ assert(seqs);
7962
+
7963
+ if (nbSeqs > 3) {
7964
+ /* Process the input in 4 independent streams to reach high throughput. */
7965
+ do {
7966
+ /* Load `litLength` and `matchLength` as a packed `U64`. It is safe
7967
+ * to use 64-bit unsigned arithmetic here because the sum of `litLength`
7968
+ * and `matchLength` cannot exceed the block size, so the 32-bit
7969
+ * subparts will never overflow. */
7970
+ U64 litMatchLength = MEM_read64(&seqs[n].litLength);
7971
+ litMatchSize0 += litMatchLength;
7972
+ if (matchLengthHalfIsZero(litMatchLength)) {
7973
+ assert(seqs[n].offset == 0);
7974
+ goto _out;
7975
+ }
7976
+
7977
+ litMatchLength = MEM_read64(&seqs[n + 1].litLength);
7978
+ litMatchSize1 += litMatchLength;
7979
+ if (matchLengthHalfIsZero(litMatchLength)) {
7980
+ n += 1;
7981
+ assert(seqs[n].offset == 0);
7982
+ goto _out;
7983
+ }
7984
+
7985
+ litMatchLength = MEM_read64(&seqs[n + 2].litLength);
7986
+ litMatchSize2 += litMatchLength;
7987
+ if (matchLengthHalfIsZero(litMatchLength)) {
7988
+ n += 2;
7989
+ assert(seqs[n].offset == 0);
7990
+ goto _out;
7991
+ }
7992
+
7993
+ litMatchLength = MEM_read64(&seqs[n + 3].litLength);
7994
+ litMatchSize3 += litMatchLength;
7995
+ if (matchLengthHalfIsZero(litMatchLength)) {
7996
+ n += 3;
7997
+ assert(seqs[n].offset == 0);
7998
+ goto _out;
7999
+ }
8000
+
8001
+ n += 4;
8002
+ } while(n < nbSeqs - 3);
8003
+ }
8004
+
8005
+ for (; n < nbSeqs; n++) {
8006
+ U64 litMatchLength = MEM_read64(&seqs[n].litLength);
8007
+ litMatchSize0 += litMatchLength;
8008
+ if (matchLengthHalfIsZero(litMatchLength)) {
8009
+ assert(seqs[n].offset == 0);
8010
+ goto _out;
8011
+ }
8012
+ }
8013
+ /* At this point n == nbSeqs, so no end terminator. */
8014
+ { BlockSummary bs;
8015
+ bs.nbSequences = ERROR(externalSequences_invalid);
8016
+ return bs;
8017
+ }
8018
+ _out:
8019
+ litMatchSize0 += litMatchSize1 + litMatchSize2 + litMatchSize3;
8020
+ { BlockSummary bs;
8021
+ bs.nbSequences = n + 1;
8022
+ if (MEM_isLittleEndian()) {
8023
+ bs.litSize = (U32)litMatchSize0;
8024
+ bs.blockSize = bs.litSize + (litMatchSize0 >> 32);
8025
+ } else {
8026
+ bs.litSize = litMatchSize0 >> 32;
8027
+ bs.blockSize = bs.litSize + (U32)litMatchSize0;
8028
+ }
8029
+ return bs;
8030
+ }
8031
+ }
7474
8032
  #endif
7475
8033
 
7476
8034
 
@@ -7506,6 +8064,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx,
7506
8064
  FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block");
7507
8065
  assert(block.nbSequences <= nbSequences);
7508
8066
  RETURN_ERROR_IF(block.litSize > litSize, externalSequences_invalid, "discrepancy: Sequences require more literals than present in buffer");
8067
+ RETURN_ERROR_IF(block.blockSize > cctx->blockSizeMax, externalSequences_invalid, "sequences incorrectly define a too large block");
7509
8068
  ZSTD_resetSeqStore(&cctx->seqStore);
7510
8069
 
7511
8070
  conversionStatus = ZSTD_convertBlockSequences(cctx,
@@ -7530,7 +8089,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx,
7530
8089
  &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
7531
8090
  &cctx->appliedParams,
7532
8091
  cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
7533
- cctx->bmi2);
8092
+ ZSTD_CCtx_get_bmi2(cctx));
7534
8093
  FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
7535
8094
  /* note: the spec forbids for any compressed block to be larger than maximum block size */
7536
8095
  if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0;
@@ -7594,7 +8153,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
7594
8153
  /* Transparent initialization stage, same as compressStream2() */
7595
8154
  DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity);
7596
8155
  assert(cctx != NULL);
7597
- if (litCapacity < litSize) {
8156
+ if (litCapacity < litSize || litCapacity - litSize < 8) {
7598
8157
  RETURN_ERROR(workSpace_tooSmall, "literals buffer is not large enough: must be at least 8 bytes larger than litSize (risk of read out-of-bound)");
7599
8158
  }
7600
8159
  FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize), "CCtx initialization failed");
@@ -7612,6 +8171,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
7612
8171
  /* Begin writing output, starting with frame header */
7613
8172
  { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
7614
8173
  &cctx->appliedParams, decompressedSize, cctx->dictID);
8174
+ FORWARD_IF_ERROR(frameHeaderSize, "ZSTD_writeFrameHeader failed");
7615
8175
  op += frameHeaderSize;
7616
8176
  assert(frameHeaderSize <= dstCapacity);
7617
8177
  dstCapacity -= frameHeaderSize;
@@ -7638,7 +8198,8 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
7638
8198
  static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs)
7639
8199
  {
7640
8200
  const ZSTD_inBuffer nullInput = { NULL, 0, 0 };
7641
- const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
8201
+ const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable)
8202
+ || (zcs->stableIn_notConsumed > 0); /* pending input, parameters not applied yet */
7642
8203
  return stableInput ? zcs->expectedInBuffer : nullInput;
7643
8204
  }
7644
8205