Skip to main content

libzstd_rs_sys/lib/compress/
zstd_compress.rs

1use core::ptr;
2
3use crate::lib::polyfill::PointerExt;
4
5pub type ZSTD_CCtx = ZSTD_CCtx_s;
6#[repr(C)]
7pub struct ZSTD_CCtx_s {
8    pub(super) stage: ZSTD_compressionStage_e,
9    pub(super) cParamsChanged: core::ffi::c_int,
10    pub(super) bmi2: core::ffi::c_int,
11    pub(super) requestedParams: ZSTD_CCtx_params,
12    pub(super) appliedParams: ZSTD_CCtx_params,
13    pub(super) simpleApiParams: ZSTD_CCtx_params,
14    pub(super) dictID: u32,
15    pub(super) dictContentSize: size_t,
16    pub(super) workspace: ZSTD_cwksp,
17    pub(super) blockSizeMax: size_t,
18    pub(super) pledgedSrcSizePlusOne: core::ffi::c_ulonglong,
19    pub(super) consumedSrcSize: core::ffi::c_ulonglong,
20    pub(super) producedCSize: core::ffi::c_ulonglong,
21    pub(super) xxhState: XXH64_state_t,
22    pub(super) customMem: ZSTD_customMem,
23    pub(super) pool: *mut ZSTD_threadPool,
24    pub(super) staticSize: size_t,
25    pub(super) seqCollector: SeqCollector,
26    pub(super) isFirstBlock: core::ffi::c_int,
27    pub(super) initialized: core::ffi::c_int,
28    pub(super) seqStore: SeqStore_t,
29    pub(super) ldmState: ldmState_t,
30    pub(super) ldmSequences: *mut rawSeq,
31    pub(super) maxNbLdmSequences: size_t,
32    pub(super) externSeqStore: RawSeqStore_t,
33    pub(super) blockState: ZSTD_blockState_t,
34    pub(super) tmpWorkspace: *mut core::ffi::c_void,
35    pub(super) tmpWkspSize: size_t,
36    pub(super) bufferedPolicy: ZSTD_buffered_policy_e,
37    pub(super) inBuff: *mut u8,
38    pub(super) inBuffSize: size_t,
39    pub(super) inToCompress: size_t,
40    pub(super) inBuffPos: size_t,
41    pub(super) inBuffTarget: size_t,
42    pub(super) outBuff: *mut u8,
43    pub(super) outBuffSize: size_t,
44    pub(super) outBuffContentSize: size_t,
45    pub(super) outBuffFlushedSize: size_t,
46    pub(super) streamStage: ZSTD_cStreamStage,
47    pub(super) frameEnded: u32,
48    pub(super) expectedInBuffer: ZSTD_inBuffer,
49    pub(super) stableIn_notConsumed: size_t,
50    pub(super) expectedOutBufferSize: size_t,
51    pub(super) localDict: ZSTD_localDict,
52    pub(super) cdict: *const ZSTD_CDict,
53    pub(super) prefixDict: ZSTD_prefixDict,
54    pub(super) mtctx: *mut ZSTDMT_CCtx,
55    pub(super) traceCtx: ZSTD_TraceCtx,
56    pub(super) blockSplitCtx: ZSTD_blockSplitCtx,
57    pub(super) extSeqBuf: *mut ZSTD_Sequence,
58    pub(super) extSeqBufCapacity: size_t,
59}
60#[derive(Copy, Clone)]
61#[repr(C)]
62pub struct ZSTD_Sequence {
63    pub offset: core::ffi::c_uint,
64    pub litLength: core::ffi::c_uint,
65    pub matchLength: core::ffi::c_uint,
66    pub rep: core::ffi::c_uint,
67}
68#[derive(Copy, Clone)]
69#[repr(C)]
70pub struct ZSTD_blockSplitCtx {
71    pub fullSeqStoreChunk: SeqStore_t,
72    pub firstHalfSeqStore: SeqStore_t,
73    pub secondHalfSeqStore: SeqStore_t,
74    pub currSeqStore: SeqStore_t,
75    pub nextSeqStore: SeqStore_t,
76    pub partitions: [u32; 196],
77    pub entropyMetadata: ZSTD_entropyCTablesMetadata_t,
78}
79#[derive(Copy, Clone)]
80#[repr(C)]
81pub struct ZSTD_entropyCTablesMetadata_t {
82    pub hufMetadata: ZSTD_hufCTablesMetadata_t,
83    pub fseMetadata: ZSTD_fseCTablesMetadata_t,
84}
85#[derive(Copy, Clone)]
86#[repr(C)]
87pub struct ZSTD_fseCTablesMetadata_t {
88    pub llType: SymbolEncodingType_e,
89    pub ofType: SymbolEncodingType_e,
90    pub mlType: SymbolEncodingType_e,
91    pub fseTablesBuffer: [u8; 133],
92    pub fseTablesSize: size_t,
93    pub lastCountSize: size_t,
94}
95pub type SymbolEncodingType_e = core::ffi::c_uint;
96pub const set_repeat: SymbolEncodingType_e = 3;
97pub const set_compressed: SymbolEncodingType_e = 2;
98pub const set_rle: SymbolEncodingType_e = 1;
99pub const set_basic: SymbolEncodingType_e = 0;
100#[derive(Copy, Clone)]
101#[repr(C)]
102pub struct ZSTD_hufCTablesMetadata_t {
103    pub hType: SymbolEncodingType_e,
104    pub hufDesBuffer: [u8; 128],
105    pub hufDesSize: size_t,
106}
107#[derive(Copy, Clone)]
108#[repr(C)]
109pub struct SeqStore_t {
110    pub sequencesStart: *mut SeqDef,
111    pub sequences: *mut SeqDef,
112    pub litStart: *mut u8,
113    pub lit: *mut u8,
114    pub llCode: *mut u8,
115    pub mlCode: *mut u8,
116    pub ofCode: *mut u8,
117    pub maxNbSeq: size_t,
118    pub maxNbLit: size_t,
119    pub longLengthType: ZSTD_longLengthType_e,
120    pub longLengthPos: u32,
121}
122pub type SeqDef = SeqDef_s;
123#[derive(Copy, Clone)]
124#[repr(C)]
125pub struct SeqDef_s {
126    pub offBase: u32,
127    pub litLength: u16,
128    pub mlBase: u16,
129}
130pub type ZSTD_prefixDict = ZSTD_prefixDict_s;
131#[derive(Copy, Clone)]
132#[repr(C)]
133pub struct ZSTD_prefixDict_s {
134    pub dict: *const core::ffi::c_void,
135    pub dictSize: size_t,
136    pub dictContentType: ZSTD_dictContentType_e,
137}
138pub type ZSTD_CDict = ZSTD_CDict_s;
139#[repr(C)]
140pub struct ZSTD_CDict_s {
141    pub dictContent: *const core::ffi::c_void,
142    pub dictContentSize: size_t,
143    pub dictContentType: ZSTD_dictContentType_e,
144    pub entropyWorkspace: *mut u32,
145    pub workspace: ZSTD_cwksp,
146    pub matchState: ZSTD_MatchState_t,
147    pub cBlockState: ZSTD_compressedBlockState_t,
148    pub customMem: ZSTD_customMem,
149    pub dictID: u32,
150    pub compressionLevel: core::ffi::c_int,
151    pub useRowMatchFinder: ZSTD_ParamSwitch_e,
152}
153
154#[repr(u32)]
155#[derive(Copy, Clone, PartialEq, Eq)]
156pub enum ParamSwitch {
157    Auto = 0,
158    Enable = 1,
159    Disable = 2,
160}
161
162impl TryFrom<i32> for ParamSwitch {
163    type Error = ();
164
165    fn try_from(value: i32) -> Result<Self, Self::Error> {
166        match value {
167            0 => Ok(Self::Auto),
168            1 => Ok(Self::Enable),
169            2 => Ok(Self::Disable),
170            _ => Err(()),
171        }
172    }
173}
174
175#[derive(Copy, Clone)]
176#[repr(C)]
177pub struct ZSTD_compressedBlockState_t {
178    pub entropy: ZSTD_entropyCTables_t,
179    pub rep: [u32; 3],
180}
181#[derive(Copy, Clone)]
182#[repr(C)]
183pub struct ZSTD_entropyCTables_t {
184    pub huf: ZSTD_hufCTables_t,
185    pub fse: ZSTD_fseCTables_t,
186}
187#[derive(Copy, Clone)]
188#[repr(C)]
189pub struct ZSTD_fseCTables_t {
190    pub offcodeCTable: [FSE_CTable; 193],
191    pub matchlengthCTable: [FSE_CTable; 363],
192    pub litlengthCTable: [FSE_CTable; 329],
193    pub offcode_repeatMode: FSE_repeat,
194    pub matchlength_repeatMode: FSE_repeat,
195    pub litlength_repeatMode: FSE_repeat,
196}
197#[derive(Copy, Clone)]
198#[repr(C)]
199pub struct ZSTD_hufCTables_t {
200    pub CTable: [HUF_CElt; 257],
201    pub repeatMode: HUF_repeat,
202}
203#[repr(C)]
204pub struct ZSTD_MatchState_t {
205    pub window: ZSTD_window_t,
206    pub loadedDictEnd: u32,
207    pub nextToUpdate: u32,
208    pub hashLog3: u32,
209    pub rowHashLog: u32,
210    pub tagTable: *mut u8,
211    pub hashCache: [u32; 8],
212    pub hashSalt: u64,
213    pub hashSaltEntropy: u32,
214    pub hashTable: *mut u32,
215    pub hashTable3: *mut u32,
216    pub chainTable: *mut u32,
217    pub forceNonContiguous: core::ffi::c_int,
218    pub dedicatedDictSearch: core::ffi::c_int,
219    pub opt: optState_t,
220    pub dictMatchState: *const ZSTD_MatchState_t,
221    pub cParams: ZSTD_compressionParameters,
222    pub ldmSeqStore: *const RawSeqStore_t,
223    pub prefetchCDictTables: core::ffi::c_int,
224    pub lazySkipping: core::ffi::c_int,
225}
226#[derive(Copy, Clone)]
227#[repr(C)]
228pub struct RawSeqStore_t {
229    pub seq: *mut rawSeq,
230    pub pos: size_t,
231    pub posInSequence: size_t,
232    pub size: size_t,
233    pub capacity: size_t,
234}
235#[derive(Copy, Clone)]
236#[repr(C)]
237pub struct rawSeq {
238    pub offset: u32,
239    pub litLength: u32,
240    pub matchLength: u32,
241}
242#[repr(C)]
243pub struct optState_t {
244    pub litFreq: *mut core::ffi::c_uint,
245    pub litLengthFreq: *mut core::ffi::c_uint,
246    pub matchLengthFreq: *mut core::ffi::c_uint,
247    pub offCodeFreq: *mut core::ffi::c_uint,
248    pub matchTable: *mut ZSTD_match_t,
249    pub priceTable: *mut ZSTD_optimal_t,
250    pub litSum: u32,
251    pub litLengthSum: u32,
252    pub matchLengthSum: u32,
253    pub offCodeSum: u32,
254    pub litSumBasePrice: u32,
255    pub litLengthSumBasePrice: u32,
256    pub matchLengthSumBasePrice: u32,
257    pub offCodeSumBasePrice: u32,
258    pub priceType: ZSTD_OptPrice_e,
259    pub symbolCosts: *const ZSTD_entropyCTables_t,
260    pub literalCompressionMode: ParamSwitch,
261}
262#[derive(Copy, Clone)]
263#[repr(C)]
264pub struct ZSTD_optimal_t {
265    pub price: core::ffi::c_int,
266    pub off: u32,
267    pub mlen: u32,
268    pub litlen: u32,
269    pub rep: [u32; 3],
270}
271#[derive(Copy, Clone)]
272#[repr(C)]
273pub struct ZSTD_match_t {
274    pub off: u32,
275    pub len: u32,
276}
277#[derive(Copy, Clone)]
278#[repr(C)]
279pub struct ZSTD_window_t {
280    pub nextSrc: *const u8,
281    pub base: *const u8,
282    pub dictBase: *const u8,
283    pub dictLimit: u32,
284    pub lowLimit: u32,
285    pub nbOverflowCorrections: u32,
286}
287#[derive(Copy, Clone)]
288#[repr(C)]
289pub struct ZSTD_cwksp {
290    pub workspace: *mut core::ffi::c_void,
291    pub workspaceEnd: *mut core::ffi::c_void,
292    pub objectEnd: *mut core::ffi::c_void,
293    pub tableEnd: *mut core::ffi::c_void,
294    pub tableValidEnd: *mut core::ffi::c_void,
295    pub allocStart: *mut core::ffi::c_void,
296    pub initOnceStart: *mut core::ffi::c_void,
297    pub allocFailed: u8,
298    pub workspaceOversizedDuration: core::ffi::c_int,
299    pub phase: ZSTD_cwksp_alloc_phase_e,
300    pub isStatic: ZSTD_cwksp_static_alloc_e,
301}
302pub type ZSTD_cwksp_static_alloc_e = core::ffi::c_uint;
303pub const ZSTD_cwksp_static_alloc: ZSTD_cwksp_static_alloc_e = 1;
304pub const ZSTD_cwksp_dynamic_alloc: ZSTD_cwksp_static_alloc_e = 0;
305pub type ZSTD_cwksp_alloc_phase_e = core::ffi::c_uint;
306pub const ZSTD_cwksp_alloc_buffers: ZSTD_cwksp_alloc_phase_e = 3;
307pub const ZSTD_cwksp_alloc_aligned: ZSTD_cwksp_alloc_phase_e = 2;
308pub const ZSTD_cwksp_alloc_aligned_init_once: ZSTD_cwksp_alloc_phase_e = 1;
309pub const ZSTD_cwksp_alloc_objects: ZSTD_cwksp_alloc_phase_e = 0;
310#[derive(Copy, Clone)]
311#[repr(C)]
312pub struct ZSTD_localDict {
313    pub dictBuffer: *mut core::ffi::c_void,
314    pub dict: *const core::ffi::c_void,
315    pub dictSize: size_t,
316    pub dictContentType: ZSTD_dictContentType_e,
317    pub cdict: *mut ZSTD_CDict,
318}
319pub type ZSTD_cStreamStage = core::ffi::c_uint;
320pub const zcss_flush: ZSTD_cStreamStage = 2;
321pub const zcss_load: ZSTD_cStreamStage = 1;
322pub const zcss_init: ZSTD_cStreamStage = 0;
323pub type ZSTD_buffered_policy_e = core::ffi::c_uint;
324pub const ZSTDb_buffered: ZSTD_buffered_policy_e = 1;
325pub const ZSTDb_not_buffered: ZSTD_buffered_policy_e = 0;
326#[repr(C)]
327pub struct ZSTD_blockState_t {
328    pub prevCBlock: *mut ZSTD_compressedBlockState_t,
329    pub nextCBlock: *mut ZSTD_compressedBlockState_t,
330    pub matchState: ZSTD_MatchState_t,
331}
332#[repr(C)]
333pub struct SeqCollector {
334    pub collectSequences: core::ffi::c_int,
335    pub seqStart: *mut ZSTD_Sequence,
336    pub seqIndex: size_t,
337    pub maxSequences: size_t,
338}
339pub type ZSTD_CCtx_params = ZSTD_CCtx_params_s;
340#[derive(Copy, Clone)]
341#[repr(C)]
342pub struct ZSTD_CCtx_params_s {
343    pub format: Format,
344    pub cParams: ZSTD_compressionParameters,
345    pub fParams: ZSTD_frameParameters,
346    pub compressionLevel: core::ffi::c_int,
347    pub forceWindow: core::ffi::c_int,
348    pub targetCBlockSize: size_t,
349    pub srcSizeHint: core::ffi::c_int,
350    pub attachDictPref: ZSTD_dictAttachPref_e,
351    pub literalCompressionMode: ParamSwitch,
352    pub nbWorkers: core::ffi::c_int,
353    pub jobSize: size_t,
354    pub overlapLog: core::ffi::c_int,
355    pub rsyncable: core::ffi::c_int,
356    pub ldmParams: ldmParams_t,
357    pub enableDedicatedDictSearch: core::ffi::c_int,
358    pub inBufferMode: ZSTD_bufferMode_e,
359    pub outBufferMode: ZSTD_bufferMode_e,
360    pub blockDelimiters: ZSTD_SequenceFormat_e,
361    pub validateSequences: core::ffi::c_int,
362    pub postBlockSplitter: ZSTD_ParamSwitch_e,
363    pub preBlockSplitter_level: core::ffi::c_int,
364    pub maxBlockSize: size_t,
365    pub useRowMatchFinder: ZSTD_ParamSwitch_e,
366    pub deterministicRefPrefix: core::ffi::c_int,
367    pub customMem: ZSTD_customMem,
368    pub prefetchCDictTables: ZSTD_ParamSwitch_e,
369    pub enableMatchFinderFallback: core::ffi::c_int,
370    pub extSeqProdState: *mut core::ffi::c_void,
371    pub extSeqProdFunc: ZSTD_sequenceProducer_F,
372    pub searchForExternalRepcodes: ZSTD_ParamSwitch_e,
373}
374pub type ZSTD_sequenceProducer_F = Option<
375    unsafe extern "C" fn(
376        *mut core::ffi::c_void,
377        *mut ZSTD_Sequence,
378        size_t,
379        *const core::ffi::c_void,
380        size_t,
381        *const core::ffi::c_void,
382        size_t,
383        core::ffi::c_int,
384        size_t,
385    ) -> size_t,
386>;
387pub type ZSTD_SequenceFormat_e = core::ffi::c_uint;
388pub const ZSTD_sf_explicitBlockDelimiters: ZSTD_SequenceFormat_e = 1;
389pub const ZSTD_sf_noBlockDelimiters: ZSTD_SequenceFormat_e = 0;
390pub type ZSTD_compressionStage_e = core::ffi::c_uint;
391pub const ZSTDcs_ending: ZSTD_compressionStage_e = 3;
392pub const ZSTDcs_ongoing: ZSTD_compressionStage_e = 2;
393pub const ZSTDcs_init: ZSTD_compressionStage_e = 1;
394pub const ZSTDcs_created: ZSTD_compressionStage_e = 0;
395pub type unalignArch = size_t;
396#[derive(Copy, Clone)]
397#[repr(C)]
398pub struct ZSTD_symbolEncodingTypeStats_t {
399    pub LLtype: u32,
400    pub Offtype: u32,
401    pub MLtype: u32,
402    pub size: size_t,
403    pub lastCountSize: size_t,
404    pub longOffsets: core::ffi::c_int,
405}
406pub type S16 = i16;
407pub type ZSTD_DefaultPolicy_e = core::ffi::c_uint;
408pub const ZSTD_defaultAllowed: ZSTD_DefaultPolicy_e = 1;
409pub const ZSTD_defaultDisallowed: ZSTD_DefaultPolicy_e = 0;
410pub type Repcodes_t = repcodes_s;
411#[derive(Copy, Clone)]
412#[repr(C)]
413pub struct repcodes_s {
414    pub rep: [u32; 3],
415}
416pub const ZSTDbss_noCompress: C2RustUnnamed_2 = 1;
417pub const ZSTDbss_compress: C2RustUnnamed_2 = 0;
418pub type ZSTD_BlockCompressor_f = Option<
419    unsafe fn(
420        &mut ZSTD_MatchState_t,
421        &mut SeqStore_t,
422        *mut u32,
423        *const core::ffi::c_void,
424        size_t,
425    ) -> size_t,
426>;
427pub type ZSTD_dictMode_e = core::ffi::c_uint;
428pub const ZSTD_dedicatedDictSearch: ZSTD_dictMode_e = 3;
429pub const ZSTD_dictMatchState: ZSTD_dictMode_e = 2;
430pub const ZSTD_extDict: ZSTD_dictMode_e = 1;
431pub const ZSTD_noDict: ZSTD_dictMode_e = 0;
432#[derive(Copy, Clone)]
433#[repr(C)]
434pub struct ZSTD_SequencePosition {
435    pub idx: u32,
436    pub posInSequence: u32,
437    pub posInSrc: size_t,
438}
439pub type S64 = i64;
440#[repr(C)]
441pub struct seqStoreSplits {
442    pub splitLocations: *mut u32,
443    pub idx: size_t,
444}
445
446pub type ZSTD_dictTableLoadMethod_e = core::ffi::c_uint;
447pub const ZSTD_dtlm_full: ZSTD_dictTableLoadMethod_e = 1;
448pub const ZSTD_dtlm_fast: ZSTD_dictTableLoadMethod_e = 0;
449pub type ZSTD_tableFillPurpose_e = core::ffi::c_uint;
450pub const ZSTD_tfp_forCDict: ZSTD_tableFillPurpose_e = 1;
451pub const ZSTD_tfp_forCCtx: ZSTD_tableFillPurpose_e = 0;
452pub type ZSTD_compResetPolicy_e = core::ffi::c_uint;
453pub const ZSTDcrp_leaveDirty: ZSTD_compResetPolicy_e = 1;
454pub const ZSTDcrp_makeClean: ZSTD_compResetPolicy_e = 0;
455pub type ZSTD_resetTarget_e = core::ffi::c_uint;
456pub const ZSTD_resetTarget_CCtx: ZSTD_resetTarget_e = 1;
457pub const ZSTD_resetTarget_CDict: ZSTD_resetTarget_e = 0;
458pub type ZSTD_indexResetPolicy_e = core::ffi::c_uint;
459pub const ZSTDirp_reset: ZSTD_indexResetPolicy_e = 1;
460pub const ZSTDirp_continue: ZSTD_indexResetPolicy_e = 0;
461pub type ZSTD_CParamMode_e = core::ffi::c_uint;
462pub const ZSTD_cpm_unknown: ZSTD_CParamMode_e = 3;
463pub const ZSTD_cpm_createCDict: ZSTD_CParamMode_e = 2;
464pub const ZSTD_cpm_attachDict: ZSTD_CParamMode_e = 1;
465pub const ZSTD_cpm_noAttachDict: ZSTD_CParamMode_e = 0;
466#[derive(Copy, Clone)]
467#[repr(C)]
468pub struct ZSTD_cpuid_t {
469    pub f1c: u32,
470    pub f1d: u32,
471    pub f7b: u32,
472    pub f7c: u32,
473}
474#[derive(Copy, Clone)]
475#[repr(C)]
476pub struct ZSTD_bounds {
477    pub error: size_t,
478    pub lowerBound: core::ffi::c_int,
479    pub upperBound: core::ffi::c_int,
480}
481pub type ZSTD_EndDirective = core::ffi::c_uint;
482pub const ZSTD_e_end: ZSTD_EndDirective = 2;
483pub const ZSTD_e_flush: ZSTD_EndDirective = 1;
484pub const ZSTD_e_continue: ZSTD_EndDirective = 0;
485pub type ZSTD_CStream = ZSTD_CCtx;
486pub type ZSTD_SequenceCopier_f = Option<
487    unsafe fn(
488        *mut ZSTD_CCtx,
489        *mut ZSTD_SequencePosition,
490        *const ZSTD_Sequence,
491        size_t,
492        *const core::ffi::c_void,
493        size_t,
494        ZSTD_ParamSwitch_e,
495    ) -> size_t,
496>;
497#[derive(Copy, Clone)]
498#[repr(C)]
499pub struct BlockSummary {
500    pub nbSequences: size_t,
501    pub blockSize: size_t,
502    pub litSize: size_t,
503}
504pub type C2RustUnnamed_2 = core::ffi::c_uint;
505pub const ZSTD_WINDOWLOG_MIN: core::ffi::c_int = 10;
506pub const ZSTD_HASHLOG_MIN: core::ffi::c_int = 6;
507pub const ZSTD_CHAINLOG_MAX_32: core::ffi::c_int = 29;
508pub const ZSTD_CHAINLOG_MAX_64: core::ffi::c_int = 30;
509pub const ZSTD_CHAINLOG_MIN: core::ffi::c_int = ZSTD_HASHLOG_MIN;
510pub const ZSTD_SEARCHLOG_MIN: core::ffi::c_int = 1;
511pub const ZSTD_MINMATCH_MAX: core::ffi::c_int = 7;
512pub const ZSTD_MINMATCH_MIN: core::ffi::c_int = 3;
513pub const ZSTD_TARGETLENGTH_MAX: core::ffi::c_int = ZSTD_BLOCKSIZE_MAX;
514pub const ZSTD_TARGETLENGTH_MIN: core::ffi::c_int = 0;
515pub const ZSTD_STRATEGY_MIN: core::ffi::c_int = ZSTD_fast as core::ffi::c_int;
516pub const ZSTD_STRATEGY_MAX: core::ffi::c_int = ZSTD_btultra2 as core::ffi::c_int;
517pub const ZSTD_OVERLAPLOG_MIN: core::ffi::c_int = 0;
518pub const ZSTD_OVERLAPLOG_MAX: core::ffi::c_int = 9;
519pub const ZSTD_LDM_HASHLOG_MIN: core::ffi::c_int = ZSTD_HASHLOG_MIN;
520pub const ZSTD_LDM_MINMATCH_MIN: core::ffi::c_int = 4;
521pub const ZSTD_LDM_MINMATCH_MAX: core::ffi::c_int = 4096;
522pub const ZSTD_LDM_BUCKETSIZELOG_MIN: core::ffi::c_int = 1;
523pub const ZSTD_LDM_BUCKETSIZELOG_MAX: core::ffi::c_int = 8;
524pub const ZSTD_LDM_HASHRATELOG_MIN: core::ffi::c_int = 0;
525pub const ZSTD_TARGETCBLOCKSIZE_MIN: core::ffi::c_int = 1340;
526pub const ZSTD_TARGETCBLOCKSIZE_MAX: core::ffi::c_int = ZSTD_BLOCKSIZE_MAX;
527pub const ZSTD_SRCSIZEHINT_MIN: core::ffi::c_int = 0;
528pub const ZSTD_SRCSIZEHINT_MAX: core::ffi::c_int = INT_MAX;
529pub const ZSTD_c_rsyncable: core::ffi::c_int = 500;
530pub const ZSTD_c_format: core::ffi::c_int = 10;
531pub const ZSTD_c_forceMaxWindow: core::ffi::c_int = 1000;
532pub const ZSTD_c_forceAttachDict: core::ffi::c_int = 1001;
533pub const ZSTD_c_literalCompressionMode: core::ffi::c_int = 1002;
534pub const ZSTD_c_srcSizeHint: core::ffi::c_int = 1004;
535pub const ZSTD_c_enableDedicatedDictSearch: core::ffi::c_int = 1005;
536pub const ZSTD_c_stableInBuffer: core::ffi::c_int = 1006;
537pub const ZSTD_c_stableOutBuffer: core::ffi::c_int = 1007;
538pub const ZSTD_c_blockDelimiters: core::ffi::c_int = 1008;
539pub const ZSTD_c_validateSequences: core::ffi::c_int = 1009;
540pub const ZSTD_BLOCKSPLITTER_LEVEL_MAX: core::ffi::c_int = 6;
541pub const ZSTD_c_blockSplitterLevel: core::ffi::c_int = 1017;
542pub const ZSTD_c_splitAfterSequences: core::ffi::c_int = 1010;
543pub const ZSTD_c_useRowMatchFinder: core::ffi::c_int = 1011;
544pub const ZSTD_c_deterministicRefPrefix: core::ffi::c_int = 1012;
545pub const ZSTD_c_prefetchCDictTables: core::ffi::c_int = 1013;
546pub const ZSTD_c_enableSeqProducerFallback: core::ffi::c_int = 1014;
547pub const ZSTD_c_maxBlockSize: core::ffi::c_int = 1015;
548pub const ZSTD_c_repcodeResolution: core::ffi::c_int = 1016;
549pub const HASH_READ_SIZE: core::ffi::c_int = 8;
550pub const ZSTD_DUBT_UNSORTED_MARK: core::ffi::c_int = 1;
551static mut kNullRawSeqStore: RawSeqStore_t = RawSeqStore_t {
552    seq: core::ptr::null_mut(),
553    pos: 0,
554    posInSequence: 0,
555    size: 0,
556    capacity: 0,
557};
558pub const ZSTD_OPT_SIZE: core::ffi::c_int = ZSTD_OPT_NUM + 3;
559pub const ZSTD_MAX_NB_BLOCK_SPLITS: core::ffi::c_int = 196;
560#[inline]
561unsafe fn ZSTD_LLcode(litLength: u32) -> u32 {
562    static LL_Code: [u8; 64] = [
563        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20,
564        20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
565        24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
566    ];
567    static LL_deltaCode: u32 = 19;
568    if litLength > 63 {
569        (ZSTD_highbit32(litLength)).wrapping_add(LL_deltaCode)
570    } else {
571        *LL_Code.as_ptr().offset(litLength as isize) as core::ffi::c_uint
572    }
573}
574#[inline]
575unsafe fn ZSTD_MLcode(mlBase: u32) -> u32 {
576    static ML_Code: [u8; 128] = [
577        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
578        25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
579        38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40,
580        40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
581        41, 41, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
582        42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
583    ];
584    static ML_deltaCode: u32 = 36;
585    if mlBase > 127 {
586        (ZSTD_highbit32(mlBase)).wrapping_add(ML_deltaCode)
587    } else {
588        *ML_Code.as_ptr().offset(mlBase as isize) as core::ffi::c_uint
589    }
590}
591#[inline]
592unsafe fn ZSTD_cParam_withinBounds(
593    cParam: ZSTD_cParameter,
594    value: core::ffi::c_int,
595) -> core::ffi::c_int {
596    let bounds = ZSTD_cParam_getBounds(cParam);
597    if ERR_isError(bounds.error) {
598        return 0;
599    }
600    if value < bounds.lowerBound {
601        return 0;
602    }
603    if value > bounds.upperBound {
604        return 0;
605    }
606    1
607}
608#[inline]
609unsafe fn ZSTD_noCompressBlock(
610    dst: *mut core::ffi::c_void,
611    dstCapacity: size_t,
612    src: *const core::ffi::c_void,
613    srcSize: size_t,
614    lastBlock: u32,
615) -> size_t {
616    let cBlockHeader24 = lastBlock
617        .wrapping_add((bt_raw as core::ffi::c_int as u32) << 1)
618        .wrapping_add((srcSize << 3) as u32);
619    if srcSize.wrapping_add(ZSTD_blockHeaderSize) > dstCapacity {
620        return Error::dstSize_tooSmall.to_error_code();
621    }
622    MEM_writeLE24(dst, cBlockHeader24);
623    libc::memcpy(
624        (dst as *mut u8).add(ZSTD_blockHeaderSize) as *mut core::ffi::c_void,
625        src,
626        srcSize as libc::size_t,
627    );
628    ZSTD_blockHeaderSize.wrapping_add(srcSize)
629}
630#[inline]
631unsafe fn ZSTD_rleCompressBlock(
632    dst: *mut core::ffi::c_void,
633    dstCapacity: size_t,
634    src: u8,
635    srcSize: size_t,
636    lastBlock: u32,
637) -> size_t {
638    let op = dst as *mut u8;
639    let cBlockHeader = lastBlock
640        .wrapping_add((bt_rle as core::ffi::c_int as u32) << 1)
641        .wrapping_add((srcSize << 3) as u32);
642    if dstCapacity < 4 {
643        return Error::dstSize_tooSmall.to_error_code();
644    }
645    MEM_writeLE24(op as *mut core::ffi::c_void, cBlockHeader);
646    *op.add(3) = src;
647    4
648}
649#[inline]
650unsafe fn ZSTD_minGain(srcSize: size_t, strat: ZSTD_strategy) -> size_t {
651    let minlog =
652        if strat as core::ffi::c_uint >= ZSTD_btultra as core::ffi::c_int as core::ffi::c_uint {
653            strat.wrapping_sub(1)
654        } else {
655            6
656        };
657    (srcSize >> minlog).wrapping_add(2)
658}
659#[inline]
660unsafe fn ZSTD_literalsCompressionIsDisabled(
661    cctxParams: *const ZSTD_CCtx_params,
662) -> core::ffi::c_int {
663    match (*cctxParams).literalCompressionMode {
664        ParamSwitch::Enable => 0,
665        ParamSwitch::Disable => 1,
666        ParamSwitch::Auto => {
667            ((*cctxParams).cParams.strategy as core::ffi::c_uint
668                == ZSTD_fast as core::ffi::c_int as core::ffi::c_uint
669                && (*cctxParams).cParams.targetLength > 0) as core::ffi::c_int
670        }
671    }
672}
673pub const REPCODE1_TO_OFFBASE: core::ffi::c_int = 1;
674pub const REPCODE3_TO_OFFBASE: core::ffi::c_int = 3;
675
676#[inline]
677unsafe fn ZSTD_window_clear(window: *mut ZSTD_window_t) {
678    let endT = ((*window).nextSrc).wrapping_offset_from((*window).base) as size_t;
679    let end = endT as u32;
680    (*window).lowLimit = end;
681    (*window).dictLimit = end;
682}
683#[inline]
684pub(crate) unsafe fn ZSTD_window_hasExtDict(window: ZSTD_window_t) -> u32 {
685    (window.lowLimit < window.dictLimit) as core::ffi::c_int as u32
686}
687#[inline]
688unsafe fn ZSTD_matchState_dictMode(ms: *const ZSTD_MatchState_t) -> ZSTD_dictMode_e {
689    (if ZSTD_window_hasExtDict((*ms).window) != 0 {
690        ZSTD_extDict as core::ffi::c_int
691    } else if !((*ms).dictMatchState).is_null() {
692        if (*(*ms).dictMatchState).dedicatedDictSearch != 0 {
693            ZSTD_dedicatedDictSearch as core::ffi::c_int
694        } else {
695            ZSTD_dictMatchState as core::ffi::c_int
696        }
697    } else {
698        ZSTD_noDict as core::ffi::c_int
699    }) as ZSTD_dictMode_e
700}
701
702#[inline]
703unsafe fn ZSTD_window_correctOverflow(
704    window: *mut ZSTD_window_t,
705    cycleLog: u32,
706    maxDist: u32,
707    src: *const core::ffi::c_void,
708) -> u32 {
709    let cycleSize = (1 as core::ffi::c_uint) << cycleLog;
710    let cycleMask = cycleSize.wrapping_sub(1);
711    let curr = (src as *const u8).offset_from((*window).base) as core::ffi::c_long as u32;
712    let currentCycle = curr & cycleMask;
713    let currentCycleCorrection = if currentCycle < ZSTD_WINDOW_START_INDEX as u32 {
714        if cycleSize > 2 {
715            cycleSize
716        } else {
717            2
718        }
719    } else {
720        0
721    };
722    let newCurrent = currentCycle
723        .wrapping_add(currentCycleCorrection)
724        .wrapping_add(if maxDist > cycleSize {
725            maxDist
726        } else {
727            cycleSize
728        });
729    let correction = curr.wrapping_sub(newCurrent);
730    if ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY == 0 {
731        // Loose bound, should be around 1<<29 (see above)
732        assert!(correction > 1 << 28);
733    }
734    (*window).base = ((*window).base).offset(correction as isize);
735    (*window).dictBase = ((*window).dictBase).offset(correction as isize);
736    if (*window).lowLimit < correction.wrapping_add(ZSTD_WINDOW_START_INDEX as u32) {
737        (*window).lowLimit = ZSTD_WINDOW_START_INDEX as u32;
738    } else {
739        (*window).lowLimit = ((*window).lowLimit).wrapping_sub(correction);
740    }
741    if (*window).dictLimit < correction.wrapping_add(ZSTD_WINDOW_START_INDEX as u32) {
742        (*window).dictLimit = ZSTD_WINDOW_START_INDEX as u32;
743    } else {
744        (*window).dictLimit = ((*window).dictLimit).wrapping_sub(correction);
745    }
746    (*window).nbOverflowCorrections = ((*window).nbOverflowCorrections).wrapping_add(1);
747    correction
748}
749#[inline]
750unsafe fn ZSTD_window_enforceMaxDist(
751    window: *mut ZSTD_window_t,
752    blockEnd: *const core::ffi::c_void,
753    maxDist: u32,
754    loadedDictEndPtr: *mut u32,
755    dictMatchStatePtr: *mut *const ZSTD_MatchState_t,
756) {
757    let blockEndIdx =
758        (blockEnd as *const u8).wrapping_offset_from((*window).base) as core::ffi::c_long as u32;
759    let loadedDictEnd = if !loadedDictEndPtr.is_null() {
760        *loadedDictEndPtr
761    } else {
762        0
763    };
764    if blockEndIdx > maxDist.wrapping_add(loadedDictEnd) {
765        let newLowLimit = blockEndIdx.wrapping_sub(maxDist);
766        if (*window).lowLimit < newLowLimit {
767            (*window).lowLimit = newLowLimit;
768        }
769        if (*window).dictLimit < (*window).lowLimit {
770            (*window).dictLimit = (*window).lowLimit;
771        }
772        if !loadedDictEndPtr.is_null() {
773            *loadedDictEndPtr = 0;
774        }
775        if !dictMatchStatePtr.is_null() {
776            *dictMatchStatePtr = core::ptr::null();
777        }
778    }
779}
780#[inline]
781unsafe fn ZSTD_checkDictValidity(
782    window: *const ZSTD_window_t,
783    blockEnd: *const core::ffi::c_void,
784    maxDist: u32,
785    loadedDictEndPtr: *mut u32,
786    dictMatchStatePtr: *mut *const ZSTD_MatchState_t,
787) {
788    let blockEndIdx =
789        (blockEnd as *const u8).wrapping_offset_from((*window).base) as core::ffi::c_long as u32;
790    let loadedDictEnd = *loadedDictEndPtr;
791    if blockEndIdx > loadedDictEnd.wrapping_add(maxDist) || loadedDictEnd != (*window).dictLimit {
792        *loadedDictEndPtr = 0;
793        *dictMatchStatePtr = core::ptr::null();
794    } else {
795        // FIXME: add log
796        // *loadedDictEndPtr != 0;
797    }
798}
799#[inline]
800unsafe fn ZSTD_window_init(window: *mut ZSTD_window_t) {
801    ptr::write_bytes(
802        window as *mut u8,
803        0,
804        ::core::mem::size_of::<ZSTD_window_t>(),
805    );
806    (*window).base = b" \0" as *const u8 as *const core::ffi::c_char as *const u8;
807    (*window).dictBase = b" \0" as *const u8 as *const core::ffi::c_char as *const u8;
808    (*window).dictLimit = ZSTD_WINDOW_START_INDEX as u32;
809    (*window).lowLimit = ZSTD_WINDOW_START_INDEX as u32;
810    (*window).nextSrc = ((*window).base).offset(ZSTD_WINDOW_START_INDEX as isize);
811    (*window).nbOverflowCorrections = 0;
812}
813#[inline]
814unsafe fn ZSTD_window_update(
815    window: *mut ZSTD_window_t,
816    src: *const core::ffi::c_void,
817    srcSize: size_t,
818    forceNonContiguous: core::ffi::c_int,
819) -> u32 {
820    let ip = src as *const u8;
821    let mut contiguous = 1;
822    if srcSize == 0 {
823        return contiguous;
824    }
825    if src != (*window).nextSrc as *const core::ffi::c_void || forceNonContiguous != 0 {
826        let distanceFromBase = ((*window).nextSrc).wrapping_offset_from((*window).base) as size_t;
827        (*window).lowLimit = (*window).dictLimit;
828        (*window).dictLimit = distanceFromBase as u32;
829        (*window).dictBase = (*window).base;
830        (*window).base = ip.wrapping_sub(distanceFromBase);
831        if ((*window).dictLimit).wrapping_sub((*window).lowLimit) < HASH_READ_SIZE as u32 {
832            (*window).lowLimit = (*window).dictLimit;
833        }
834        contiguous = 0;
835    }
836    (*window).nextSrc = ip.add(srcSize);
837    if (ip.add(srcSize) > ((*window).dictBase).wrapping_offset((*window).lowLimit as isize))
838        && (ip < ((*window).dictBase).wrapping_offset((*window).dictLimit as isize))
839    {
840        let highInputIdx = ip.add(srcSize).offset_from((*window).dictBase) as size_t;
841        let lowLimitMax = if highInputIdx > (*window).dictLimit as size_t {
842            (*window).dictLimit
843        } else {
844            highInputIdx as u32
845        };
846        (*window).lowLimit = lowLimitMax;
847    }
848    contiguous
849}
850pub const ZSTD_SHORT_CACHE_TAG_BITS: core::ffi::c_int = 8;
851#[inline]
852unsafe fn ZSTD_hasExtSeqProd(params: *const ZSTD_CCtx_params) -> core::ffi::c_int {
853    ((*params).extSeqProdFunc).is_some() as core::ffi::c_int
854}
855
856use libc::{ptrdiff_t, size_t};
857
858use crate::lib::common::allocations::{ZSTD_customCalloc, ZSTD_customFree, ZSTD_customMalloc};
859use crate::lib::common::bits::ZSTD_highbit32;
860use crate::lib::common::entropy_common::FSE_readNCount;
861use crate::lib::common::error_private::{ERR_isError, Error};
862use crate::lib::common::fse::{
863    FSE_CTable, FSE_repeat, FSE_repeat_check, FSE_repeat_none, FSE_repeat_valid,
864};
865use crate::lib::common::huf::{
866    HUF_CElt, HUF_flags_optimalDepth, HUF_repeat, HUF_repeat_check, HUF_repeat_none,
867    HUF_repeat_valid, HUF_OPTIMAL_DEPTH_THRESHOLD, HUF_SYMBOLVALUE_MAX, HUF_WORKSPACE_SIZE,
868};
869use crate::lib::common::mem::{
870    MEM_32bits, MEM_64bits, MEM_read64, MEM_readLE32, MEM_readST, MEM_writeLE16, MEM_writeLE24,
871    MEM_writeLE32, MEM_writeLE64,
872};
873use crate::lib::common::pool::ZSTD_threadPool;
874use crate::lib::common::xxhash::{
875    XXH64_state_t, ZSTD_XXH64_digest, ZSTD_XXH64_reset, ZSTD_XXH64_update_slice,
876};
877use crate::lib::common::zstd_internal::{
878    bt_compressed, bt_raw, bt_rle, repStartValue, DefaultMaxOff, LLFSELog, LL_bits, LL_defaultNorm,
879    LL_defaultNormLog, LitHufLog, Litbits, MLFSELog, ML_bits, ML_defaultNorm, ML_defaultNormLog,
880    MaxLL, MaxML, MaxOff, OF_defaultNorm, OF_defaultNormLog, OffFSELog, ZSTD_cpuSupportsBmi2,
881    ZSTD_limitCopy, MINMATCH, WILDCOPY_OVERLENGTH, ZSTD_OPT_NUM, ZSTD_REP_NUM,
882    ZSTD_WORKSPACETOOLARGE_FACTOR, ZSTD_WORKSPACETOOLARGE_MAXDURATION,
883};
884use crate::lib::common::zstd_trace::{
885    ZSTD_Trace, ZSTD_TraceCtx, ZSTD_trace_compress_begin, ZSTD_trace_compress_end,
886};
887use crate::lib::compress::fse_compress::FSE_buildCTable_wksp;
888use crate::lib::compress::hist::{HIST_countFast_wksp, HIST_count_wksp};
889use crate::lib::compress::huf_compress::{
890    HUF_buildCTable_wksp, HUF_estimateCompressedSize, HUF_optimalTableLog, HUF_readCTable,
891    HUF_validateCTable, HUF_writeCTable_wksp,
892};
893use crate::lib::compress::zstd_compress_internal::{
894    zop_dynamic, ZSTD_OptPrice_e, ZSTD_count, ZSTD_getSequenceLength, ZSTD_llt_literalLength,
895    ZSTD_llt_matchLength, ZSTD_llt_none, ZSTD_longLengthType_e, ZSTD_storeSeq, ZSTD_storeSeqOnly,
896    ZSTD_updateRep, ZSTD_window_needOverflowCorrection, ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY,
897    ZSTD_WINDOW_START_INDEX,
898};
899use crate::lib::compress::zstd_compress_literals::ZSTD_compressLiterals;
900use crate::lib::compress::zstd_compress_sequences::{
901    ZSTD_buildCTable, ZSTD_crossEntropyCost, ZSTD_encodeSequences, ZSTD_fseBitCost,
902    ZSTD_selectEncodingType,
903};
904use crate::lib::compress::zstd_compress_superblock::ZSTD_compressSuperBlock;
905use crate::lib::compress::zstd_double_fast::{
906    ZSTD_compressBlock_doubleFast, ZSTD_compressBlock_doubleFast_dictMatchState,
907    ZSTD_compressBlock_doubleFast_extDict, ZSTD_fillDoubleHashTable,
908};
909use crate::lib::compress::zstd_fast::{
910    ZSTD_compressBlock_fast, ZSTD_compressBlock_fast_dictMatchState,
911    ZSTD_compressBlock_fast_extDict, ZSTD_fillHashTable,
912};
913use crate::lib::compress::zstd_lazy::{
914    ZSTD_compressBlock_btlazy2, ZSTD_compressBlock_btlazy2_dictMatchState,
915    ZSTD_compressBlock_btlazy2_extDict, ZSTD_compressBlock_greedy,
916    ZSTD_compressBlock_greedy_dedicatedDictSearch,
917    ZSTD_compressBlock_greedy_dedicatedDictSearch_row, ZSTD_compressBlock_greedy_dictMatchState,
918    ZSTD_compressBlock_greedy_dictMatchState_row, ZSTD_compressBlock_greedy_extDict,
919    ZSTD_compressBlock_greedy_extDict_row, ZSTD_compressBlock_greedy_row, ZSTD_compressBlock_lazy,
920    ZSTD_compressBlock_lazy2, ZSTD_compressBlock_lazy2_dedicatedDictSearch,
921    ZSTD_compressBlock_lazy2_dedicatedDictSearch_row, ZSTD_compressBlock_lazy2_dictMatchState,
922    ZSTD_compressBlock_lazy2_dictMatchState_row, ZSTD_compressBlock_lazy2_extDict,
923    ZSTD_compressBlock_lazy2_extDict_row, ZSTD_compressBlock_lazy2_row,
924    ZSTD_compressBlock_lazy_dedicatedDictSearch, ZSTD_compressBlock_lazy_dedicatedDictSearch_row,
925    ZSTD_compressBlock_lazy_dictMatchState, ZSTD_compressBlock_lazy_dictMatchState_row,
926    ZSTD_compressBlock_lazy_extDict, ZSTD_compressBlock_lazy_extDict_row,
927    ZSTD_compressBlock_lazy_row, ZSTD_dedicatedDictSearch_lazy_loadDictionary,
928    ZSTD_insertAndFindFirstIndex, ZSTD_row_update,
929};
930use crate::lib::compress::zstd_ldm::{
931    ldmEntry_t, ldmMatchCandidate_t, ldmParams_t, ldmState_t, ZSTD_ldm_adjustParameters,
932    ZSTD_ldm_blockCompress, ZSTD_ldm_fillHashTable, ZSTD_ldm_generateSequences,
933    ZSTD_ldm_getMaxNbSeq, ZSTD_ldm_getTableSize, ZSTD_ldm_skipRawSeqStoreBytes,
934    ZSTD_ldm_skipSequences,
935};
936use crate::lib::compress::zstd_opt::{
937    ZSTD_compressBlock_btopt, ZSTD_compressBlock_btopt_dictMatchState,
938    ZSTD_compressBlock_btopt_extDict, ZSTD_compressBlock_btultra, ZSTD_compressBlock_btultra2,
939    ZSTD_compressBlock_btultra_dictMatchState, ZSTD_compressBlock_btultra_extDict, ZSTD_updateTree,
940};
941use crate::lib::compress::zstd_preSplit::ZSTD_splitBlock;
942use crate::lib::compress::zstdmt_compress::{
943    ZSTDMT_CCtx, ZSTDMT_compressStream_generic, ZSTDMT_createCCtx_advanced, ZSTDMT_freeCCtx,
944    ZSTDMT_getFrameProgression, ZSTDMT_initCStream_internal, ZSTDMT_nextInputSizeHint,
945    ZSTDMT_sizeof_CCtx, ZSTDMT_toFlushNow, ZSTDMT_updateCParams_whileCompressing,
946};
947use crate::lib::zstd::{
948    Format, ZSTD_ParamSwitch_e, ZSTD_ResetDirective, ZSTD_bm_buffered, ZSTD_bm_stable,
949    ZSTD_btlazy2, ZSTD_btopt, ZSTD_btultra, ZSTD_btultra2, ZSTD_bufferMode_e, ZSTD_cParameter,
950    ZSTD_compressionParameters, ZSTD_customMem, ZSTD_dct_auto, ZSTD_dct_fullDict,
951    ZSTD_dct_rawContent, ZSTD_dfast, ZSTD_dictAttachPref_e, ZSTD_dictContentType_e,
952    ZSTD_dictLoadMethod_e, ZSTD_dlm_byCopy, ZSTD_dlm_byRef,
953    ZSTD_error_stabilityCondition_notRespected, ZSTD_fast, ZSTD_frameParameters,
954    ZSTD_frameProgression, ZSTD_greedy, ZSTD_inBuffer, ZSTD_inBuffer_s, ZSTD_lazy, ZSTD_lazy2,
955    ZSTD_outBuffer, ZSTD_outBuffer_s, ZSTD_parameters, ZSTD_strategy, ZSTD_BLOCKSIZE_MAX,
956    ZSTD_BLOCKSIZE_MAX_MIN, ZSTD_CLEVEL_DEFAULT, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_MAGICNUMBER,
957    ZSTD_MAGIC_DICTIONARY, ZSTD_MAGIC_SKIPPABLE_START, ZSTD_SKIPPABLEHEADERSIZE,
958    ZSTD_VERSION_NUMBER, ZSTD_WINDOWLOG_ABSOLUTEMIN, ZSTD_WINDOWLOG_MAX, ZSTD_WINDOWLOG_MAX_32,
959    ZSTD_WINDOWLOG_MAX_64,
960};
961pub const ZSTD_BLOCKHEADERSIZE: core::ffi::c_int = 3;
962static ZSTD_blockHeaderSize: size_t = ZSTD_BLOCKHEADERSIZE as size_t;
963pub const MIN_CBLOCK_SIZE: core::ffi::c_int = 1 + 1;
964pub const LONGNBSEQ: core::ffi::c_int = 0x7f00 as core::ffi::c_int;
965pub const ZSTD_CWKSP_ALIGNMENT_BYTES: core::ffi::c_int = 64;
966#[inline]
967unsafe fn ZSTD_cwksp_assert_internal_consistency(ws: *mut ZSTD_cwksp) {
968    assert!((*ws).workspace <= (*ws).objectEnd);
969    assert!((*ws).objectEnd <= (*ws).tableEnd);
970    assert!((*ws).objectEnd <= (*ws).tableValidEnd);
971    assert!((*ws).tableEnd <= (*ws).allocStart);
972    assert!((*ws).tableValidEnd <= (*ws).allocStart);
973    assert!((*ws).allocStart <= (*ws).workspaceEnd);
974    assert!((*ws).initOnceStart <= ZSTD_cwksp_initialAllocStart(ws));
975    assert!((*ws).workspace <= (*ws).initOnceStart);
976}
977#[inline]
978unsafe fn ZSTD_cwksp_align(size: size_t, align: size_t) -> size_t {
979    let mask = align.wrapping_sub(1);
980    size.wrapping_add(mask) & !mask
981}
982#[inline]
983unsafe fn ZSTD_cwksp_alloc_size(size: size_t) -> size_t {
984    if size == 0 {
985        return 0;
986    }
987    size
988}
989#[inline]
990unsafe fn ZSTD_cwksp_aligned_alloc_size(size: size_t, alignment: size_t) -> size_t {
991    ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, alignment))
992}
993#[inline]
994unsafe fn ZSTD_cwksp_aligned64_alloc_size(size: size_t) -> size_t {
995    ZSTD_cwksp_aligned_alloc_size(size, ZSTD_CWKSP_ALIGNMENT_BYTES as size_t)
996}
997#[inline]
998unsafe fn ZSTD_cwksp_slack_space_required() -> size_t {
999    (ZSTD_CWKSP_ALIGNMENT_BYTES * 2) as size_t
1000}
1001#[inline]
1002unsafe fn ZSTD_cwksp_bytes_to_align_ptr(ptr: *mut core::ffi::c_void, alignBytes: size_t) -> size_t {
1003    let alignBytesMask = alignBytes.wrapping_sub(1);
1004
1005    alignBytes.wrapping_sub(ptr as size_t & alignBytesMask) & alignBytesMask
1006}
1007#[inline]
1008unsafe fn ZSTD_cwksp_initialAllocStart(ws: *mut ZSTD_cwksp) -> *mut core::ffi::c_void {
1009    let mut endPtr = (*ws).workspaceEnd as *mut core::ffi::c_char;
1010    endPtr = endPtr.offset(-((endPtr as size_t % ZSTD_CWKSP_ALIGNMENT_BYTES as size_t) as isize));
1011    endPtr as *mut core::ffi::c_void
1012}
1013#[inline]
1014unsafe fn ZSTD_cwksp_reserve_internal_buffer_space(
1015    ws: *mut ZSTD_cwksp,
1016    bytes: size_t,
1017) -> *mut core::ffi::c_void {
1018    let alloc = ((*ws).allocStart as *mut u8).offset(-(bytes as isize)) as *mut core::ffi::c_void;
1019    let bottom = (*ws).tableEnd;
1020    ZSTD_cwksp_assert_internal_consistency(ws);
1021    if alloc < bottom {
1022        (*ws).allocFailed = 1;
1023        return core::ptr::null_mut();
1024    }
1025    if alloc < (*ws).tableValidEnd {
1026        (*ws).tableValidEnd = alloc;
1027    }
1028    (*ws).allocStart = alloc;
1029    alloc
1030}
1031#[inline]
1032unsafe fn ZSTD_cwksp_internal_advance_phase(
1033    ws: *mut ZSTD_cwksp,
1034    phase: ZSTD_cwksp_alloc_phase_e,
1035) -> size_t {
1036    if phase as core::ffi::c_uint > (*ws).phase as core::ffi::c_uint {
1037        if ((*ws).phase as core::ffi::c_uint)
1038            < ZSTD_cwksp_alloc_aligned_init_once as core::ffi::c_int as core::ffi::c_uint
1039            && phase as core::ffi::c_uint
1040                >= ZSTD_cwksp_alloc_aligned_init_once as core::ffi::c_int as core::ffi::c_uint
1041        {
1042            (*ws).tableValidEnd = (*ws).objectEnd;
1043            (*ws).initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
1044            let alloc = (*ws).objectEnd;
1045            let bytesToAlign =
1046                ZSTD_cwksp_bytes_to_align_ptr(alloc, ZSTD_CWKSP_ALIGNMENT_BYTES as size_t);
1047            let objectEnd = (alloc as *mut u8).add(bytesToAlign) as *mut core::ffi::c_void;
1048            if objectEnd > (*ws).workspaceEnd {
1049                return Error::memory_allocation.to_error_code();
1050            }
1051            (*ws).objectEnd = objectEnd;
1052            (*ws).tableEnd = objectEnd;
1053            if (*ws).tableValidEnd < (*ws).tableEnd {
1054                (*ws).tableValidEnd = (*ws).tableEnd;
1055            }
1056        }
1057        (*ws).phase = phase;
1058        ZSTD_cwksp_assert_internal_consistency(ws);
1059    }
1060    0
1061}
1062#[inline]
1063unsafe fn ZSTD_cwksp_owns_buffer(
1064    ws: *const ZSTD_cwksp,
1065    ptr: *const core::ffi::c_void,
1066) -> core::ffi::c_int {
1067    (!ptr.is_null()
1068        && (*ws).workspace <= ptr as *mut core::ffi::c_void
1069        && ptr < (*ws).workspaceEnd as *const core::ffi::c_void) as core::ffi::c_int
1070}
1071#[inline]
1072unsafe fn ZSTD_cwksp_reserve_internal(
1073    ws: *mut ZSTD_cwksp,
1074    bytes: size_t,
1075    phase: ZSTD_cwksp_alloc_phase_e,
1076) -> *mut core::ffi::c_void {
1077    let mut alloc = core::ptr::null_mut::<core::ffi::c_void>();
1078    if ERR_isError(ZSTD_cwksp_internal_advance_phase(ws, phase)) || bytes == 0 {
1079        return core::ptr::null_mut();
1080    }
1081    alloc = ZSTD_cwksp_reserve_internal_buffer_space(ws, bytes);
1082    alloc
1083}
1084#[inline]
1085unsafe fn ZSTD_cwksp_reserve_buffer(ws: *mut ZSTD_cwksp, bytes: size_t) -> *mut u8 {
1086    ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers) as *mut u8
1087}
1088#[inline]
1089unsafe fn ZSTD_cwksp_reserve_aligned_init_once(
1090    ws: *mut ZSTD_cwksp,
1091    bytes: size_t,
1092) -> *mut core::ffi::c_void {
1093    let alignedBytes = ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES as size_t);
1094    let ptr = ZSTD_cwksp_reserve_internal(ws, alignedBytes, ZSTD_cwksp_alloc_aligned_init_once);
1095    if !ptr.is_null() && ptr < (*ws).initOnceStart {
1096        ptr::write_bytes(
1097            ptr as *mut u8,
1098            0,
1099            (if (((*ws).initOnceStart as *mut u8).offset_from(ptr as *mut u8) as core::ffi::c_long
1100                as size_t)
1101                < alignedBytes
1102            {
1103                ((*ws).initOnceStart as *mut u8).offset_from(ptr as *mut u8) as core::ffi::c_long
1104                    as size_t
1105            } else {
1106                alignedBytes
1107            }) as libc::size_t,
1108        );
1109        (*ws).initOnceStart = ptr;
1110    }
1111    ptr
1112}
1113#[inline]
1114unsafe fn ZSTD_cwksp_reserve_aligned64(
1115    ws: *mut ZSTD_cwksp,
1116    bytes: size_t,
1117) -> *mut core::ffi::c_void {
1118    ZSTD_cwksp_reserve_internal(
1119        ws,
1120        ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES as size_t),
1121        ZSTD_cwksp_alloc_aligned,
1122    )
1123}
1124#[inline]
1125unsafe fn ZSTD_cwksp_reserve_table(ws: *mut ZSTD_cwksp, bytes: size_t) -> *mut core::ffi::c_void {
1126    let phase = ZSTD_cwksp_alloc_aligned_init_once;
1127    let mut alloc = core::ptr::null_mut::<core::ffi::c_void>();
1128    let mut end = core::ptr::null_mut::<core::ffi::c_void>();
1129    let mut top = core::ptr::null_mut::<core::ffi::c_void>();
1130    if ((*ws).phase as core::ffi::c_uint) < phase as core::ffi::c_uint
1131        && ERR_isError(ZSTD_cwksp_internal_advance_phase(ws, phase))
1132    {
1133        return core::ptr::null_mut();
1134    }
1135    alloc = (*ws).tableEnd;
1136    end = (alloc as *mut u8).add(bytes) as *mut core::ffi::c_void;
1137    top = (*ws).allocStart;
1138    ZSTD_cwksp_assert_internal_consistency(ws);
1139    if end > top {
1140        (*ws).allocFailed = 1;
1141        return core::ptr::null_mut();
1142    }
1143    (*ws).tableEnd = end;
1144    alloc
1145}
1146#[inline]
1147unsafe fn ZSTD_cwksp_reserve_object(ws: *mut ZSTD_cwksp, bytes: size_t) -> *mut core::ffi::c_void {
1148    let roundedBytes = ZSTD_cwksp_align(bytes, ::core::mem::size_of::<*mut core::ffi::c_void>());
1149    let alloc = (*ws).objectEnd;
1150    let end = (alloc as *mut u8).add(roundedBytes) as *mut core::ffi::c_void;
1151    ZSTD_cwksp_assert_internal_consistency(ws);
1152    if (*ws).phase as core::ffi::c_uint
1153        != ZSTD_cwksp_alloc_objects as core::ffi::c_int as core::ffi::c_uint
1154        || end > (*ws).workspaceEnd
1155    {
1156        (*ws).allocFailed = 1;
1157        return core::ptr::null_mut();
1158    }
1159    (*ws).objectEnd = end;
1160    (*ws).tableEnd = end;
1161    (*ws).tableValidEnd = end;
1162    alloc
1163}
1164#[inline]
1165unsafe fn ZSTD_cwksp_mark_tables_dirty(ws: *mut ZSTD_cwksp) {
1166    (*ws).tableValidEnd = (*ws).objectEnd;
1167    ZSTD_cwksp_assert_internal_consistency(ws);
1168}
1169#[inline]
1170unsafe fn ZSTD_cwksp_mark_tables_clean(ws: *mut ZSTD_cwksp) {
1171    if (*ws).tableValidEnd < (*ws).tableEnd {
1172        (*ws).tableValidEnd = (*ws).tableEnd;
1173    }
1174    ZSTD_cwksp_assert_internal_consistency(ws);
1175}
1176#[inline]
1177unsafe fn ZSTD_cwksp_clean_tables(ws: *mut ZSTD_cwksp) {
1178    if (*ws).tableValidEnd < (*ws).tableEnd {
1179        ptr::write_bytes(
1180            (*ws).tableValidEnd,
1181            0,
1182            ((*ws).tableEnd as *mut u8).offset_from((*ws).tableValidEnd as *mut u8) as usize,
1183        );
1184    }
1185    ZSTD_cwksp_mark_tables_clean(ws);
1186}
1187#[inline]
1188unsafe fn ZSTD_cwksp_clear_tables(ws: *mut ZSTD_cwksp) {
1189    (*ws).tableEnd = (*ws).objectEnd;
1190    ZSTD_cwksp_assert_internal_consistency(ws);
1191}
1192#[inline]
1193unsafe fn ZSTD_cwksp_clear(ws: *mut ZSTD_cwksp) {
1194    (*ws).tableEnd = (*ws).objectEnd;
1195    (*ws).allocStart = ZSTD_cwksp_initialAllocStart(ws);
1196    (*ws).allocFailed = 0;
1197    if (*ws).phase as core::ffi::c_uint
1198        > ZSTD_cwksp_alloc_aligned_init_once as core::ffi::c_int as core::ffi::c_uint
1199    {
1200        (*ws).phase = ZSTD_cwksp_alloc_aligned_init_once;
1201    }
1202    ZSTD_cwksp_assert_internal_consistency(ws);
1203}
1204#[inline]
1205unsafe fn ZSTD_cwksp_sizeof(ws: *const ZSTD_cwksp) -> size_t {
1206    ((*ws).workspaceEnd as *mut u8).offset_from((*ws).workspace as *mut u8) as core::ffi::c_long
1207        as size_t
1208}
1209#[inline]
1210unsafe fn ZSTD_cwksp_init(
1211    ws: *mut ZSTD_cwksp,
1212    start: *mut core::ffi::c_void,
1213    size: size_t,
1214    isStatic: ZSTD_cwksp_static_alloc_e,
1215) {
1216    (*ws).workspace = start;
1217    (*ws).workspaceEnd = (start as *mut u8).add(size) as *mut core::ffi::c_void;
1218    (*ws).objectEnd = (*ws).workspace;
1219    (*ws).tableValidEnd = (*ws).objectEnd;
1220    (*ws).initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
1221    (*ws).phase = ZSTD_cwksp_alloc_objects;
1222    (*ws).isStatic = isStatic;
1223    ZSTD_cwksp_clear(ws);
1224    (*ws).workspaceOversizedDuration = 0;
1225    ZSTD_cwksp_assert_internal_consistency(ws);
1226}
1227#[inline]
1228unsafe fn ZSTD_cwksp_create(
1229    ws: *mut ZSTD_cwksp,
1230    size: size_t,
1231    customMem: ZSTD_customMem,
1232) -> size_t {
1233    let workspace = ZSTD_customMalloc(size, customMem);
1234    if workspace.is_null() {
1235        return Error::memory_allocation.to_error_code();
1236    }
1237    ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
1238    0
1239}
1240#[inline]
1241unsafe fn ZSTD_cwksp_free(ws: *mut ZSTD_cwksp, customMem: ZSTD_customMem) {
1242    let ptr = (*ws).workspace;
1243    let size = (*ws)
1244        .workspaceEnd
1245        .byte_offset_from_unsigned((*ws).workspace);
1246    ptr::write_bytes(ws as *mut u8, 0, ::core::mem::size_of::<ZSTD_cwksp>());
1247    ZSTD_customFree(ptr, size, customMem);
1248}
1249#[inline]
1250unsafe fn ZSTD_cwksp_move(dst: *mut ZSTD_cwksp, src: *mut ZSTD_cwksp) {
1251    *dst = *src;
1252    ptr::write_bytes(src as *mut u8, 0, ::core::mem::size_of::<ZSTD_cwksp>());
1253}
1254#[inline]
1255unsafe fn ZSTD_cwksp_reserve_failed(ws: *const ZSTD_cwksp) -> core::ffi::c_int {
1256    (*ws).allocFailed as core::ffi::c_int
1257}
1258#[inline]
1259unsafe fn ZSTD_cwksp_available_space(ws: *mut ZSTD_cwksp) -> size_t {
1260    ((*ws).allocStart as *mut u8).offset_from((*ws).tableEnd as *mut u8) as core::ffi::c_long
1261        as size_t
1262}
1263#[inline]
1264unsafe fn ZSTD_cwksp_check_available(
1265    ws: *mut ZSTD_cwksp,
1266    additionalNeededSpace: size_t,
1267) -> core::ffi::c_int {
1268    (ZSTD_cwksp_available_space(ws) >= additionalNeededSpace) as core::ffi::c_int
1269}
1270#[inline]
1271unsafe fn ZSTD_cwksp_check_too_large(
1272    ws: *mut ZSTD_cwksp,
1273    additionalNeededSpace: size_t,
1274) -> core::ffi::c_int {
1275    ZSTD_cwksp_check_available(
1276        ws,
1277        additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR as size_t,
1278    )
1279}
1280#[inline]
1281unsafe fn ZSTD_cwksp_check_wasteful(
1282    ws: *mut ZSTD_cwksp,
1283    additionalNeededSpace: size_t,
1284) -> core::ffi::c_int {
1285    (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace) != 0
1286        && (*ws).workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION)
1287        as core::ffi::c_int
1288}
1289#[inline]
1290unsafe fn ZSTD_cwksp_bump_oversized_duration(ws: *mut ZSTD_cwksp, additionalNeededSpace: size_t) {
1291    if ZSTD_cwksp_check_too_large(ws, additionalNeededSpace) != 0 {
1292        (*ws).workspaceOversizedDuration += 1;
1293    } else {
1294        (*ws).workspaceOversizedDuration = 0;
1295    }
1296}
1297pub const ZSTDMT_JOBSIZE_MIN: core::ffi::c_int = 512 * ((1) << 10);
1298
1299pub const STREAM_ACCUMULATOR_MIN_32: core::ffi::c_int = 25;
1300pub const STREAM_ACCUMULATOR_MIN_64: core::ffi::c_int = 57;
1301pub const ZSTD_COMPRESSBLOCK_DOUBLEFAST: unsafe fn(
1302    &mut ZSTD_MatchState_t,
1303    &mut SeqStore_t,
1304    *mut u32,
1305    *const core::ffi::c_void,
1306    size_t,
1307) -> size_t = ZSTD_compressBlock_doubleFast;
1308pub const ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE: unsafe fn(
1309    &mut ZSTD_MatchState_t,
1310    &mut SeqStore_t,
1311    *mut u32,
1312    *const core::ffi::c_void,
1313    size_t,
1314) -> size_t = ZSTD_compressBlock_doubleFast_dictMatchState;
1315pub const ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT: unsafe fn(
1316    &mut ZSTD_MatchState_t,
1317    &mut SeqStore_t,
1318    *mut u32,
1319    *const core::ffi::c_void,
1320    size_t,
1321) -> size_t = ZSTD_compressBlock_doubleFast_extDict;
1322pub const ZSTD_LAZY_DDSS_BUCKET_LOG: core::ffi::c_int = 2;
1323pub const ZSTD_ROW_HASH_TAG_BITS: core::ffi::c_int = 8;
1324pub const ZSTD_COMPRESSBLOCK_GREEDY: unsafe fn(
1325    &mut ZSTD_MatchState_t,
1326    &mut SeqStore_t,
1327    *mut u32,
1328    *const core::ffi::c_void,
1329    size_t,
1330) -> size_t = ZSTD_compressBlock_greedy;
1331pub const ZSTD_COMPRESSBLOCK_GREEDY_ROW: unsafe fn(
1332    &mut ZSTD_MatchState_t,
1333    &mut SeqStore_t,
1334    *mut u32,
1335    *const core::ffi::c_void,
1336    size_t,
1337) -> size_t = ZSTD_compressBlock_greedy_row;
1338pub const ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE: unsafe fn(
1339    &mut ZSTD_MatchState_t,
1340    &mut SeqStore_t,
1341    *mut u32,
1342    *const core::ffi::c_void,
1343    size_t,
1344) -> size_t = ZSTD_compressBlock_greedy_dictMatchState;
1345pub const ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW: unsafe fn(
1346    &mut ZSTD_MatchState_t,
1347    &mut SeqStore_t,
1348    *mut u32,
1349    *const core::ffi::c_void,
1350    size_t,
1351) -> size_t = ZSTD_compressBlock_greedy_dictMatchState_row;
1352pub const ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH: unsafe fn(
1353    &mut ZSTD_MatchState_t,
1354    &mut SeqStore_t,
1355    *mut u32,
1356    *const core::ffi::c_void,
1357    size_t,
1358) -> size_t = ZSTD_compressBlock_greedy_dedicatedDictSearch;
1359pub const ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW: unsafe fn(
1360    &mut ZSTD_MatchState_t,
1361    &mut SeqStore_t,
1362    *mut u32,
1363    *const core::ffi::c_void,
1364    size_t,
1365) -> size_t = ZSTD_compressBlock_greedy_dedicatedDictSearch_row;
1366pub const ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT: unsafe fn(
1367    &mut ZSTD_MatchState_t,
1368    &mut SeqStore_t,
1369    *mut u32,
1370    *const core::ffi::c_void,
1371    size_t,
1372) -> size_t = ZSTD_compressBlock_greedy_extDict;
1373pub const ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW: unsafe fn(
1374    &mut ZSTD_MatchState_t,
1375    &mut SeqStore_t,
1376    *mut u32,
1377    *const core::ffi::c_void,
1378    size_t,
1379) -> size_t = ZSTD_compressBlock_greedy_extDict_row;
1380pub const ZSTD_COMPRESSBLOCK_LAZY: unsafe fn(
1381    &mut ZSTD_MatchState_t,
1382    &mut SeqStore_t,
1383    *mut u32,
1384    *const core::ffi::c_void,
1385    size_t,
1386) -> size_t = ZSTD_compressBlock_lazy;
1387pub const ZSTD_COMPRESSBLOCK_LAZY_ROW: unsafe fn(
1388    &mut ZSTD_MatchState_t,
1389    &mut SeqStore_t,
1390    *mut u32,
1391    *const core::ffi::c_void,
1392    size_t,
1393) -> size_t = ZSTD_compressBlock_lazy_row;
1394pub const ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE: unsafe fn(
1395    &mut ZSTD_MatchState_t,
1396    &mut SeqStore_t,
1397    *mut u32,
1398    *const core::ffi::c_void,
1399    size_t,
1400) -> size_t = ZSTD_compressBlock_lazy_dictMatchState;
1401pub const ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW: unsafe fn(
1402    &mut ZSTD_MatchState_t,
1403    &mut SeqStore_t,
1404    *mut u32,
1405    *const core::ffi::c_void,
1406    size_t,
1407) -> size_t = ZSTD_compressBlock_lazy_dictMatchState_row;
1408pub const ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH: unsafe fn(
1409    &mut ZSTD_MatchState_t,
1410    &mut SeqStore_t,
1411    *mut u32,
1412    *const core::ffi::c_void,
1413    size_t,
1414) -> size_t = ZSTD_compressBlock_lazy_dedicatedDictSearch;
1415pub const ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW: unsafe fn(
1416    &mut ZSTD_MatchState_t,
1417    &mut SeqStore_t,
1418    *mut u32,
1419    *const core::ffi::c_void,
1420    size_t,
1421) -> size_t = ZSTD_compressBlock_lazy_dedicatedDictSearch_row;
1422pub const ZSTD_COMPRESSBLOCK_LAZY_EXTDICT: unsafe fn(
1423    &mut ZSTD_MatchState_t,
1424    &mut SeqStore_t,
1425    *mut u32,
1426    *const core::ffi::c_void,
1427    size_t,
1428) -> size_t = ZSTD_compressBlock_lazy_extDict;
1429pub const ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW: unsafe fn(
1430    &mut ZSTD_MatchState_t,
1431    &mut SeqStore_t,
1432    *mut u32,
1433    *const core::ffi::c_void,
1434    size_t,
1435) -> size_t = ZSTD_compressBlock_lazy_extDict_row;
1436pub const ZSTD_COMPRESSBLOCK_LAZY2: unsafe fn(
1437    &mut ZSTD_MatchState_t,
1438    &mut SeqStore_t,
1439    *mut u32,
1440    *const core::ffi::c_void,
1441    size_t,
1442) -> size_t = ZSTD_compressBlock_lazy2;
1443pub const ZSTD_COMPRESSBLOCK_LAZY2_ROW: unsafe fn(
1444    &mut ZSTD_MatchState_t,
1445    &mut SeqStore_t,
1446    *mut u32,
1447    *const core::ffi::c_void,
1448    size_t,
1449) -> size_t = ZSTD_compressBlock_lazy2_row;
1450pub const ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE: unsafe fn(
1451    &mut ZSTD_MatchState_t,
1452    &mut SeqStore_t,
1453    *mut u32,
1454    *const core::ffi::c_void,
1455    size_t,
1456) -> size_t = ZSTD_compressBlock_lazy2_dictMatchState;
1457pub const ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW: unsafe fn(
1458    &mut ZSTD_MatchState_t,
1459    &mut SeqStore_t,
1460    *mut u32,
1461    *const core::ffi::c_void,
1462    size_t,
1463) -> size_t = ZSTD_compressBlock_lazy2_dictMatchState_row;
1464pub const ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH: unsafe fn(
1465    &mut ZSTD_MatchState_t,
1466    &mut SeqStore_t,
1467    *mut u32,
1468    *const core::ffi::c_void,
1469    size_t,
1470) -> size_t = ZSTD_compressBlock_lazy2_dedicatedDictSearch;
1471pub const ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW: unsafe fn(
1472    &mut ZSTD_MatchState_t,
1473    &mut SeqStore_t,
1474    *mut u32,
1475    *const core::ffi::c_void,
1476    size_t,
1477) -> size_t = ZSTD_compressBlock_lazy2_dedicatedDictSearch_row;
1478pub const ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT: unsafe fn(
1479    &mut ZSTD_MatchState_t,
1480    &mut SeqStore_t,
1481    *mut u32,
1482    *const core::ffi::c_void,
1483    size_t,
1484) -> size_t = ZSTD_compressBlock_lazy2_extDict;
1485pub const ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW: unsafe fn(
1486    &mut ZSTD_MatchState_t,
1487    &mut SeqStore_t,
1488    *mut u32,
1489    *const core::ffi::c_void,
1490    size_t,
1491) -> size_t = ZSTD_compressBlock_lazy2_extDict_row;
1492pub const ZSTD_COMPRESSBLOCK_BTLAZY2: unsafe fn(
1493    &mut ZSTD_MatchState_t,
1494    &mut SeqStore_t,
1495    *mut u32,
1496    *const core::ffi::c_void,
1497    size_t,
1498) -> size_t = ZSTD_compressBlock_btlazy2;
1499pub const ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE: unsafe fn(
1500    &mut ZSTD_MatchState_t,
1501    &mut SeqStore_t,
1502    *mut u32,
1503    *const core::ffi::c_void,
1504    size_t,
1505) -> size_t = ZSTD_compressBlock_btlazy2_dictMatchState;
1506pub const ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT: unsafe fn(
1507    &mut ZSTD_MatchState_t,
1508    &mut SeqStore_t,
1509    *mut u32,
1510    *const core::ffi::c_void,
1511    size_t,
1512) -> size_t = ZSTD_compressBlock_btlazy2_extDict;
1513pub const ZSTD_COMPRESSBLOCK_BTOPT: unsafe fn(
1514    &mut ZSTD_MatchState_t,
1515    &mut SeqStore_t,
1516    *mut u32,
1517    *const core::ffi::c_void,
1518    size_t,
1519) -> size_t = ZSTD_compressBlock_btopt;
1520pub const ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE: unsafe fn(
1521    &mut ZSTD_MatchState_t,
1522    &mut SeqStore_t,
1523    *mut u32,
1524    *const core::ffi::c_void,
1525    size_t,
1526) -> size_t = ZSTD_compressBlock_btopt_dictMatchState;
1527pub const ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT: unsafe fn(
1528    &mut ZSTD_MatchState_t,
1529    &mut SeqStore_t,
1530    *mut u32,
1531    *const core::ffi::c_void,
1532    size_t,
1533) -> size_t = ZSTD_compressBlock_btopt_extDict;
1534pub const ZSTD_COMPRESSBLOCK_BTULTRA: unsafe fn(
1535    &mut ZSTD_MatchState_t,
1536    &mut SeqStore_t,
1537    *mut u32,
1538    *const core::ffi::c_void,
1539    size_t,
1540) -> size_t = ZSTD_compressBlock_btultra;
1541pub const ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE: unsafe fn(
1542    &mut ZSTD_MatchState_t,
1543    &mut SeqStore_t,
1544    *mut u32,
1545    *const core::ffi::c_void,
1546    size_t,
1547) -> size_t = ZSTD_compressBlock_btultra_dictMatchState;
1548pub const ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT: unsafe fn(
1549    &mut ZSTD_MatchState_t,
1550    &mut SeqStore_t,
1551    *mut u32,
1552    *const core::ffi::c_void,
1553    size_t,
1554) -> size_t = ZSTD_compressBlock_btultra_extDict;
1555pub const ZSTD_COMPRESSBLOCK_BTULTRA2: unsafe fn(
1556    &mut ZSTD_MatchState_t,
1557    &mut SeqStore_t,
1558    *mut u32,
1559    *const core::ffi::c_void,
1560    size_t,
1561) -> size_t = ZSTD_compressBlock_btultra2;
1562pub const ZSTD_LDM_DEFAULT_WINDOW_LOG: core::ffi::c_int = 27;
1563pub const INT_MAX: core::ffi::c_int = __INT_MAX__;
1564#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBound))]
1565pub extern "C" fn ZSTD_compressBound(srcSize: size_t) -> size_t {
1566    let r = if srcSize as core::ffi::c_ulonglong
1567        >= (if ::core::mem::size_of::<size_t>() == 8 {
1568            0xff00ff00ff00ff00 as core::ffi::c_ulonglong
1569        } else {
1570            0xff00ff00 as core::ffi::c_uint as core::ffi::c_ulonglong
1571        }) {
1572        0
1573    } else {
1574        srcSize
1575            .wrapping_add(srcSize >> 8)
1576            .wrapping_add(if srcSize < ((128) << 10) as size_t {
1577                (((128) << 10) as size_t).wrapping_sub(srcSize) >> 11
1578            } else {
1579                0
1580            })
1581    };
1582    if r == 0 {
1583        return Error::srcSize_wrong.to_error_code();
1584    }
1585    r
1586}
1587#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCCtx))]
1588pub unsafe extern "C" fn ZSTD_createCCtx() -> *mut ZSTD_CCtx {
1589    ZSTD_createCCtx_advanced(ZSTD_customMem::default())
1590}
1591unsafe fn ZSTD_initCCtx(cctx: *mut ZSTD_CCtx, memManager: ZSTD_customMem) {
1592    ptr::write_bytes(cctx as *mut u8, 0, ::core::mem::size_of::<ZSTD_CCtx>());
1593    (*cctx).customMem = memManager;
1594    (*cctx).bmi2 = ZSTD_cpuSupportsBmi2() as _;
1595    let _err = ZSTD_CCtx_reset(cctx, ZSTD_ResetDirective::ZSTD_reset_parameters);
1596}
1597#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCCtx_advanced))]
1598pub unsafe extern "C" fn ZSTD_createCCtx_advanced(customMem: ZSTD_customMem) -> *mut ZSTD_CCtx {
1599    let cctx = ZSTD_customMalloc(::core::mem::size_of::<ZSTD_CCtx>(), customMem) as *mut ZSTD_CCtx;
1600    if cctx.is_null() {
1601        return core::ptr::null_mut();
1602    }
1603    ZSTD_initCCtx(cctx, customMem);
1604    cctx
1605}
1606#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initStaticCCtx))]
1607pub unsafe extern "C" fn ZSTD_initStaticCCtx(
1608    workspace: *mut core::ffi::c_void,
1609    workspaceSize: size_t,
1610) -> *mut ZSTD_CCtx {
1611    let mut ws = ZSTD_cwksp {
1612        workspace: core::ptr::null_mut::<core::ffi::c_void>(),
1613        workspaceEnd: core::ptr::null_mut::<core::ffi::c_void>(),
1614        objectEnd: core::ptr::null_mut::<core::ffi::c_void>(),
1615        tableEnd: core::ptr::null_mut::<core::ffi::c_void>(),
1616        tableValidEnd: core::ptr::null_mut::<core::ffi::c_void>(),
1617        allocStart: core::ptr::null_mut::<core::ffi::c_void>(),
1618        initOnceStart: core::ptr::null_mut::<core::ffi::c_void>(),
1619        allocFailed: 0,
1620        workspaceOversizedDuration: 0,
1621        phase: ZSTD_cwksp_alloc_objects,
1622        isStatic: ZSTD_cwksp_dynamic_alloc,
1623    };
1624    let mut cctx = core::ptr::null_mut::<ZSTD_CCtx>();
1625    if workspaceSize <= ::core::mem::size_of::<ZSTD_CCtx>() {
1626        return core::ptr::null_mut();
1627    }
1628    if workspace as size_t & 7 != 0 {
1629        return core::ptr::null_mut();
1630    }
1631    ZSTD_cwksp_init(&mut ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
1632    cctx =
1633        ZSTD_cwksp_reserve_object(&mut ws, ::core::mem::size_of::<ZSTD_CCtx>()) as *mut ZSTD_CCtx;
1634    if cctx.is_null() {
1635        return core::ptr::null_mut();
1636    }
1637    ptr::write_bytes(cctx as *mut u8, 0, ::core::mem::size_of::<ZSTD_CCtx>());
1638    ZSTD_cwksp_move(&mut (*cctx).workspace, &mut ws);
1639    (*cctx).staticSize = workspaceSize;
1640    if ZSTD_cwksp_check_available(
1641        &mut (*cctx).workspace,
1642        (if ((((8) << 10) + 512) as size_t).wrapping_add(
1643            (::core::mem::size_of::<core::ffi::c_uint>())
1644                .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
1645        ) > 8208
1646        {
1647            ((((8) << 10) + 512) as size_t).wrapping_add(
1648                (::core::mem::size_of::<core::ffi::c_uint>())
1649                    .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
1650            )
1651        } else {
1652            8208
1653        })
1654        .wrapping_add(
1655            (2 as size_t).wrapping_mul(::core::mem::size_of::<ZSTD_compressedBlockState_t>()),
1656        ),
1657    ) == 0
1658    {
1659        return core::ptr::null_mut();
1660    }
1661    (*cctx).blockState.prevCBlock = ZSTD_cwksp_reserve_object(
1662        &mut (*cctx).workspace,
1663        ::core::mem::size_of::<ZSTD_compressedBlockState_t>(),
1664    ) as *mut ZSTD_compressedBlockState_t;
1665    (*cctx).blockState.nextCBlock = ZSTD_cwksp_reserve_object(
1666        &mut (*cctx).workspace,
1667        ::core::mem::size_of::<ZSTD_compressedBlockState_t>(),
1668    ) as *mut ZSTD_compressedBlockState_t;
1669    (*cctx).tmpWorkspace = ZSTD_cwksp_reserve_object(
1670        &mut (*cctx).workspace,
1671        if ((((8) << 10) + 512) as size_t).wrapping_add(
1672            (::core::mem::size_of::<core::ffi::c_uint>())
1673                .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
1674        ) > 8208
1675        {
1676            ((((8) << 10) + 512) as size_t).wrapping_add(
1677                (::core::mem::size_of::<core::ffi::c_uint>())
1678                    .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
1679            )
1680        } else {
1681            8208
1682        },
1683    );
1684    (*cctx).tmpWkspSize = if ((((8) << 10) + 512) as size_t).wrapping_add(
1685        (::core::mem::size_of::<core::ffi::c_uint>())
1686            .wrapping_mul(((if 35 > 52 as core::ffi::c_int { 35 } else { 52 }) + 2) as size_t),
1687    ) > 8208 as size_t
1688    {
1689        ((((8) << 10) + 512) as size_t).wrapping_add(
1690            (::core::mem::size_of::<core::ffi::c_uint>())
1691                .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
1692        )
1693    } else {
1694        8208
1695    };
1696    (*cctx).bmi2 = ZSTD_cpuSupportsBmi2() as _;
1697    cctx
1698}
1699unsafe fn ZSTD_clearAllDicts(cctx: *mut ZSTD_CCtx) {
1700    ZSTD_customFree(
1701        (*cctx).localDict.dictBuffer,
1702        (*cctx).localDict.dictSize,
1703        (*cctx).customMem,
1704    );
1705    ZSTD_freeCDict((*cctx).localDict.cdict);
1706    ptr::write_bytes(
1707        &mut (*cctx).localDict as *mut ZSTD_localDict as *mut u8,
1708        0,
1709        ::core::mem::size_of::<ZSTD_localDict>(),
1710    );
1711    ptr::write_bytes(
1712        &mut (*cctx).prefixDict as *mut ZSTD_prefixDict as *mut u8,
1713        0,
1714        ::core::mem::size_of::<ZSTD_prefixDict>(),
1715    );
1716    (*cctx).cdict = core::ptr::null();
1717}
1718unsafe fn ZSTD_sizeof_localDict(dict: ZSTD_localDict) -> size_t {
1719    let bufferSize = if !(dict.dictBuffer).is_null() {
1720        dict.dictSize
1721    } else {
1722        0
1723    };
1724    let cdictSize = ZSTD_sizeof_CDict(dict.cdict);
1725    bufferSize.wrapping_add(cdictSize)
1726}
1727unsafe fn ZSTD_freeCCtxContent(cctx: *mut ZSTD_CCtx) {
1728    ZSTD_clearAllDicts(cctx);
1729    ZSTDMT_freeCCtx((*cctx).mtctx);
1730    (*cctx).mtctx = core::ptr::null_mut();
1731    ZSTD_cwksp_free(&mut (*cctx).workspace, (*cctx).customMem);
1732}
1733#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_freeCCtx))]
1734pub unsafe extern "C" fn ZSTD_freeCCtx(cctx: *mut ZSTD_CCtx) -> size_t {
1735    if cctx.is_null() {
1736        return 0;
1737    }
1738    if (*cctx).staticSize != 0 {
1739        return Error::memory_allocation.to_error_code();
1740    }
1741    let cctxInWorkspace =
1742        ZSTD_cwksp_owns_buffer(&(*cctx).workspace, cctx as *const core::ffi::c_void);
1743    ZSTD_freeCCtxContent(cctx);
1744    if cctxInWorkspace == 0 {
1745        ZSTD_customFree(
1746            cctx as *mut core::ffi::c_void,
1747            ::core::mem::size_of::<ZSTD_CCtx>(),
1748            (*cctx).customMem,
1749        );
1750    }
1751    0
1752}
1753unsafe fn ZSTD_sizeof_mtctx(cctx: *const ZSTD_CCtx) -> size_t {
1754    ZSTDMT_sizeof_CCtx((*cctx).mtctx)
1755}
1756#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_sizeof_CCtx))]
1757pub unsafe extern "C" fn ZSTD_sizeof_CCtx(cctx: *const ZSTD_CCtx) -> size_t {
1758    if cctx.is_null() {
1759        return 0;
1760    }
1761    (if (*cctx).workspace.workspace == cctx as *mut core::ffi::c_void {
1762        0
1763    } else {
1764        ::core::mem::size_of::<ZSTD_CCtx>()
1765    })
1766    .wrapping_add(ZSTD_cwksp_sizeof(&(*cctx).workspace))
1767    .wrapping_add(ZSTD_sizeof_localDict((*cctx).localDict))
1768    .wrapping_add(ZSTD_sizeof_mtctx(cctx))
1769}
1770#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_sizeof_CStream))]
1771pub unsafe extern "C" fn ZSTD_sizeof_CStream(zcs: *const ZSTD_CStream) -> size_t {
1772    ZSTD_sizeof_CCtx(zcs)
1773}
1774pub unsafe fn ZSTD_getSeqStore(ctx: *const ZSTD_CCtx) -> *const SeqStore_t {
1775    &(*ctx).seqStore
1776}
1777unsafe fn ZSTD_rowMatchFinderSupported(strategy: ZSTD_strategy) -> core::ffi::c_int {
1778    (strategy as core::ffi::c_uint >= ZSTD_greedy as core::ffi::c_int as core::ffi::c_uint
1779        && strategy as core::ffi::c_uint <= ZSTD_lazy2 as core::ffi::c_int as core::ffi::c_uint)
1780        as core::ffi::c_int
1781}
1782unsafe fn ZSTD_rowMatchFinderUsed(
1783    strategy: ZSTD_strategy,
1784    mode: ZSTD_ParamSwitch_e,
1785) -> core::ffi::c_int {
1786    (ZSTD_rowMatchFinderSupported(strategy) != 0 && mode == ZSTD_ParamSwitch_e::ZSTD_ps_enable)
1787        as core::ffi::c_int
1788}
1789unsafe fn ZSTD_resolveRowMatchFinderMode(
1790    mut mode: ZSTD_ParamSwitch_e,
1791    cParams: *const ZSTD_compressionParameters,
1792) -> ZSTD_ParamSwitch_e {
1793    let kWindowLogLowerBound = 14;
1794    if mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
1795        return mode;
1796    }
1797    mode = ZSTD_ParamSwitch_e::ZSTD_ps_disable;
1798    if ZSTD_rowMatchFinderSupported((*cParams).strategy) == 0 {
1799        return mode;
1800    }
1801    if (*cParams).windowLog > kWindowLogLowerBound {
1802        mode = ZSTD_ParamSwitch_e::ZSTD_ps_enable;
1803    }
1804    mode
1805}
1806unsafe fn ZSTD_resolveBlockSplitterMode(
1807    mode: ZSTD_ParamSwitch_e,
1808    cParams: *const ZSTD_compressionParameters,
1809) -> ZSTD_ParamSwitch_e {
1810    if mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
1811        return mode;
1812    }
1813    if (*cParams).strategy as core::ffi::c_uint
1814        >= ZSTD_btopt as core::ffi::c_int as core::ffi::c_uint
1815        && (*cParams).windowLog >= 17
1816    {
1817        ZSTD_ParamSwitch_e::ZSTD_ps_enable
1818    } else {
1819        ZSTD_ParamSwitch_e::ZSTD_ps_disable
1820    }
1821}
1822unsafe fn ZSTD_allocateChainTable(
1823    strategy: ZSTD_strategy,
1824    useRowMatchFinder: ZSTD_ParamSwitch_e,
1825    forDDSDict: u32,
1826) -> core::ffi::c_int {
1827    (forDDSDict != 0
1828        || strategy as core::ffi::c_uint != ZSTD_fast as core::ffi::c_int as core::ffi::c_uint
1829            && ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder) == 0) as core::ffi::c_int
1830}
1831unsafe fn ZSTD_resolveEnableLdm(
1832    mode: ZSTD_ParamSwitch_e,
1833    cParams: *const ZSTD_compressionParameters,
1834) -> ZSTD_ParamSwitch_e {
1835    if mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
1836        return mode;
1837    }
1838    if (*cParams).strategy as core::ffi::c_uint
1839        >= ZSTD_btopt as core::ffi::c_int as core::ffi::c_uint
1840        && (*cParams).windowLog >= 27
1841    {
1842        ZSTD_ParamSwitch_e::ZSTD_ps_enable
1843    } else {
1844        ZSTD_ParamSwitch_e::ZSTD_ps_disable
1845    }
1846}
1847unsafe fn ZSTD_resolveExternalSequenceValidation(mode: core::ffi::c_int) -> core::ffi::c_int {
1848    mode
1849}
1850unsafe fn ZSTD_resolveMaxBlockSize(maxBlockSize: size_t) -> size_t {
1851    if maxBlockSize == 0 {
1852        ZSTD_BLOCKSIZE_MAX as size_t
1853    } else {
1854        maxBlockSize
1855    }
1856}
1857unsafe fn ZSTD_resolveExternalRepcodeSearch(
1858    value: ZSTD_ParamSwitch_e,
1859    cLevel: core::ffi::c_int,
1860) -> ZSTD_ParamSwitch_e {
1861    if value != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
1862        return value;
1863    }
1864    if cLevel < 10 {
1865        ZSTD_ParamSwitch_e::ZSTD_ps_disable
1866    } else {
1867        ZSTD_ParamSwitch_e::ZSTD_ps_enable
1868    }
1869}
1870unsafe fn ZSTD_CDictIndicesAreTagged(
1871    cParams: *const ZSTD_compressionParameters,
1872) -> core::ffi::c_int {
1873    ((*cParams).strategy as core::ffi::c_uint == ZSTD_fast as core::ffi::c_int as core::ffi::c_uint
1874        || (*cParams).strategy as core::ffi::c_uint
1875            == ZSTD_dfast as core::ffi::c_int as core::ffi::c_uint) as core::ffi::c_int
1876}
1877unsafe fn ZSTD_makeCCtxParamsFromCParams(cParams: ZSTD_compressionParameters) -> ZSTD_CCtx_params {
1878    let mut cctxParams = ZSTD_CCtx_params_s {
1879        format: Format::ZSTD_f_zstd1,
1880        cParams: ZSTD_compressionParameters {
1881            windowLog: 0,
1882            chainLog: 0,
1883            hashLog: 0,
1884            searchLog: 0,
1885            minMatch: 0,
1886            targetLength: 0,
1887            strategy: 0,
1888        },
1889        fParams: ZSTD_frameParameters {
1890            contentSizeFlag: 0,
1891            checksumFlag: 0,
1892            noDictIDFlag: 0,
1893        },
1894        compressionLevel: 0,
1895        forceWindow: 0,
1896        targetCBlockSize: 0,
1897        srcSizeHint: 0,
1898        attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
1899        literalCompressionMode: ParamSwitch::Auto,
1900        nbWorkers: 0,
1901        jobSize: 0,
1902        overlapLog: 0,
1903        rsyncable: 0,
1904        ldmParams: ldmParams_t {
1905            enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
1906            hashLog: 0,
1907            bucketSizeLog: 0,
1908            minMatchLength: 0,
1909            hashRateLog: 0,
1910            windowLog: 0,
1911        },
1912        enableDedicatedDictSearch: 0,
1913        inBufferMode: ZSTD_bm_buffered,
1914        outBufferMode: ZSTD_bm_buffered,
1915        blockDelimiters: ZSTD_sf_noBlockDelimiters,
1916        validateSequences: 0,
1917        postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
1918        preBlockSplitter_level: 0,
1919        maxBlockSize: 0,
1920        useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
1921        deterministicRefPrefix: 0,
1922        customMem: ZSTD_customMem::default(),
1923        prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
1924        enableMatchFinderFallback: 0,
1925        extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
1926        extSeqProdFunc: None,
1927        searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
1928    };
1929    ZSTD_CCtxParams_init(&mut cctxParams, ZSTD_CLEVEL_DEFAULT);
1930    cctxParams.cParams = cParams;
1931    cctxParams.ldmParams.enableLdm =
1932        ZSTD_resolveEnableLdm(cctxParams.ldmParams.enableLdm, &cParams);
1933    if cctxParams.ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
1934        ZSTD_ldm_adjustParameters(&mut cctxParams.ldmParams, &cParams);
1935    }
1936    cctxParams.postBlockSplitter =
1937        ZSTD_resolveBlockSplitterMode(cctxParams.postBlockSplitter, &cParams);
1938    cctxParams.useRowMatchFinder =
1939        ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
1940    cctxParams.validateSequences =
1941        ZSTD_resolveExternalSequenceValidation(cctxParams.validateSequences);
1942    cctxParams.maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams.maxBlockSize);
1943    cctxParams.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(
1944        cctxParams.searchForExternalRepcodes,
1945        cctxParams.compressionLevel,
1946    );
1947    cctxParams
1948}
1949unsafe fn ZSTD_createCCtxParams_advanced(customMem: ZSTD_customMem) -> *mut ZSTD_CCtx_params {
1950    let params = ZSTD_customCalloc(::core::mem::size_of::<ZSTD_CCtx_params>(), customMem)
1951        as *mut ZSTD_CCtx_params;
1952    if params.is_null() {
1953        return core::ptr::null_mut();
1954    }
1955    ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
1956    (*params).customMem = customMem;
1957    params
1958}
1959#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCCtxParams))]
1960pub unsafe extern "C" fn ZSTD_createCCtxParams() -> *mut ZSTD_CCtx_params {
1961    ZSTD_createCCtxParams_advanced(ZSTD_customMem::default())
1962}
1963#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_freeCCtxParams))]
1964pub unsafe extern "C" fn ZSTD_freeCCtxParams(params: *mut ZSTD_CCtx_params) -> size_t {
1965    if params.is_null() {
1966        return 0;
1967    }
1968    ZSTD_customFree(
1969        params as *mut core::ffi::c_void,
1970        ::core::mem::size_of::<ZSTD_CCtx_params>(),
1971        (*params).customMem,
1972    );
1973    0
1974}
1975#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtxParams_reset))]
1976pub unsafe extern "C" fn ZSTD_CCtxParams_reset(params: *mut ZSTD_CCtx_params) -> size_t {
1977    ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT)
1978}
1979#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtxParams_init))]
1980pub unsafe extern "C" fn ZSTD_CCtxParams_init(
1981    cctxParams: *mut ZSTD_CCtx_params,
1982    compressionLevel: core::ffi::c_int,
1983) -> size_t {
1984    if cctxParams.is_null() {
1985        return Error::GENERIC.to_error_code();
1986    }
1987    ptr::write_bytes(
1988        cctxParams as *mut u8,
1989        0,
1990        ::core::mem::size_of::<ZSTD_CCtx_params>(),
1991    );
1992    (*cctxParams).compressionLevel = compressionLevel;
1993    (*cctxParams).fParams.contentSizeFlag = 1;
1994    0
1995}
1996pub const ZSTD_NO_CLEVEL: core::ffi::c_int = 0;
1997unsafe fn ZSTD_CCtxParams_init_internal(
1998    cctxParams: *mut ZSTD_CCtx_params,
1999    params: *const ZSTD_parameters,
2000    compressionLevel: core::ffi::c_int,
2001) {
2002    ptr::write_bytes(
2003        cctxParams as *mut u8,
2004        0,
2005        ::core::mem::size_of::<ZSTD_CCtx_params>(),
2006    );
2007    (*cctxParams).cParams = (*params).cParams;
2008    (*cctxParams).fParams = (*params).fParams;
2009    (*cctxParams).compressionLevel = compressionLevel;
2010    (*cctxParams).useRowMatchFinder =
2011        ZSTD_resolveRowMatchFinderMode((*cctxParams).useRowMatchFinder, &(*params).cParams);
2012    (*cctxParams).postBlockSplitter =
2013        ZSTD_resolveBlockSplitterMode((*cctxParams).postBlockSplitter, &(*params).cParams);
2014    (*cctxParams).ldmParams.enableLdm =
2015        ZSTD_resolveEnableLdm((*cctxParams).ldmParams.enableLdm, &(*params).cParams);
2016    (*cctxParams).validateSequences =
2017        ZSTD_resolveExternalSequenceValidation((*cctxParams).validateSequences);
2018    (*cctxParams).maxBlockSize = ZSTD_resolveMaxBlockSize((*cctxParams).maxBlockSize);
2019    (*cctxParams).searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(
2020        (*cctxParams).searchForExternalRepcodes,
2021        compressionLevel,
2022    );
2023}
2024#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtxParams_init_advanced))]
2025pub unsafe extern "C" fn ZSTD_CCtxParams_init_advanced(
2026    cctxParams: *mut ZSTD_CCtx_params,
2027    params: ZSTD_parameters,
2028) -> size_t {
2029    if cctxParams.is_null() {
2030        return Error::GENERIC.to_error_code();
2031    }
2032    let err_code = ZSTD_checkCParams(params.cParams);
2033    if ERR_isError(err_code) {
2034        return err_code;
2035    }
2036    ZSTD_CCtxParams_init_internal(cctxParams, &params, ZSTD_NO_CLEVEL);
2037    0
2038}
2039unsafe fn ZSTD_CCtxParams_setZstdParams(
2040    cctxParams: *mut ZSTD_CCtx_params,
2041    params: *const ZSTD_parameters,
2042) {
2043    (*cctxParams).cParams = (*params).cParams;
2044    (*cctxParams).fParams = (*params).fParams;
2045    (*cctxParams).compressionLevel = ZSTD_NO_CLEVEL;
2046}
2047#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_cParam_getBounds))]
2048pub unsafe extern "C" fn ZSTD_cParam_getBounds(param: ZSTD_cParameter) -> ZSTD_bounds {
2049    let mut bounds = {
2050        ZSTD_bounds {
2051            error: 0,
2052            lowerBound: 0,
2053            upperBound: 0,
2054        }
2055    };
2056    match param.0 {
2057        100 => {
2058            bounds.lowerBound = ZSTD_minCLevel();
2059            bounds.upperBound = ZSTD_maxCLevel();
2060            bounds
2061        }
2062        101 => {
2063            bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
2064            bounds.upperBound = if ::core::mem::size_of::<size_t>() == 4 {
2065                ZSTD_WINDOWLOG_MAX_32
2066            } else {
2067                ZSTD_WINDOWLOG_MAX_64
2068            };
2069            bounds
2070        }
2071        102 => {
2072            bounds.lowerBound = ZSTD_HASHLOG_MIN;
2073            bounds.upperBound = if (if ::core::mem::size_of::<size_t>() == 4 {
2074                ZSTD_WINDOWLOG_MAX_32
2075            } else {
2076                ZSTD_WINDOWLOG_MAX_64
2077            }) < 30
2078            {
2079                if ::core::mem::size_of::<size_t>() == 4 {
2080                    ZSTD_WINDOWLOG_MAX_32
2081                } else {
2082                    ZSTD_WINDOWLOG_MAX_64
2083                }
2084            } else {
2085                30
2086            };
2087            bounds
2088        }
2089        103 => {
2090            bounds.lowerBound = ZSTD_CHAINLOG_MIN;
2091            bounds.upperBound = if ::core::mem::size_of::<size_t>() == 4 {
2092                ZSTD_CHAINLOG_MAX_32
2093            } else {
2094                ZSTD_CHAINLOG_MAX_64
2095            };
2096            bounds
2097        }
2098        104 => {
2099            bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
2100            bounds.upperBound = (if ::core::mem::size_of::<size_t>() == 4 {
2101                ZSTD_WINDOWLOG_MAX_32
2102            } else {
2103                ZSTD_WINDOWLOG_MAX_64
2104            }) - 1;
2105            bounds
2106        }
2107        105 => {
2108            bounds.lowerBound = ZSTD_MINMATCH_MIN;
2109            bounds.upperBound = ZSTD_MINMATCH_MAX;
2110            bounds
2111        }
2112        106 => {
2113            bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
2114            bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
2115            bounds
2116        }
2117        107 => {
2118            bounds.lowerBound = ZSTD_STRATEGY_MIN;
2119            bounds.upperBound = ZSTD_STRATEGY_MAX;
2120            bounds
2121        }
2122        200 => {
2123            bounds.lowerBound = 0;
2124            bounds.upperBound = 1;
2125            bounds
2126        }
2127        201 => {
2128            bounds.lowerBound = 0;
2129            bounds.upperBound = 1;
2130            bounds
2131        }
2132        202 => {
2133            bounds.lowerBound = 0;
2134            bounds.upperBound = 1;
2135            bounds
2136        }
2137        400 => {
2138            bounds.lowerBound = 0;
2139            bounds.upperBound = if ::core::mem::size_of::<*mut core::ffi::c_void>() == 4 {
2140                64
2141            } else {
2142                256
2143            };
2144            bounds
2145        }
2146        401 => {
2147            bounds.lowerBound = 0;
2148            bounds.upperBound = if MEM_32bits() {
2149                512 * (1 << 20)
2150            } else {
2151                1024 * (1 << 20)
2152            };
2153            bounds
2154        }
2155        402 => {
2156            bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
2157            bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
2158            bounds
2159        }
2160        1005 => {
2161            bounds.lowerBound = 0;
2162            bounds.upperBound = 1;
2163            bounds
2164        }
2165        160 => {
2166            bounds.lowerBound = ZSTD_ParamSwitch_e::ZSTD_ps_auto as core::ffi::c_int;
2167            bounds.upperBound = ZSTD_ParamSwitch_e::ZSTD_ps_disable as core::ffi::c_int;
2168            bounds
2169        }
2170        161 => {
2171            bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
2172            bounds.upperBound = if (if ::core::mem::size_of::<size_t>() == 4 {
2173                ZSTD_WINDOWLOG_MAX_32
2174            } else {
2175                ZSTD_WINDOWLOG_MAX_64
2176            }) < 30
2177            {
2178                if ::core::mem::size_of::<size_t>() == 4 {
2179                    ZSTD_WINDOWLOG_MAX_32
2180                } else {
2181                    ZSTD_WINDOWLOG_MAX_64
2182                }
2183            } else {
2184                30
2185            };
2186            bounds
2187        }
2188        162 => {
2189            bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
2190            bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
2191            bounds
2192        }
2193        163 => {
2194            bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
2195            bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
2196            bounds
2197        }
2198        164 => {
2199            bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
2200            bounds.upperBound = (if ::core::mem::size_of::<size_t>() == 4 {
2201                ZSTD_WINDOWLOG_MAX_32
2202            } else {
2203                ZSTD_WINDOWLOG_MAX_64
2204            }) - ZSTD_HASHLOG_MIN;
2205            bounds
2206        }
2207        500 => {
2208            bounds.lowerBound = 0;
2209            bounds.upperBound = 1;
2210            bounds
2211        }
2212        1000 => {
2213            bounds.lowerBound = 0;
2214            bounds.upperBound = 1;
2215            bounds
2216        }
2217        10 => {
2218            bounds.lowerBound = Format::ZSTD_f_zstd1 as core::ffi::c_int;
2219            bounds.upperBound = Format::ZSTD_f_zstd1_magicless as core::ffi::c_int;
2220            bounds
2221        }
2222        1001 => {
2223            bounds.lowerBound = ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach.0 as core::ffi::c_int;
2224            bounds.upperBound = ZSTD_dictAttachPref_e::ZSTD_dictForceLoad.0 as core::ffi::c_int;
2225            bounds
2226        }
2227        1002 => {
2228            bounds.lowerBound = ZSTD_ParamSwitch_e::ZSTD_ps_auto as core::ffi::c_int;
2229            bounds.upperBound = ZSTD_ParamSwitch_e::ZSTD_ps_disable as core::ffi::c_int;
2230            bounds
2231        }
2232        130 => {
2233            bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
2234            bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
2235            bounds
2236        }
2237        1004 => {
2238            bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
2239            bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
2240            bounds
2241        }
2242        1006 | 1007 => {
2243            bounds.lowerBound = ZSTD_bm_buffered as core::ffi::c_int;
2244            bounds.upperBound = ZSTD_bm_stable as core::ffi::c_int;
2245            bounds
2246        }
2247        1008 => {
2248            bounds.lowerBound = ZSTD_sf_noBlockDelimiters as core::ffi::c_int;
2249            bounds.upperBound = ZSTD_sf_explicitBlockDelimiters as core::ffi::c_int;
2250            bounds
2251        }
2252        1009 => {
2253            bounds.lowerBound = 0;
2254            bounds.upperBound = 1;
2255            bounds
2256        }
2257        1010 => {
2258            bounds.lowerBound = ZSTD_ParamSwitch_e::ZSTD_ps_auto as core::ffi::c_int;
2259            bounds.upperBound = ZSTD_ParamSwitch_e::ZSTD_ps_disable as core::ffi::c_int;
2260            bounds
2261        }
2262        1017 => {
2263            bounds.lowerBound = 0;
2264            bounds.upperBound = ZSTD_BLOCKSPLITTER_LEVEL_MAX;
2265            bounds
2266        }
2267        1011 => {
2268            bounds.lowerBound = ZSTD_ParamSwitch_e::ZSTD_ps_auto as core::ffi::c_int;
2269            bounds.upperBound = ZSTD_ParamSwitch_e::ZSTD_ps_disable as core::ffi::c_int;
2270            bounds
2271        }
2272        1012 => {
2273            bounds.lowerBound = 0;
2274            bounds.upperBound = 1;
2275            bounds
2276        }
2277        1013 => {
2278            bounds.lowerBound = ZSTD_ParamSwitch_e::ZSTD_ps_auto as core::ffi::c_int;
2279            bounds.upperBound = ZSTD_ParamSwitch_e::ZSTD_ps_disable as core::ffi::c_int;
2280            bounds
2281        }
2282        1014 => {
2283            bounds.lowerBound = 0;
2284            bounds.upperBound = 1;
2285            bounds
2286        }
2287        1015 => {
2288            bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
2289            bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
2290            bounds
2291        }
2292        1016 => {
2293            bounds.lowerBound = ZSTD_ParamSwitch_e::ZSTD_ps_auto as core::ffi::c_int;
2294            bounds.upperBound = ZSTD_ParamSwitch_e::ZSTD_ps_disable as core::ffi::c_int;
2295            bounds
2296        }
2297        _ => {
2298            bounds.error = Error::parameter_unsupported.to_error_code();
2299            bounds
2300        }
2301    }
2302}
2303unsafe fn ZSTD_cParam_clampBounds(cParam: ZSTD_cParameter, value: *mut core::ffi::c_int) -> size_t {
2304    let bounds = ZSTD_cParam_getBounds(cParam);
2305    if ERR_isError(bounds.error) {
2306        return bounds.error;
2307    }
2308    if *value < bounds.lowerBound {
2309        *value = bounds.lowerBound;
2310    }
2311    if *value > bounds.upperBound {
2312        *value = bounds.upperBound;
2313    }
2314    0
2315}
2316unsafe fn ZSTD_isUpdateAuthorized(param: ZSTD_cParameter) -> core::ffi::c_int {
2317    match param {
2318        ZSTD_cParameter::ZSTD_c_compressionLevel
2319        | ZSTD_cParameter::ZSTD_c_hashLog
2320        | ZSTD_cParameter::ZSTD_c_chainLog
2321        | ZSTD_cParameter::ZSTD_c_searchLog
2322        | ZSTD_cParameter::ZSTD_c_minMatch
2323        | ZSTD_cParameter::ZSTD_c_targetLength
2324        | ZSTD_cParameter::ZSTD_c_strategy => 1,
2325
2326        _ if param == ZSTD_cParameter::ZSTD_c_blockSplitterLevel => 1,
2327
2328        _ => 0,
2329    }
2330}
2331#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_setParameter))]
2332pub unsafe extern "C" fn ZSTD_CCtx_setParameter(
2333    cctx: *mut ZSTD_CCtx,
2334    param: ZSTD_cParameter,
2335    value: core::ffi::c_int,
2336) -> size_t {
2337    if (*cctx).streamStage != zcss_init {
2338        if ZSTD_isUpdateAuthorized(param) != 0 {
2339            (*cctx).cParamsChanged = 1;
2340        } else {
2341            return Error::stage_wrong.to_error_code();
2342        }
2343    }
2344
2345    match param {
2346        ZSTD_cParameter::ZSTD_c_nbWorkers => {
2347            if value != 0 && (*cctx).staticSize != 0 {
2348                Error::parameter_unsupported.to_error_code()
2349            } else {
2350                ZSTD_CCtxParams_setParameter(&mut (*cctx).requestedParams, param, value)
2351            }
2352        }
2353
2354        ZSTD_cParameter::ZSTD_c_compressionLevel
2355        | ZSTD_cParameter::ZSTD_c_windowLog
2356        | ZSTD_cParameter::ZSTD_c_hashLog
2357        | ZSTD_cParameter::ZSTD_c_chainLog
2358        | ZSTD_cParameter::ZSTD_c_searchLog
2359        | ZSTD_cParameter::ZSTD_c_minMatch
2360        | ZSTD_cParameter::ZSTD_c_targetLength
2361        | ZSTD_cParameter::ZSTD_c_strategy
2362        | ZSTD_cParameter::ZSTD_c_ldmHashRateLog
2363        | ZSTD_cParameter::ZSTD_c_format
2364        | ZSTD_cParameter::ZSTD_c_contentSizeFlag
2365        | ZSTD_cParameter::ZSTD_c_checksumFlag
2366        | ZSTD_cParameter::ZSTD_c_dictIDFlag
2367        | ZSTD_cParameter::ZSTD_c_forceMaxWindow
2368        | ZSTD_cParameter::ZSTD_c_forceAttachDict
2369        | ZSTD_cParameter::ZSTD_c_literalCompressionMode
2370        | ZSTD_cParameter::ZSTD_c_jobSize
2371        | ZSTD_cParameter::ZSTD_c_overlapLog
2372        | ZSTD_cParameter::ZSTD_c_rsyncable
2373        | ZSTD_cParameter::ZSTD_c_enableDedicatedDictSearch
2374        | ZSTD_cParameter::ZSTD_c_enableLongDistanceMatching
2375        | ZSTD_cParameter::ZSTD_c_ldmHashLog
2376        | ZSTD_cParameter::ZSTD_c_ldmMinMatch
2377        | ZSTD_cParameter::ZSTD_c_ldmBucketSizeLog
2378        | ZSTD_cParameter::ZSTD_c_targetCBlockSize
2379        | ZSTD_cParameter::ZSTD_c_srcSizeHint
2380        | ZSTD_cParameter::ZSTD_c_stableInBuffer
2381        | ZSTD_cParameter::ZSTD_c_stableOutBuffer
2382        | ZSTD_cParameter::ZSTD_c_blockDelimiters
2383        | ZSTD_cParameter::ZSTD_c_validateSequences
2384        | ZSTD_cParameter::ZSTD_c_splitAfterSequences
2385        | ZSTD_cParameter::ZSTD_c_blockSplitterLevel
2386        | ZSTD_cParameter::ZSTD_c_useRowMatchFinder
2387        | ZSTD_cParameter::ZSTD_c_deterministicRefPrefix
2388        | ZSTD_cParameter::ZSTD_c_prefetchCDictTables
2389        | ZSTD_cParameter::ZSTD_c_enableSeqProducerFallback
2390        | ZSTD_cParameter::ZSTD_c_maxBlockSize
2391        | ZSTD_cParameter::ZSTD_c_repcodeResolution => {
2392            ZSTD_CCtxParams_setParameter(&mut (*cctx).requestedParams, param, value)
2393        }
2394
2395        _ => Error::parameter_unsupported.to_error_code(),
2396    }
2397}
2398#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtxParams_setParameter))]
2399pub unsafe extern "C" fn ZSTD_CCtxParams_setParameter(
2400    CCtxParams: *mut ZSTD_CCtx_params,
2401    param: ZSTD_cParameter,
2402    mut value: core::ffi::c_int,
2403) -> size_t {
2404    match param.0 {
2405        10 => {
2406            let Ok(format) = Format::try_from(value) else {
2407                return Error::parameter_outOfBound.to_error_code();
2408            };
2409
2410            (*CCtxParams).format = format;
2411            (*CCtxParams).format as size_t
2412        }
2413        100 => {
2414            let err_code = ZSTD_cParam_clampBounds(param, &mut value);
2415            if ERR_isError(err_code) {
2416                return err_code;
2417            }
2418            if value == 0 {
2419                (*CCtxParams).compressionLevel = ZSTD_CLEVEL_DEFAULT;
2420            } else {
2421                (*CCtxParams).compressionLevel = value;
2422            }
2423            if (*CCtxParams).compressionLevel >= 0 {
2424                return (*CCtxParams).compressionLevel as size_t;
2425            }
2426            0
2427        }
2428        101 => {
2429            if value != 0 && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_windowLog, value) == 0
2430            {
2431                return Error::parameter_outOfBound.to_error_code();
2432            }
2433            (*CCtxParams).cParams.windowLog = value as u32;
2434            (*CCtxParams).cParams.windowLog as size_t
2435        }
2436        102 => {
2437            if value != 0 && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_hashLog, value) == 0 {
2438                return Error::parameter_outOfBound.to_error_code();
2439            }
2440            (*CCtxParams).cParams.hashLog = value as u32;
2441            (*CCtxParams).cParams.hashLog as size_t
2442        }
2443        103 => {
2444            if value != 0 && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_chainLog, value) == 0
2445            {
2446                return Error::parameter_outOfBound.to_error_code();
2447            }
2448            (*CCtxParams).cParams.chainLog = value as u32;
2449            (*CCtxParams).cParams.chainLog as size_t
2450        }
2451        104 => {
2452            if value != 0 && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_searchLog, value) == 0
2453            {
2454                return Error::parameter_outOfBound.to_error_code();
2455            }
2456            (*CCtxParams).cParams.searchLog = value as u32;
2457            value as size_t
2458        }
2459        105 => {
2460            if value != 0 && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_minMatch, value) == 0
2461            {
2462                return Error::parameter_outOfBound.to_error_code();
2463            }
2464            (*CCtxParams).cParams.minMatch = value as u32;
2465            (*CCtxParams).cParams.minMatch as size_t
2466        }
2467        106 => {
2468            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_targetLength, value) == 0 {
2469                return Error::parameter_outOfBound.to_error_code();
2470            }
2471            (*CCtxParams).cParams.targetLength = value as u32;
2472            (*CCtxParams).cParams.targetLength as size_t
2473        }
2474        107 => {
2475            if value != 0 && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_strategy, value) == 0
2476            {
2477                return Error::parameter_outOfBound.to_error_code();
2478            }
2479            (*CCtxParams).cParams.strategy = value as ZSTD_strategy;
2480            (*CCtxParams).cParams.strategy as size_t
2481        }
2482        200 => {
2483            (*CCtxParams).fParams.contentSizeFlag = (value != 0) as core::ffi::c_int;
2484            (*CCtxParams).fParams.contentSizeFlag as size_t
2485        }
2486        201 => {
2487            (*CCtxParams).fParams.checksumFlag = (value != 0) as core::ffi::c_int;
2488            (*CCtxParams).fParams.checksumFlag as size_t
2489        }
2490        202 => {
2491            (*CCtxParams).fParams.noDictIDFlag = (value == 0) as core::ffi::c_int;
2492            ((*CCtxParams).fParams.noDictIDFlag == 0) as core::ffi::c_int as size_t
2493        }
2494        1000 => {
2495            (*CCtxParams).forceWindow = (value != 0) as core::ffi::c_int;
2496            (*CCtxParams).forceWindow as size_t
2497        }
2498        1001 => {
2499            let Ok(pref) = ZSTD_dictAttachPref_e::try_from(value) else {
2500                return Error::parameter_outOfBound.to_error_code();
2501            };
2502            (*CCtxParams).attachDictPref = pref;
2503            (*CCtxParams).attachDictPref.0 as size_t
2504        }
2505        1002 => {
2506            let Ok(lcm) = ParamSwitch::try_from(value) else {
2507                return Error::parameter_outOfBound.to_error_code();
2508            };
2509            (*CCtxParams).literalCompressionMode = lcm;
2510            (*CCtxParams).literalCompressionMode as size_t
2511        }
2512        400 => {
2513            let err_code_0 = ZSTD_cParam_clampBounds(param, &mut value);
2514            if ERR_isError(err_code_0) {
2515                return err_code_0;
2516            }
2517            (*CCtxParams).nbWorkers = value;
2518            (*CCtxParams).nbWorkers as size_t
2519        }
2520        401 => {
2521            if value != 0 && value < ZSTDMT_JOBSIZE_MIN {
2522                value = ZSTDMT_JOBSIZE_MIN;
2523            }
2524            let err_code_1 = ZSTD_cParam_clampBounds(param, &mut value);
2525            if ERR_isError(err_code_1) {
2526                return err_code_1;
2527            }
2528            (*CCtxParams).jobSize = value as size_t;
2529            (*CCtxParams).jobSize
2530        }
2531        402 => {
2532            let err_code_2 =
2533                ZSTD_cParam_clampBounds(ZSTD_cParameter::ZSTD_c_overlapLog, &mut value);
2534            if ERR_isError(err_code_2) {
2535                return err_code_2;
2536            }
2537            (*CCtxParams).overlapLog = value;
2538            (*CCtxParams).overlapLog as size_t
2539        }
2540        500 => {
2541            let err_code_3 =
2542                ZSTD_cParam_clampBounds(ZSTD_cParameter::ZSTD_c_overlapLog, &mut value);
2543            if ERR_isError(err_code_3) {
2544                return err_code_3;
2545            }
2546            (*CCtxParams).rsyncable = value;
2547            (*CCtxParams).rsyncable as size_t
2548        }
2549        1005 => {
2550            (*CCtxParams).enableDedicatedDictSearch = (value != 0) as core::ffi::c_int;
2551            (*CCtxParams).enableDedicatedDictSearch as size_t
2552        }
2553        160 => {
2554            let Ok(value) = ZSTD_ParamSwitch_e::try_from(value) else {
2555                return Error::parameter_outOfBound.to_error_code();
2556            };
2557            (*CCtxParams).ldmParams.enableLdm = value as ZSTD_ParamSwitch_e;
2558            (*CCtxParams).ldmParams.enableLdm as size_t
2559        }
2560        161 => {
2561            if value != 0
2562                && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_ldmHashLog, value) == 0
2563            {
2564                return Error::parameter_outOfBound.to_error_code();
2565            }
2566            (*CCtxParams).ldmParams.hashLog = value as u32;
2567            (*CCtxParams).ldmParams.hashLog as size_t
2568        }
2569        162 => {
2570            if value != 0
2571                && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_ldmMinMatch, value) == 0
2572            {
2573                return Error::parameter_outOfBound.to_error_code();
2574            }
2575            (*CCtxParams).ldmParams.minMatchLength = value as u32;
2576            (*CCtxParams).ldmParams.minMatchLength as size_t
2577        }
2578        163 => {
2579            if value != 0
2580                && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_ldmBucketSizeLog, value) == 0
2581            {
2582                return Error::parameter_outOfBound.to_error_code();
2583            }
2584            (*CCtxParams).ldmParams.bucketSizeLog = value as u32;
2585            (*CCtxParams).ldmParams.bucketSizeLog as size_t
2586        }
2587        164 => {
2588            if value != 0
2589                && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_ldmHashRateLog, value) == 0
2590            {
2591                return Error::parameter_outOfBound.to_error_code();
2592            }
2593            (*CCtxParams).ldmParams.hashRateLog = value as u32;
2594            (*CCtxParams).ldmParams.hashRateLog as size_t
2595        }
2596        130 => {
2597            if value != 0 {
2598                value = if value > 1340 { value } else { 1340 };
2599                if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_targetCBlockSize, value) == 0 {
2600                    return Error::parameter_outOfBound.to_error_code();
2601                }
2602            }
2603            (*CCtxParams).targetCBlockSize = value as u32 as size_t;
2604            (*CCtxParams).targetCBlockSize
2605        }
2606        1004 => {
2607            if value != 0
2608                && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam7, value) == 0
2609            {
2610                return Error::parameter_outOfBound.to_error_code();
2611            }
2612            (*CCtxParams).srcSizeHint = value;
2613            (*CCtxParams).srcSizeHint as size_t
2614        }
2615        1006 => {
2616            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam9, value) == 0 {
2617                return Error::parameter_outOfBound.to_error_code();
2618            }
2619            (*CCtxParams).inBufferMode = value as ZSTD_bufferMode_e;
2620            (*CCtxParams).inBufferMode as size_t
2621        }
2622        1007 => {
2623            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam10, value) == 0 {
2624                return Error::parameter_outOfBound.to_error_code();
2625            }
2626            (*CCtxParams).outBufferMode = value as ZSTD_bufferMode_e;
2627            (*CCtxParams).outBufferMode as size_t
2628        }
2629        1008 => {
2630            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam11, value) == 0 {
2631                return Error::parameter_outOfBound.to_error_code();
2632            }
2633            (*CCtxParams).blockDelimiters = value as ZSTD_SequenceFormat_e;
2634            (*CCtxParams).blockDelimiters as size_t
2635        }
2636        1009 => {
2637            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam12, value) == 0 {
2638                return Error::parameter_outOfBound.to_error_code();
2639            }
2640            (*CCtxParams).validateSequences = value;
2641            (*CCtxParams).validateSequences as size_t
2642        }
2643        1010 => {
2644            let Ok(value) = ZSTD_ParamSwitch_e::try_from(value) else {
2645                return Error::parameter_outOfBound.to_error_code();
2646            };
2647            (*CCtxParams).postBlockSplitter = value as ZSTD_ParamSwitch_e;
2648            (*CCtxParams).postBlockSplitter as size_t
2649        }
2650        1017 => {
2651            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam20, value) == 0 {
2652                return Error::parameter_outOfBound.to_error_code();
2653            }
2654            (*CCtxParams).preBlockSplitter_level = value;
2655            (*CCtxParams).preBlockSplitter_level as size_t
2656        }
2657        1011 => {
2658            let Ok(value) = ZSTD_ParamSwitch_e::try_from(value) else {
2659                return Error::parameter_outOfBound.to_error_code();
2660            };
2661            (*CCtxParams).useRowMatchFinder = value as ZSTD_ParamSwitch_e;
2662            (*CCtxParams).useRowMatchFinder as size_t
2663        }
2664        1012 => {
2665            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam15, value) == 0 {
2666                return Error::parameter_outOfBound.to_error_code();
2667            }
2668            (*CCtxParams).deterministicRefPrefix = (value != 0) as core::ffi::c_int;
2669            (*CCtxParams).deterministicRefPrefix as size_t
2670        }
2671        1013 => {
2672            let Ok(value) = ZSTD_ParamSwitch_e::try_from(value) else {
2673                return Error::parameter_outOfBound.to_error_code();
2674            };
2675            (*CCtxParams).prefetchCDictTables = value as ZSTD_ParamSwitch_e;
2676            (*CCtxParams).prefetchCDictTables as size_t
2677        }
2678        1014 => {
2679            if ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam17, value) == 0 {
2680                return Error::parameter_outOfBound.to_error_code();
2681            }
2682            (*CCtxParams).enableMatchFinderFallback = value;
2683            (*CCtxParams).enableMatchFinderFallback as size_t
2684        }
2685        1015 => {
2686            if value != 0
2687                && ZSTD_cParam_withinBounds(ZSTD_cParameter::ZSTD_c_experimentalParam18, value) == 0
2688            {
2689                return Error::parameter_outOfBound.to_error_code();
2690            }
2691            (*CCtxParams).maxBlockSize = value as size_t;
2692            (*CCtxParams).maxBlockSize
2693        }
2694        1016 => {
2695            let Ok(value) = ZSTD_ParamSwitch_e::try_from(value) else {
2696                return Error::parameter_outOfBound.to_error_code();
2697            };
2698            (*CCtxParams).searchForExternalRepcodes = value;
2699            (*CCtxParams).searchForExternalRepcodes as size_t
2700        }
2701        _ => Error::parameter_unsupported.to_error_code(),
2702    }
2703}
2704#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_getParameter))]
2705pub unsafe extern "C" fn ZSTD_CCtx_getParameter(
2706    cctx: *const ZSTD_CCtx,
2707    param: ZSTD_cParameter,
2708    value: *mut core::ffi::c_int,
2709) -> size_t {
2710    ZSTD_CCtxParams_getParameter(&(*cctx).requestedParams, param, value)
2711}
2712#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtxParams_getParameter))]
2713pub unsafe extern "C" fn ZSTD_CCtxParams_getParameter(
2714    CCtxParams: *const ZSTD_CCtx_params,
2715    param: ZSTD_cParameter,
2716    value: *mut core::ffi::c_int,
2717) -> size_t {
2718    match param.0 {
2719        10 => {
2720            *value = (*CCtxParams).format as core::ffi::c_int;
2721        }
2722        100 => {
2723            *value = (*CCtxParams).compressionLevel;
2724        }
2725        101 => {
2726            *value = (*CCtxParams).cParams.windowLog as core::ffi::c_int;
2727        }
2728        102 => {
2729            *value = (*CCtxParams).cParams.hashLog as core::ffi::c_int;
2730        }
2731        103 => {
2732            *value = (*CCtxParams).cParams.chainLog as core::ffi::c_int;
2733        }
2734        104 => {
2735            *value = (*CCtxParams).cParams.searchLog as core::ffi::c_int;
2736        }
2737        105 => {
2738            *value = (*CCtxParams).cParams.minMatch as core::ffi::c_int;
2739        }
2740        106 => {
2741            *value = (*CCtxParams).cParams.targetLength as core::ffi::c_int;
2742        }
2743        107 => {
2744            *value = (*CCtxParams).cParams.strategy as core::ffi::c_int;
2745        }
2746        200 => {
2747            *value = (*CCtxParams).fParams.contentSizeFlag;
2748        }
2749        201 => {
2750            *value = (*CCtxParams).fParams.checksumFlag;
2751        }
2752        202 => {
2753            *value = ((*CCtxParams).fParams.noDictIDFlag == 0) as core::ffi::c_int;
2754        }
2755        1000 => {
2756            *value = (*CCtxParams).forceWindow;
2757        }
2758        1001 => {
2759            *value = (*CCtxParams).attachDictPref.0 as core::ffi::c_int;
2760        }
2761        1002 => {
2762            *value = (*CCtxParams).literalCompressionMode as core::ffi::c_int;
2763        }
2764        400 => {
2765            *value = (*CCtxParams).nbWorkers;
2766        }
2767        401 => {
2768            *value = (*CCtxParams).jobSize as core::ffi::c_int;
2769        }
2770        402 => {
2771            *value = (*CCtxParams).overlapLog;
2772        }
2773        500 => {
2774            *value = (*CCtxParams).rsyncable;
2775        }
2776        1005 => {
2777            *value = (*CCtxParams).enableDedicatedDictSearch;
2778        }
2779        160 => {
2780            *value = (*CCtxParams).ldmParams.enableLdm as core::ffi::c_int;
2781        }
2782        161 => {
2783            *value = (*CCtxParams).ldmParams.hashLog as core::ffi::c_int;
2784        }
2785        162 => {
2786            *value = (*CCtxParams).ldmParams.minMatchLength as core::ffi::c_int;
2787        }
2788        163 => {
2789            *value = (*CCtxParams).ldmParams.bucketSizeLog as core::ffi::c_int;
2790        }
2791        164 => {
2792            *value = (*CCtxParams).ldmParams.hashRateLog as core::ffi::c_int;
2793        }
2794        130 => {
2795            *value = (*CCtxParams).targetCBlockSize as core::ffi::c_int;
2796        }
2797        1004 => {
2798            *value = (*CCtxParams).srcSizeHint;
2799        }
2800        1006 => {
2801            *value = (*CCtxParams).inBufferMode as core::ffi::c_int;
2802        }
2803        1007 => {
2804            *value = (*CCtxParams).outBufferMode as core::ffi::c_int;
2805        }
2806        1008 => {
2807            *value = (*CCtxParams).blockDelimiters as core::ffi::c_int;
2808        }
2809        1009 => {
2810            *value = (*CCtxParams).validateSequences;
2811        }
2812        1010 => {
2813            *value = (*CCtxParams).postBlockSplitter as core::ffi::c_int;
2814        }
2815        1017 => {
2816            *value = (*CCtxParams).preBlockSplitter_level;
2817        }
2818        1011 => {
2819            *value = (*CCtxParams).useRowMatchFinder as core::ffi::c_int;
2820        }
2821        1012 => {
2822            *value = (*CCtxParams).deterministicRefPrefix;
2823        }
2824        1013 => {
2825            *value = (*CCtxParams).prefetchCDictTables as core::ffi::c_int;
2826        }
2827        1014 => {
2828            *value = (*CCtxParams).enableMatchFinderFallback;
2829        }
2830        1015 => {
2831            *value = (*CCtxParams).maxBlockSize as core::ffi::c_int;
2832        }
2833        1016 => {
2834            *value = (*CCtxParams).searchForExternalRepcodes as core::ffi::c_int;
2835        }
2836        _ => return Error::parameter_unsupported.to_error_code(),
2837    }
2838    0
2839}
2840#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_setParametersUsingCCtxParams))]
2841pub unsafe extern "C" fn ZSTD_CCtx_setParametersUsingCCtxParams(
2842    cctx: *mut ZSTD_CCtx,
2843    params: *const ZSTD_CCtx_params,
2844) -> size_t {
2845    if (*cctx).streamStage as core::ffi::c_uint
2846        != zcss_init as core::ffi::c_int as core::ffi::c_uint
2847    {
2848        return Error::stage_wrong.to_error_code();
2849    }
2850    if !((*cctx).cdict).is_null() {
2851        return Error::stage_wrong.to_error_code();
2852    }
2853    (*cctx).requestedParams = *params;
2854    0
2855}
2856#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_setCParams))]
2857pub unsafe extern "C" fn ZSTD_CCtx_setCParams(
2858    cctx: *mut ZSTD_CCtx,
2859    cparams: ZSTD_compressionParameters,
2860) -> size_t {
2861    let err_code = ZSTD_checkCParams(cparams);
2862    if ERR_isError(err_code) {
2863        return err_code;
2864    }
2865    let err_code_0 = ZSTD_CCtx_setParameter(
2866        cctx,
2867        ZSTD_cParameter::ZSTD_c_windowLog,
2868        cparams.windowLog as core::ffi::c_int,
2869    );
2870    if ERR_isError(err_code_0) {
2871        return err_code_0;
2872    }
2873    let err_code_1 = ZSTD_CCtx_setParameter(
2874        cctx,
2875        ZSTD_cParameter::ZSTD_c_chainLog,
2876        cparams.chainLog as core::ffi::c_int,
2877    );
2878    if ERR_isError(err_code_1) {
2879        return err_code_1;
2880    }
2881    let err_code_2 = ZSTD_CCtx_setParameter(
2882        cctx,
2883        ZSTD_cParameter::ZSTD_c_hashLog,
2884        cparams.hashLog as core::ffi::c_int,
2885    );
2886    if ERR_isError(err_code_2) {
2887        return err_code_2;
2888    }
2889    let err_code_3 = ZSTD_CCtx_setParameter(
2890        cctx,
2891        ZSTD_cParameter::ZSTD_c_searchLog,
2892        cparams.searchLog as core::ffi::c_int,
2893    );
2894    if ERR_isError(err_code_3) {
2895        return err_code_3;
2896    }
2897    let err_code_4 = ZSTD_CCtx_setParameter(
2898        cctx,
2899        ZSTD_cParameter::ZSTD_c_minMatch,
2900        cparams.minMatch as core::ffi::c_int,
2901    );
2902    if ERR_isError(err_code_4) {
2903        return err_code_4;
2904    }
2905    let err_code_5 = ZSTD_CCtx_setParameter(
2906        cctx,
2907        ZSTD_cParameter::ZSTD_c_targetLength,
2908        cparams.targetLength as core::ffi::c_int,
2909    );
2910    if ERR_isError(err_code_5) {
2911        return err_code_5;
2912    }
2913    let err_code_6 = ZSTD_CCtx_setParameter(
2914        cctx,
2915        ZSTD_cParameter::ZSTD_c_strategy,
2916        cparams.strategy as core::ffi::c_int,
2917    );
2918    if ERR_isError(err_code_6) {
2919        return err_code_6;
2920    }
2921    0
2922}
2923#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_setFParams))]
2924pub unsafe extern "C" fn ZSTD_CCtx_setFParams(
2925    cctx: *mut ZSTD_CCtx,
2926    fparams: ZSTD_frameParameters,
2927) -> size_t {
2928    let err_code = ZSTD_CCtx_setParameter(
2929        cctx,
2930        ZSTD_cParameter::ZSTD_c_contentSizeFlag,
2931        (fparams.contentSizeFlag != 0) as core::ffi::c_int,
2932    );
2933    if ERR_isError(err_code) {
2934        return err_code;
2935    }
2936    let err_code_0 = ZSTD_CCtx_setParameter(
2937        cctx,
2938        ZSTD_cParameter::ZSTD_c_checksumFlag,
2939        (fparams.checksumFlag != 0) as core::ffi::c_int,
2940    );
2941    if ERR_isError(err_code_0) {
2942        return err_code_0;
2943    }
2944    let err_code_1 = ZSTD_CCtx_setParameter(
2945        cctx,
2946        ZSTD_cParameter::ZSTD_c_dictIDFlag,
2947        (fparams.noDictIDFlag == 0) as core::ffi::c_int,
2948    );
2949    if ERR_isError(err_code_1) {
2950        return err_code_1;
2951    }
2952    0
2953}
2954#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_setParams))]
2955pub unsafe extern "C" fn ZSTD_CCtx_setParams(
2956    cctx: *mut ZSTD_CCtx,
2957    params: ZSTD_parameters,
2958) -> size_t {
2959    let err_code = ZSTD_checkCParams(params.cParams);
2960    if ERR_isError(err_code) {
2961        return err_code;
2962    }
2963    let err_code_0 = ZSTD_CCtx_setFParams(cctx, params.fParams);
2964    if ERR_isError(err_code_0) {
2965        return err_code_0;
2966    }
2967    let err_code_1 = ZSTD_CCtx_setCParams(cctx, params.cParams);
2968    if ERR_isError(err_code_1) {
2969        return err_code_1;
2970    }
2971    0
2972}
2973#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_setPledgedSrcSize))]
2974pub unsafe extern "C" fn ZSTD_CCtx_setPledgedSrcSize(
2975    cctx: *mut ZSTD_CCtx,
2976    pledgedSrcSize: core::ffi::c_ulonglong,
2977) -> size_t {
2978    if (*cctx).streamStage as core::ffi::c_uint
2979        != zcss_init as core::ffi::c_int as core::ffi::c_uint
2980    {
2981        return Error::stage_wrong.to_error_code();
2982    }
2983    (*cctx).pledgedSrcSizePlusOne = pledgedSrcSize.wrapping_add(1);
2984    0
2985}
2986unsafe fn ZSTD_initLocalDict(cctx: *mut ZSTD_CCtx) -> size_t {
2987    let dl: *mut ZSTD_localDict = &mut (*cctx).localDict;
2988    if ((*dl).dict).is_null() {
2989        return 0;
2990    }
2991    if !((*dl).cdict).is_null() {
2992        return 0;
2993    }
2994    (*dl).cdict = ZSTD_createCDict_advanced2(
2995        (*dl).dict,
2996        (*dl).dictSize,
2997        ZSTD_dlm_byRef,
2998        (*dl).dictContentType,
2999        &(*cctx).requestedParams,
3000        (*cctx).customMem,
3001    );
3002    if ((*dl).cdict).is_null() {
3003        return Error::memory_allocation.to_error_code();
3004    }
3005    (*cctx).cdict = (*dl).cdict;
3006    0
3007}
3008#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_loadDictionary_advanced))]
3009pub unsafe extern "C" fn ZSTD_CCtx_loadDictionary_advanced(
3010    cctx: *mut ZSTD_CCtx,
3011    dict: *const core::ffi::c_void,
3012    dictSize: size_t,
3013    dictLoadMethod: ZSTD_dictLoadMethod_e,
3014    dictContentType: ZSTD_dictContentType_e,
3015) -> size_t {
3016    if (*cctx).streamStage as core::ffi::c_uint
3017        != zcss_init as core::ffi::c_int as core::ffi::c_uint
3018    {
3019        return Error::stage_wrong.to_error_code();
3020    }
3021    ZSTD_clearAllDicts(cctx);
3022    if dict.is_null() || dictSize == 0 {
3023        return 0;
3024    }
3025    if dictLoadMethod as core::ffi::c_uint
3026        == ZSTD_dlm_byRef as core::ffi::c_int as core::ffi::c_uint
3027    {
3028        (*cctx).localDict.dict = dict;
3029    } else {
3030        let mut dictBuffer = core::ptr::null_mut::<core::ffi::c_void>();
3031        if (*cctx).staticSize != 0 {
3032            return Error::memory_allocation.to_error_code();
3033        }
3034        dictBuffer = ZSTD_customMalloc(dictSize, (*cctx).customMem);
3035        if dictBuffer.is_null() {
3036            return Error::memory_allocation.to_error_code();
3037        }
3038        libc::memcpy(dictBuffer, dict, dictSize as libc::size_t);
3039        (*cctx).localDict.dictBuffer = dictBuffer;
3040        (*cctx).localDict.dict = dictBuffer;
3041    }
3042    (*cctx).localDict.dictSize = dictSize;
3043    (*cctx).localDict.dictContentType = dictContentType;
3044    0
3045}
3046#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_loadDictionary_byReference))]
3047pub unsafe extern "C" fn ZSTD_CCtx_loadDictionary_byReference(
3048    cctx: *mut ZSTD_CCtx,
3049    dict: *const core::ffi::c_void,
3050    dictSize: size_t,
3051) -> size_t {
3052    ZSTD_CCtx_loadDictionary_advanced(cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto)
3053}
3054#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_loadDictionary))]
3055pub unsafe extern "C" fn ZSTD_CCtx_loadDictionary(
3056    cctx: *mut ZSTD_CCtx,
3057    dict: *const core::ffi::c_void,
3058    dictSize: size_t,
3059) -> size_t {
3060    ZSTD_CCtx_loadDictionary_advanced(cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto)
3061}
3062#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_refCDict))]
3063pub unsafe extern "C" fn ZSTD_CCtx_refCDict(
3064    cctx: *mut ZSTD_CCtx,
3065    cdict: *const ZSTD_CDict,
3066) -> size_t {
3067    if (*cctx).streamStage as core::ffi::c_uint
3068        != zcss_init as core::ffi::c_int as core::ffi::c_uint
3069    {
3070        return Error::stage_wrong.to_error_code();
3071    }
3072    ZSTD_clearAllDicts(cctx);
3073    (*cctx).cdict = cdict;
3074    0
3075}
3076#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_refThreadPool))]
3077pub unsafe extern "C" fn ZSTD_CCtx_refThreadPool(
3078    cctx: *mut ZSTD_CCtx,
3079    pool: *mut ZSTD_threadPool,
3080) -> size_t {
3081    if (*cctx).streamStage as core::ffi::c_uint
3082        != zcss_init as core::ffi::c_int as core::ffi::c_uint
3083    {
3084        return Error::stage_wrong.to_error_code();
3085    }
3086    (*cctx).pool = pool;
3087    0
3088}
3089#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_refPrefix))]
3090pub unsafe extern "C" fn ZSTD_CCtx_refPrefix(
3091    cctx: *mut ZSTD_CCtx,
3092    prefix: *const core::ffi::c_void,
3093    prefixSize: size_t,
3094) -> size_t {
3095    ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent)
3096}
3097#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_refPrefix_advanced))]
3098pub unsafe extern "C" fn ZSTD_CCtx_refPrefix_advanced(
3099    cctx: *mut ZSTD_CCtx,
3100    prefix: *const core::ffi::c_void,
3101    prefixSize: size_t,
3102    dictContentType: ZSTD_dictContentType_e,
3103) -> size_t {
3104    if (*cctx).streamStage as core::ffi::c_uint
3105        != zcss_init as core::ffi::c_int as core::ffi::c_uint
3106    {
3107        return Error::stage_wrong.to_error_code();
3108    }
3109    ZSTD_clearAllDicts(cctx);
3110    if !prefix.is_null() && prefixSize > 0 {
3111        (*cctx).prefixDict.dict = prefix;
3112        (*cctx).prefixDict.dictSize = prefixSize;
3113        (*cctx).prefixDict.dictContentType = dictContentType;
3114    }
3115    0
3116}
3117#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtx_reset))]
3118pub unsafe extern "C" fn ZSTD_CCtx_reset(
3119    cctx: *mut ZSTD_CCtx,
3120    reset: ZSTD_ResetDirective,
3121) -> size_t {
3122    if matches!(
3123        reset,
3124        ZSTD_ResetDirective::ZSTD_reset_session_only
3125            | ZSTD_ResetDirective::ZSTD_reset_session_and_parameters
3126    ) {
3127        (*cctx).streamStage = zcss_init;
3128        (*cctx).pledgedSrcSizePlusOne = 0;
3129    }
3130
3131    if matches!(
3132        reset,
3133        ZSTD_ResetDirective::ZSTD_reset_parameters
3134            | ZSTD_ResetDirective::ZSTD_reset_session_and_parameters
3135    ) {
3136        if (*cctx).streamStage as core::ffi::c_uint
3137            != zcss_init as core::ffi::c_int as core::ffi::c_uint
3138        {
3139            return Error::stage_wrong.to_error_code();
3140        }
3141        ZSTD_clearAllDicts(cctx);
3142        return ZSTD_CCtxParams_reset(&mut (*cctx).requestedParams);
3143    }
3144
3145    0
3146}
3147#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_checkCParams))]
3148pub unsafe extern "C" fn ZSTD_checkCParams(cParams: ZSTD_compressionParameters) -> size_t {
3149    if ZSTD_cParam_withinBounds(
3150        ZSTD_cParameter::ZSTD_c_windowLog,
3151        cParams.windowLog as core::ffi::c_int,
3152    ) == 0
3153    {
3154        return Error::parameter_outOfBound.to_error_code();
3155    }
3156    if ZSTD_cParam_withinBounds(
3157        ZSTD_cParameter::ZSTD_c_chainLog,
3158        cParams.chainLog as core::ffi::c_int,
3159    ) == 0
3160    {
3161        return Error::parameter_outOfBound.to_error_code();
3162    }
3163    if ZSTD_cParam_withinBounds(
3164        ZSTD_cParameter::ZSTD_c_hashLog,
3165        cParams.hashLog as core::ffi::c_int,
3166    ) == 0
3167    {
3168        return Error::parameter_outOfBound.to_error_code();
3169    }
3170    if ZSTD_cParam_withinBounds(
3171        ZSTD_cParameter::ZSTD_c_searchLog,
3172        cParams.searchLog as core::ffi::c_int,
3173    ) == 0
3174    {
3175        return Error::parameter_outOfBound.to_error_code();
3176    }
3177    if ZSTD_cParam_withinBounds(
3178        ZSTD_cParameter::ZSTD_c_minMatch,
3179        cParams.minMatch as core::ffi::c_int,
3180    ) == 0
3181    {
3182        return Error::parameter_outOfBound.to_error_code();
3183    }
3184    if ZSTD_cParam_withinBounds(
3185        ZSTD_cParameter::ZSTD_c_targetLength,
3186        cParams.targetLength as core::ffi::c_int,
3187    ) == 0
3188    {
3189        return Error::parameter_outOfBound.to_error_code();
3190    }
3191    if ZSTD_cParam_withinBounds(
3192        ZSTD_cParameter::ZSTD_c_strategy,
3193        cParams.strategy as core::ffi::c_int,
3194    ) == 0
3195    {
3196        return Error::parameter_outOfBound.to_error_code();
3197    }
3198    0
3199}
3200unsafe fn ZSTD_clampCParams(mut cParams: ZSTD_compressionParameters) -> ZSTD_compressionParameters {
3201    let bounds = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_windowLog);
3202    if (cParams.windowLog as core::ffi::c_int) < bounds.lowerBound {
3203        cParams.windowLog = bounds.lowerBound as core::ffi::c_uint;
3204    } else if cParams.windowLog as core::ffi::c_int > bounds.upperBound {
3205        cParams.windowLog = bounds.upperBound as core::ffi::c_uint;
3206    }
3207    let bounds_0 = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_chainLog);
3208    if (cParams.chainLog as core::ffi::c_int) < bounds_0.lowerBound {
3209        cParams.chainLog = bounds_0.lowerBound as core::ffi::c_uint;
3210    } else if cParams.chainLog as core::ffi::c_int > bounds_0.upperBound {
3211        cParams.chainLog = bounds_0.upperBound as core::ffi::c_uint;
3212    }
3213    let bounds_1 = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_hashLog);
3214    if (cParams.hashLog as core::ffi::c_int) < bounds_1.lowerBound {
3215        cParams.hashLog = bounds_1.lowerBound as core::ffi::c_uint;
3216    } else if cParams.hashLog as core::ffi::c_int > bounds_1.upperBound {
3217        cParams.hashLog = bounds_1.upperBound as core::ffi::c_uint;
3218    }
3219    let bounds_2 = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_searchLog);
3220    if (cParams.searchLog as core::ffi::c_int) < bounds_2.lowerBound {
3221        cParams.searchLog = bounds_2.lowerBound as core::ffi::c_uint;
3222    } else if cParams.searchLog as core::ffi::c_int > bounds_2.upperBound {
3223        cParams.searchLog = bounds_2.upperBound as core::ffi::c_uint;
3224    }
3225    let bounds_3 = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_minMatch);
3226    if (cParams.minMatch as core::ffi::c_int) < bounds_3.lowerBound {
3227        cParams.minMatch = bounds_3.lowerBound as core::ffi::c_uint;
3228    } else if cParams.minMatch as core::ffi::c_int > bounds_3.upperBound {
3229        cParams.minMatch = bounds_3.upperBound as core::ffi::c_uint;
3230    }
3231    let bounds_4 = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_targetLength);
3232    if (cParams.targetLength as core::ffi::c_int) < bounds_4.lowerBound {
3233        cParams.targetLength = bounds_4.lowerBound as core::ffi::c_uint;
3234    } else if cParams.targetLength as core::ffi::c_int > bounds_4.upperBound {
3235        cParams.targetLength = bounds_4.upperBound as core::ffi::c_uint;
3236    }
3237    let bounds_5 = ZSTD_cParam_getBounds(ZSTD_cParameter::ZSTD_c_strategy);
3238    if (cParams.strategy as core::ffi::c_int) < bounds_5.lowerBound {
3239        cParams.strategy = bounds_5.lowerBound as ZSTD_strategy;
3240    } else if cParams.strategy as core::ffi::c_int > bounds_5.upperBound {
3241        cParams.strategy = bounds_5.upperBound as ZSTD_strategy;
3242    }
3243    cParams
3244}
3245#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_cycleLog))]
3246pub unsafe extern "C" fn ZSTD_cycleLog(hashLog: u32, strat: ZSTD_strategy) -> u32 {
3247    let btScale = (strat >= ZSTD_btlazy2) as u32;
3248    hashLog.wrapping_sub(btScale)
3249}
3250unsafe fn ZSTD_dictAndWindowLog(windowLog: u32, srcSize: u64, dictSize: u64) -> u32 {
3251    let maxWindowSize = 1 << ZSTD_WINDOWLOG_MAX;
3252    if dictSize == 0 {
3253        return windowLog;
3254    }
3255    let windowSize = ((1) << windowLog) as u64;
3256    let dictAndWindowSize = dictSize.wrapping_add(windowSize);
3257    if windowSize >= dictSize.wrapping_add(srcSize) {
3258        windowLog
3259    } else if dictAndWindowSize >= maxWindowSize {
3260        (if ::core::mem::size_of::<size_t>() == 4 {
3261            ZSTD_WINDOWLOG_MAX_32
3262        } else {
3263            ZSTD_WINDOWLOG_MAX_64
3264        }) as u32
3265    } else {
3266        (ZSTD_highbit32((dictAndWindowSize as u32).wrapping_sub(1))).wrapping_add(1)
3267    }
3268}
3269unsafe fn ZSTD_adjustCParams_internal(
3270    mut cPar: ZSTD_compressionParameters,
3271    mut srcSize: core::ffi::c_ulonglong,
3272    mut dictSize: size_t,
3273    mode: ZSTD_CParamMode_e,
3274    mut useRowMatchFinder: ZSTD_ParamSwitch_e,
3275) -> ZSTD_compressionParameters {
3276    let minSrcSize = 513;
3277    let maxWindowResize = ((1)
3278        << ((if ::core::mem::size_of::<size_t>() == 4 {
3279            ZSTD_WINDOWLOG_MAX_32
3280        } else {
3281            ZSTD_WINDOWLOG_MAX_64
3282        }) - 1)) as u64;
3283    match mode as core::ffi::c_uint {
3284        2 => {
3285            if dictSize != 0 && srcSize == ZSTD_CONTENTSIZE_UNKNOWN {
3286                srcSize = minSrcSize as core::ffi::c_ulonglong;
3287            }
3288        }
3289        1 => {
3290            dictSize = 0;
3291        }
3292        3 | 0 | _ => {}
3293    }
3294    if srcSize <= maxWindowResize && dictSize as u64 <= maxWindowResize {
3295        let tSize = srcSize.wrapping_add(dictSize as core::ffi::c_ulonglong) as u32;
3296        static hashSizeMin: u32 = ((1) << ZSTD_HASHLOG_MIN) as u32;
3297        let srcLog = if tSize < hashSizeMin {
3298            ZSTD_HASHLOG_MIN as core::ffi::c_uint
3299        } else {
3300            (ZSTD_highbit32(tSize.wrapping_sub(1))).wrapping_add(1)
3301        };
3302        if cPar.windowLog > srcLog {
3303            cPar.windowLog = srcLog;
3304        }
3305    }
3306    if srcSize != ZSTD_CONTENTSIZE_UNKNOWN {
3307        let dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, srcSize, dictSize as u64);
3308        let cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
3309        if cPar.hashLog > dictAndWindowLog.wrapping_add(1) {
3310            cPar.hashLog = dictAndWindowLog.wrapping_add(1);
3311        }
3312        if cycleLog > dictAndWindowLog {
3313            cPar.chainLog = (cPar.chainLog).wrapping_sub(cycleLog.wrapping_sub(dictAndWindowLog));
3314        }
3315    }
3316    if cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN as core::ffi::c_uint {
3317        cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN as core::ffi::c_uint;
3318    }
3319    if mode as core::ffi::c_uint == ZSTD_cpm_createCDict as core::ffi::c_int as core::ffi::c_uint
3320        && ZSTD_CDictIndicesAreTagged(&cPar) != 0
3321    {
3322        let maxShortCacheHashLog = (32 - ZSTD_SHORT_CACHE_TAG_BITS) as u32;
3323        if cPar.hashLog > maxShortCacheHashLog {
3324            cPar.hashLog = maxShortCacheHashLog;
3325        }
3326        if cPar.chainLog > maxShortCacheHashLog {
3327            cPar.chainLog = maxShortCacheHashLog;
3328        }
3329    }
3330    if useRowMatchFinder == ZSTD_ParamSwitch_e::ZSTD_ps_auto {
3331        useRowMatchFinder = ZSTD_ParamSwitch_e::ZSTD_ps_enable;
3332    }
3333    if ZSTD_rowMatchFinderUsed(cPar.strategy, useRowMatchFinder) != 0 {
3334        let rowLog = if 4
3335            > (if cPar.searchLog < 6 {
3336                cPar.searchLog
3337            } else {
3338                6
3339            }) {
3340            4
3341        } else if cPar.searchLog < 6 {
3342            cPar.searchLog
3343        } else {
3344            6
3345        };
3346        let maxRowHashLog = (32 - ZSTD_ROW_HASH_TAG_BITS) as u32;
3347        let maxHashLog = maxRowHashLog.wrapping_add(rowLog);
3348        if cPar.hashLog > maxHashLog {
3349            cPar.hashLog = maxHashLog;
3350        }
3351    }
3352    cPar
3353}
3354#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_adjustCParams))]
3355pub unsafe extern "C" fn ZSTD_adjustCParams(
3356    mut cPar: ZSTD_compressionParameters,
3357    mut srcSize: core::ffi::c_ulonglong,
3358    dictSize: size_t,
3359) -> ZSTD_compressionParameters {
3360    cPar = ZSTD_clampCParams(cPar);
3361    if srcSize == 0 {
3362        srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
3363    }
3364    ZSTD_adjustCParams_internal(
3365        cPar,
3366        srcSize,
3367        dictSize,
3368        ZSTD_cpm_unknown,
3369        ZSTD_ParamSwitch_e::ZSTD_ps_auto,
3370    )
3371}
3372unsafe fn ZSTD_overrideCParams(
3373    cParams: *mut ZSTD_compressionParameters,
3374    overrides: *const ZSTD_compressionParameters,
3375) {
3376    if (*overrides).windowLog != 0 {
3377        (*cParams).windowLog = (*overrides).windowLog;
3378    }
3379    if (*overrides).hashLog != 0 {
3380        (*cParams).hashLog = (*overrides).hashLog;
3381    }
3382    if (*overrides).chainLog != 0 {
3383        (*cParams).chainLog = (*overrides).chainLog;
3384    }
3385    if (*overrides).searchLog != 0 {
3386        (*cParams).searchLog = (*overrides).searchLog;
3387    }
3388    if (*overrides).minMatch != 0 {
3389        (*cParams).minMatch = (*overrides).minMatch;
3390    }
3391    if (*overrides).targetLength != 0 {
3392        (*cParams).targetLength = (*overrides).targetLength;
3393    }
3394    if (*overrides).strategy as u64 != 0 {
3395        (*cParams).strategy = (*overrides).strategy;
3396    }
3397}
3398#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getCParamsFromCCtxParams))]
3399pub unsafe extern "C" fn ZSTD_getCParamsFromCCtxParams(
3400    CCtxParams: *const ZSTD_CCtx_params,
3401    mut srcSizeHint: u64,
3402    dictSize: size_t,
3403    mode: ZSTD_CParamMode_e,
3404) -> ZSTD_compressionParameters {
3405    let mut cParams = ZSTD_compressionParameters {
3406        windowLog: 0,
3407        chainLog: 0,
3408        hashLog: 0,
3409        searchLog: 0,
3410        minMatch: 0,
3411        targetLength: 0,
3412        strategy: 0,
3413    };
3414    if srcSizeHint as core::ffi::c_ulonglong == ZSTD_CONTENTSIZE_UNKNOWN
3415        && (*CCtxParams).srcSizeHint > 0
3416    {
3417        srcSizeHint = (*CCtxParams).srcSizeHint as u64;
3418    }
3419    cParams = ZSTD_getCParams_internal(
3420        (*CCtxParams).compressionLevel,
3421        srcSizeHint as core::ffi::c_ulonglong,
3422        dictSize,
3423        mode,
3424    );
3425    if (*CCtxParams).ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
3426        cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG as core::ffi::c_uint;
3427    }
3428    ZSTD_overrideCParams(&mut cParams, &(*CCtxParams).cParams);
3429    ZSTD_adjustCParams_internal(
3430        cParams,
3431        srcSizeHint as core::ffi::c_ulonglong,
3432        dictSize,
3433        mode,
3434        (*CCtxParams).useRowMatchFinder,
3435    )
3436}
3437unsafe fn ZSTD_sizeof_matchState(
3438    cParams: *const ZSTD_compressionParameters,
3439    useRowMatchFinder: ZSTD_ParamSwitch_e,
3440    enableDedicatedDictSearch: core::ffi::c_int,
3441    forCCtx: u32,
3442) -> size_t {
3443    let chainSize = if ZSTD_allocateChainTable(
3444        (*cParams).strategy,
3445        useRowMatchFinder,
3446        (enableDedicatedDictSearch != 0 && forCCtx == 0) as core::ffi::c_int as u32,
3447    ) != 0
3448    {
3449        (1 as size_t) << (*cParams).chainLog
3450    } else {
3451        0 as size_t
3452    };
3453    let hSize = (1 as size_t) << (*cParams).hashLog;
3454    let hashLog3 = if forCCtx != 0 && (*cParams).minMatch == 3 {
3455        if (17) < (*cParams).windowLog {
3456            17
3457        } else {
3458            (*cParams).windowLog
3459        }
3460    } else {
3461        0
3462    };
3463    let h3Size = if hashLog3 != 0 {
3464        (1 as size_t) << hashLog3
3465    } else {
3466        0 as size_t
3467    };
3468    let tableSpace = chainSize
3469        .wrapping_mul(::core::mem::size_of::<u32>())
3470        .wrapping_add(hSize.wrapping_mul(::core::mem::size_of::<u32>()))
3471        .wrapping_add(h3Size.wrapping_mul(::core::mem::size_of::<u32>()));
3472    let optPotentialSpace = (ZSTD_cwksp_aligned64_alloc_size(
3473        ((MaxML + 1) as size_t).wrapping_mul(::core::mem::size_of::<u32>()),
3474    ))
3475    .wrapping_add(ZSTD_cwksp_aligned64_alloc_size(
3476        ((MaxLL + 1) as size_t).wrapping_mul(::core::mem::size_of::<u32>()),
3477    ))
3478    .wrapping_add(ZSTD_cwksp_aligned64_alloc_size(
3479        ((MaxOff + 1) as size_t).wrapping_mul(::core::mem::size_of::<u32>()),
3480    ))
3481    .wrapping_add(ZSTD_cwksp_aligned64_alloc_size(
3482        (((1) << Litbits) as size_t).wrapping_mul(::core::mem::size_of::<u32>()),
3483    ))
3484    .wrapping_add(ZSTD_cwksp_aligned64_alloc_size(
3485        (ZSTD_OPT_SIZE as size_t).wrapping_mul(::core::mem::size_of::<ZSTD_match_t>()),
3486    ))
3487    .wrapping_add(ZSTD_cwksp_aligned64_alloc_size(
3488        (ZSTD_OPT_SIZE as size_t).wrapping_mul(::core::mem::size_of::<ZSTD_optimal_t>()),
3489    ));
3490    let lazyAdditionalSpace =
3491        if ZSTD_rowMatchFinderUsed((*cParams).strategy, useRowMatchFinder) != 0 {
3492            ZSTD_cwksp_aligned64_alloc_size(hSize)
3493        } else {
3494            0
3495        };
3496    let optSpace = if forCCtx != 0
3497        && (*cParams).strategy as core::ffi::c_uint
3498            >= ZSTD_btopt as core::ffi::c_int as core::ffi::c_uint
3499    {
3500        optPotentialSpace
3501    } else {
3502        0
3503    };
3504    let slackSpace = ZSTD_cwksp_slack_space_required();
3505    tableSpace
3506        .wrapping_add(optSpace)
3507        .wrapping_add(slackSpace)
3508        .wrapping_add(lazyAdditionalSpace)
3509}
3510unsafe fn ZSTD_maxNbSeq(
3511    blockSize: size_t,
3512    minMatch: core::ffi::c_uint,
3513    useSequenceProducer: core::ffi::c_int,
3514) -> size_t {
3515    let divider = (if minMatch == 3 || useSequenceProducer != 0 {
3516        3
3517    } else {
3518        4
3519    }) as u32;
3520    blockSize / divider as size_t
3521}
3522unsafe fn ZSTD_estimateCCtxSize_usingCCtxParams_internal(
3523    cParams: *const ZSTD_compressionParameters,
3524    ldmParams: *const ldmParams_t,
3525    isStatic: core::ffi::c_int,
3526    useRowMatchFinder: ZSTD_ParamSwitch_e,
3527    buffInSize: size_t,
3528    buffOutSize: size_t,
3529    pledgedSrcSize: u64,
3530    useSequenceProducer: core::ffi::c_int,
3531    maxBlockSize: size_t,
3532) -> size_t {
3533    let windowSize = (if 1
3534        > (if (1) << (*cParams).windowLog < pledgedSrcSize as core::ffi::c_ulonglong {
3535            (1) << (*cParams).windowLog
3536        } else {
3537            pledgedSrcSize as core::ffi::c_ulonglong
3538        }) {
3539        1
3540    } else if (1) << (*cParams).windowLog < pledgedSrcSize as core::ffi::c_ulonglong {
3541        (1) << (*cParams).windowLog
3542    } else {
3543        pledgedSrcSize as core::ffi::c_ulonglong
3544    }) as size_t;
3545    let blockSize = if ZSTD_resolveMaxBlockSize(maxBlockSize) < windowSize {
3546        ZSTD_resolveMaxBlockSize(maxBlockSize)
3547    } else {
3548        windowSize
3549    };
3550    let maxNbSeq = ZSTD_maxNbSeq(blockSize, (*cParams).minMatch, useSequenceProducer);
3551    let tokenSpace = (ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH.wrapping_add(blockSize)))
3552        .wrapping_add(ZSTD_cwksp_aligned64_alloc_size(
3553            maxNbSeq.wrapping_mul(::core::mem::size_of::<SeqDef>()),
3554        ))
3555        .wrapping_add(
3556            3 * ZSTD_cwksp_alloc_size(maxNbSeq.wrapping_mul(::core::mem::size_of::<u8>())),
3557        );
3558    let tmpWorkSpace = ZSTD_cwksp_alloc_size(
3559        if ((((8) << 10) + 512) as size_t).wrapping_add(
3560            (::core::mem::size_of::<core::ffi::c_uint>())
3561                .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
3562        ) > 8208
3563        {
3564            ((((8) << 10) + 512) as size_t).wrapping_add(
3565                (::core::mem::size_of::<core::ffi::c_uint>())
3566                    .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
3567            )
3568        } else {
3569            8208
3570        },
3571    );
3572    let blockStateSpace =
3573        2 * ZSTD_cwksp_alloc_size(::core::mem::size_of::<ZSTD_compressedBlockState_t>());
3574    let matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, 0, 1);
3575    let ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
3576    let maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
3577    let ldmSeqSpace = if (*ldmParams).enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
3578        ZSTD_cwksp_aligned64_alloc_size(maxNbLdmSeq.wrapping_mul(::core::mem::size_of::<rawSeq>()))
3579    } else {
3580        0
3581    };
3582    let bufferSpace =
3583        (ZSTD_cwksp_alloc_size(buffInSize)).wrapping_add(ZSTD_cwksp_alloc_size(buffOutSize));
3584    let cctxSpace = if isStatic != 0 {
3585        ZSTD_cwksp_alloc_size(::core::mem::size_of::<ZSTD_CCtx>())
3586    } else {
3587        0
3588    };
3589    let maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
3590    let externalSeqSpace = if useSequenceProducer != 0 {
3591        ZSTD_cwksp_aligned64_alloc_size(
3592            maxNbExternalSeq.wrapping_mul(::core::mem::size_of::<ZSTD_Sequence>()),
3593        )
3594    } else {
3595        0
3596    };
3597
3598    cctxSpace
3599        .wrapping_add(tmpWorkSpace)
3600        .wrapping_add(blockStateSpace)
3601        .wrapping_add(ldmSpace)
3602        .wrapping_add(ldmSeqSpace)
3603        .wrapping_add(matchStateSize)
3604        .wrapping_add(tokenSpace)
3605        .wrapping_add(bufferSpace)
3606        .wrapping_add(externalSeqSpace)
3607}
3608#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCCtxSize_usingCCtxParams))]
3609pub unsafe extern "C" fn ZSTD_estimateCCtxSize_usingCCtxParams(
3610    params: *const ZSTD_CCtx_params,
3611) -> size_t {
3612    let cParams =
3613        ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
3614    let useRowMatchFinder = ZSTD_resolveRowMatchFinderMode((*params).useRowMatchFinder, &cParams);
3615    if (*params).nbWorkers > 0 {
3616        return Error::GENERIC.to_error_code();
3617    }
3618    ZSTD_estimateCCtxSize_usingCCtxParams_internal(
3619        &cParams,
3620        &(*params).ldmParams,
3621        1,
3622        useRowMatchFinder,
3623        0,
3624        0,
3625        ZSTD_CONTENTSIZE_UNKNOWN,
3626        ZSTD_hasExtSeqProd(params),
3627        (*params).maxBlockSize,
3628    )
3629}
3630#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCCtxSize_usingCParams))]
3631pub unsafe extern "C" fn ZSTD_estimateCCtxSize_usingCParams(
3632    cParams: ZSTD_compressionParameters,
3633) -> size_t {
3634    let mut initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
3635    if ZSTD_rowMatchFinderSupported(cParams.strategy) != 0 {
3636        let mut noRowCCtxSize: size_t = 0;
3637        let mut rowCCtxSize: size_t = 0;
3638        initialParams.useRowMatchFinder = ZSTD_ParamSwitch_e::ZSTD_ps_disable;
3639        noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
3640        initialParams.useRowMatchFinder = ZSTD_ParamSwitch_e::ZSTD_ps_enable;
3641        rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
3642        if noRowCCtxSize > rowCCtxSize {
3643            noRowCCtxSize
3644        } else {
3645            rowCCtxSize
3646        }
3647    } else {
3648        ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams)
3649    }
3650}
3651static srcSizeTiers: [core::ffi::c_ulonglong; 4] = [
3652    16 * (1 << 10),
3653    128 * (1 << 10),
3654    256 * (1 << 10),
3655    ZSTD_CONTENTSIZE_UNKNOWN,
3656];
3657unsafe extern "C" fn ZSTD_estimateCCtxSize_internal(compressionLevel: core::ffi::c_int) -> size_t {
3658    let mut tier = 0;
3659    let mut largestSize = 0;
3660    while tier < 4 {
3661        let cParams = ZSTD_getCParams_internal(
3662            compressionLevel,
3663            srcSizeTiers[tier],
3664            0,
3665            ZSTD_cpm_noAttachDict,
3666        );
3667        largestSize = if ZSTD_estimateCCtxSize_usingCParams(cParams) > largestSize {
3668            ZSTD_estimateCCtxSize_usingCParams(cParams)
3669        } else {
3670            largestSize
3671        };
3672        tier += 1;
3673    }
3674    largestSize
3675}
3676#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCCtxSize))]
3677pub unsafe extern "C" fn ZSTD_estimateCCtxSize(compressionLevel: core::ffi::c_int) -> size_t {
3678    let mut level: core::ffi::c_int = 0;
3679    let mut memBudget = 0;
3680    level = if compressionLevel < 1 {
3681        compressionLevel
3682    } else {
3683        1
3684    };
3685    while level <= compressionLevel {
3686        let newMB = ZSTD_estimateCCtxSize_internal(level);
3687        if newMB > memBudget {
3688            memBudget = newMB;
3689        }
3690        level += 1;
3691    }
3692    memBudget
3693}
3694#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCStreamSize_usingCCtxParams))]
3695pub unsafe extern "C" fn ZSTD_estimateCStreamSize_usingCCtxParams(
3696    params: *const ZSTD_CCtx_params,
3697) -> size_t {
3698    if (*params).nbWorkers > 0 {
3699        return Error::GENERIC.to_error_code();
3700    }
3701    let cParams =
3702        ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
3703    let blockSize = if ZSTD_resolveMaxBlockSize((*params).maxBlockSize) < (1) << cParams.windowLog {
3704        ZSTD_resolveMaxBlockSize((*params).maxBlockSize)
3705    } else {
3706        (1) << cParams.windowLog
3707    };
3708    let inBuffSize = if (*params).inBufferMode as core::ffi::c_uint
3709        == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint
3710    {
3711        ((1 as size_t) << cParams.windowLog).wrapping_add(blockSize)
3712    } else {
3713        0
3714    };
3715    let outBuffSize = if (*params).outBufferMode as core::ffi::c_uint
3716        == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint
3717    {
3718        (ZSTD_compressBound(blockSize)).wrapping_add(1)
3719    } else {
3720        0
3721    };
3722    let useRowMatchFinder =
3723        ZSTD_resolveRowMatchFinderMode((*params).useRowMatchFinder, &(*params).cParams);
3724    ZSTD_estimateCCtxSize_usingCCtxParams_internal(
3725        &cParams,
3726        &(*params).ldmParams,
3727        1,
3728        useRowMatchFinder,
3729        inBuffSize,
3730        outBuffSize,
3731        ZSTD_CONTENTSIZE_UNKNOWN,
3732        ZSTD_hasExtSeqProd(params),
3733        (*params).maxBlockSize,
3734    )
3735}
3736#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCStreamSize_usingCParams))]
3737pub unsafe extern "C" fn ZSTD_estimateCStreamSize_usingCParams(
3738    cParams: ZSTD_compressionParameters,
3739) -> size_t {
3740    let mut initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
3741    if ZSTD_rowMatchFinderSupported(cParams.strategy) != 0 {
3742        let mut noRowCCtxSize: size_t = 0;
3743        let mut rowCCtxSize: size_t = 0;
3744        initialParams.useRowMatchFinder = ZSTD_ParamSwitch_e::ZSTD_ps_disable;
3745        noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
3746        initialParams.useRowMatchFinder = ZSTD_ParamSwitch_e::ZSTD_ps_enable;
3747        rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
3748        if noRowCCtxSize > rowCCtxSize {
3749            noRowCCtxSize
3750        } else {
3751            rowCCtxSize
3752        }
3753    } else {
3754        ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams)
3755    }
3756}
3757unsafe fn ZSTD_estimateCStreamSize_internal(compressionLevel: core::ffi::c_int) -> size_t {
3758    let cParams = ZSTD_getCParams_internal(
3759        compressionLevel,
3760        ZSTD_CONTENTSIZE_UNKNOWN,
3761        0,
3762        ZSTD_cpm_noAttachDict,
3763    );
3764    ZSTD_estimateCStreamSize_usingCParams(cParams)
3765}
3766#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCStreamSize))]
3767pub unsafe extern "C" fn ZSTD_estimateCStreamSize(compressionLevel: core::ffi::c_int) -> size_t {
3768    let mut level: core::ffi::c_int = 0;
3769    let mut memBudget = 0;
3770    level = if compressionLevel < 1 {
3771        compressionLevel
3772    } else {
3773        1
3774    };
3775    while level <= compressionLevel {
3776        let newMB = ZSTD_estimateCStreamSize_internal(level);
3777        if newMB > memBudget {
3778            memBudget = newMB;
3779        }
3780        level += 1;
3781    }
3782    memBudget
3783}
3784#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getFrameProgression))]
3785pub unsafe extern "C" fn ZSTD_getFrameProgression(cctx: *const ZSTD_CCtx) -> ZSTD_frameProgression {
3786    if (*cctx).appliedParams.nbWorkers > 0 {
3787        return ZSTDMT_getFrameProgression((*cctx).mtctx);
3788    }
3789    let mut fp = ZSTD_frameProgression {
3790        ingested: 0,
3791        consumed: 0,
3792        produced: 0,
3793        flushed: 0,
3794        currentJobID: 0,
3795        nbActiveWorkers: 0,
3796    };
3797    let buffered = if ((*cctx).inBuff).is_null() {
3798        0
3799    } else {
3800        ((*cctx).inBuffPos).wrapping_sub((*cctx).inToCompress)
3801    };
3802
3803    if buffered != 0 {
3804        assert!((*cctx).inBuffPos >= (*cctx).inToCompress)
3805    }
3806    assert!(buffered <= ZSTD_BLOCKSIZE_MAX as usize);
3807
3808    fp.ingested = ((*cctx).consumedSrcSize).wrapping_add(buffered as core::ffi::c_ulonglong);
3809    fp.consumed = (*cctx).consumedSrcSize;
3810    fp.produced = (*cctx).producedCSize;
3811    fp.flushed = (*cctx).producedCSize;
3812    fp.currentJobID = 0;
3813    fp.nbActiveWorkers = 0;
3814    fp
3815}
3816#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_toFlushNow))]
3817pub unsafe extern "C" fn ZSTD_toFlushNow(cctx: *mut ZSTD_CCtx) -> size_t {
3818    if (*cctx).appliedParams.nbWorkers > 0 {
3819        return ZSTDMT_toFlushNow((*cctx).mtctx);
3820    }
3821    0
3822}
3823unsafe fn ZSTD_assertEqualCParams(
3824    cParams1: ZSTD_compressionParameters,
3825    cParams2: ZSTD_compressionParameters,
3826) {
3827    assert_eq!(cParams1.windowLog, cParams2.windowLog);
3828    assert_eq!(cParams1.chainLog, cParams2.chainLog);
3829    assert_eq!(cParams1.hashLog, cParams2.hashLog);
3830    assert_eq!(cParams1.searchLog, cParams2.searchLog);
3831    assert_eq!(cParams1.minMatch, cParams2.minMatch);
3832    assert_eq!(cParams1.targetLength, cParams2.targetLength);
3833    assert_eq!(cParams1.strategy, cParams2.strategy);
3834}
3835pub unsafe fn ZSTD_reset_compressedBlockState(bs: *mut ZSTD_compressedBlockState_t) {
3836    let mut i: core::ffi::c_int = 0;
3837    i = 0;
3838    while i < ZSTD_REP_NUM {
3839        *((*bs).rep).as_mut_ptr().offset(i as isize) = *repStartValue.as_ptr().offset(i as isize);
3840        i += 1;
3841    }
3842    (*bs).entropy.huf.repeatMode = HUF_repeat_none;
3843    (*bs).entropy.fse.offcode_repeatMode = FSE_repeat_none;
3844    (*bs).entropy.fse.matchlength_repeatMode = FSE_repeat_none;
3845    (*bs).entropy.fse.litlength_repeatMode = FSE_repeat_none;
3846}
3847unsafe fn ZSTD_invalidateMatchState(ms: &mut ZSTD_MatchState_t) {
3848    ZSTD_window_clear(&mut ms.window);
3849    ms.nextToUpdate = ms.window.dictLimit;
3850    ms.loadedDictEnd = 0;
3851    ms.opt.litLengthSum = 0;
3852    ms.dictMatchState = core::ptr::null();
3853}
3854unsafe fn ZSTD_bitmix(mut val: u64, len: u64) -> u64 {
3855    val ^= val.rotate_right(49) ^ val.rotate_right(24);
3856    val = val.wrapping_mul(0x9fb21c651e98df25u64);
3857    val ^= (val >> 35).wrapping_add(len);
3858    val = val.wrapping_mul(0x9fb21c651e98df25u64);
3859    val ^ val >> 28
3860}
3861unsafe fn ZSTD_advanceHashSalt(ms: &mut ZSTD_MatchState_t) {
3862    ms.hashSalt = ZSTD_bitmix(ms.hashSalt, 8) ^ ZSTD_bitmix(ms.hashSaltEntropy as u64, 4);
3863}
3864unsafe fn ZSTD_reset_matchState(
3865    ms: &mut ZSTD_MatchState_t,
3866    ws: *mut ZSTD_cwksp,
3867    cParams: *const ZSTD_compressionParameters,
3868    useRowMatchFinder: ZSTD_ParamSwitch_e,
3869    crp: ZSTD_compResetPolicy_e,
3870    forceResetIndex: ZSTD_indexResetPolicy_e,
3871    forWho: ZSTD_resetTarget_e,
3872) -> size_t {
3873    let chainSize = if ZSTD_allocateChainTable(
3874        (*cParams).strategy,
3875        useRowMatchFinder,
3876        (ms.dedicatedDictSearch != 0
3877            && forWho as core::ffi::c_uint
3878                == ZSTD_resetTarget_CDict as core::ffi::c_int as core::ffi::c_uint)
3879            as core::ffi::c_int as u32,
3880    ) != 0
3881    {
3882        (1 as size_t) << (*cParams).chainLog
3883    } else {
3884        0 as size_t
3885    };
3886    let hSize = (1 as size_t) << (*cParams).hashLog;
3887    let hashLog3 = if forWho as core::ffi::c_uint
3888        == ZSTD_resetTarget_CCtx as core::ffi::c_int as core::ffi::c_uint
3889        && (*cParams).minMatch == 3
3890    {
3891        if (17) < (*cParams).windowLog {
3892            17
3893        } else {
3894            (*cParams).windowLog
3895        }
3896    } else {
3897        0
3898    };
3899    let h3Size = if hashLog3 != 0 {
3900        (1 as size_t) << hashLog3
3901    } else {
3902        0 as size_t
3903    };
3904    if forceResetIndex as core::ffi::c_uint
3905        == ZSTDirp_reset as core::ffi::c_int as core::ffi::c_uint
3906    {
3907        ZSTD_window_init(&mut ms.window);
3908        ZSTD_cwksp_mark_tables_dirty(ws);
3909    }
3910    ms.hashLog3 = hashLog3;
3911    ms.lazySkipping = 0;
3912    ZSTD_invalidateMatchState(ms);
3913    ZSTD_cwksp_clear_tables(ws);
3914    ms.hashTable =
3915        ZSTD_cwksp_reserve_table(ws, hSize.wrapping_mul(::core::mem::size_of::<u32>())) as *mut u32;
3916    ms.chainTable =
3917        ZSTD_cwksp_reserve_table(ws, chainSize.wrapping_mul(::core::mem::size_of::<u32>()))
3918            as *mut u32;
3919    ms.hashTable3 = ZSTD_cwksp_reserve_table(ws, h3Size.wrapping_mul(::core::mem::size_of::<u32>()))
3920        as *mut u32;
3921    if ZSTD_cwksp_reserve_failed(ws) != 0 {
3922        return Error::memory_allocation.to_error_code();
3923    }
3924    if crp as core::ffi::c_uint != ZSTDcrp_leaveDirty as core::ffi::c_int as core::ffi::c_uint {
3925        ZSTD_cwksp_clean_tables(ws);
3926    }
3927    if ZSTD_rowMatchFinderUsed((*cParams).strategy, useRowMatchFinder) != 0 {
3928        let tagTableSize = hSize;
3929        if forWho as core::ffi::c_uint
3930            == ZSTD_resetTarget_CCtx as core::ffi::c_int as core::ffi::c_uint
3931        {
3932            ms.tagTable = ZSTD_cwksp_reserve_aligned_init_once(ws, tagTableSize) as *mut u8;
3933            ZSTD_advanceHashSalt(ms);
3934        } else {
3935            ms.tagTable = ZSTD_cwksp_reserve_aligned64(ws, tagTableSize) as *mut u8;
3936            ptr::write_bytes(ms.tagTable, 0, tagTableSize);
3937            ms.hashSalt = 0;
3938        }
3939        let rowLog = if 4
3940            > (if (*cParams).searchLog < 6 {
3941                (*cParams).searchLog
3942            } else {
3943                6
3944            }) {
3945            4
3946        } else if (*cParams).searchLog < 6 {
3947            (*cParams).searchLog
3948        } else {
3949            6
3950        };
3951        ms.rowHashLog = ((*cParams).hashLog).wrapping_sub(rowLog);
3952    }
3953    if forWho as core::ffi::c_uint == ZSTD_resetTarget_CCtx as core::ffi::c_int as core::ffi::c_uint
3954        && (*cParams).strategy as core::ffi::c_uint
3955            >= ZSTD_btopt as core::ffi::c_int as core::ffi::c_uint
3956    {
3957        ms.opt.litFreq = ZSTD_cwksp_reserve_aligned64(
3958            ws,
3959            (((1) << Litbits) as size_t).wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>()),
3960        ) as *mut core::ffi::c_uint;
3961        ms.opt.litLengthFreq = ZSTD_cwksp_reserve_aligned64(
3962            ws,
3963            ((MaxLL + 1) as size_t).wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>()),
3964        ) as *mut core::ffi::c_uint;
3965        ms.opt.matchLengthFreq = ZSTD_cwksp_reserve_aligned64(
3966            ws,
3967            ((MaxML + 1) as size_t).wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>()),
3968        ) as *mut core::ffi::c_uint;
3969        ms.opt.offCodeFreq = ZSTD_cwksp_reserve_aligned64(
3970            ws,
3971            ((MaxOff + 1) as size_t).wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>()),
3972        ) as *mut core::ffi::c_uint;
3973        ms.opt.matchTable = ZSTD_cwksp_reserve_aligned64(
3974            ws,
3975            (ZSTD_OPT_SIZE as size_t).wrapping_mul(::core::mem::size_of::<ZSTD_match_t>()),
3976        ) as *mut ZSTD_match_t;
3977        ms.opt.priceTable = ZSTD_cwksp_reserve_aligned64(
3978            ws,
3979            (ZSTD_OPT_SIZE as size_t).wrapping_mul(::core::mem::size_of::<ZSTD_optimal_t>()),
3980        ) as *mut ZSTD_optimal_t;
3981    }
3982    ms.cParams = *cParams;
3983    if ZSTD_cwksp_reserve_failed(ws) != 0 {
3984        return Error::memory_allocation.to_error_code();
3985    }
3986    0
3987}
3988pub const ZSTD_INDEXOVERFLOW_MARGIN: core::ffi::c_int = 16 * ((1) << 20);
3989unsafe fn ZSTD_indexTooCloseToMax(w: ZSTD_window_t) -> core::ffi::c_int {
3990    ((w.nextSrc).wrapping_offset_from(w.base) as size_t
3991        > (if MEM_64bits() {
3992            (3500 as core::ffi::c_uint)
3993                .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
3994        } else {
3995            (2000 as core::ffi::c_uint)
3996                .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
3997        })
3998        .wrapping_sub(ZSTD_INDEXOVERFLOW_MARGIN as core::ffi::c_uint) as size_t)
3999        as core::ffi::c_int
4000}
4001unsafe fn ZSTD_dictTooBig(loadedDictSize: size_t) -> core::ffi::c_int {
4002    (loadedDictSize
4003        > (-(1 as core::ffi::c_int) as u32).wrapping_sub(if MEM_64bits() {
4004            (3500 as core::ffi::c_uint)
4005                .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
4006        } else {
4007            (2000 as core::ffi::c_uint)
4008                .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
4009        }) as size_t) as core::ffi::c_int
4010}
4011unsafe fn ZSTD_resetCCtx_internal(
4012    zc: *mut ZSTD_CCtx,
4013    mut params: *const ZSTD_CCtx_params,
4014    pledgedSrcSize: u64,
4015    loadedDictSize: size_t,
4016    crp: ZSTD_compResetPolicy_e,
4017    zbuff: ZSTD_buffered_policy_e,
4018) -> size_t {
4019    let ws: *mut ZSTD_cwksp = &mut (*zc).workspace;
4020    (*zc).isFirstBlock = 1;
4021    (*zc).appliedParams = *params;
4022    params = &mut (*zc).appliedParams;
4023    if (*params).ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
4024        ZSTD_ldm_adjustParameters(&mut (*zc).appliedParams.ldmParams, &(*params).cParams);
4025    }
4026    let windowSize = if 1
4027        > (if (1 as size_t) << (*params).cParams.windowLog < pledgedSrcSize as size_t {
4028            (1 as size_t) << (*params).cParams.windowLog
4029        } else {
4030            pledgedSrcSize as size_t
4031        }) {
4032        1
4033    } else if (1 as size_t) << (*params).cParams.windowLog < pledgedSrcSize as size_t {
4034        (1 as size_t) << (*params).cParams.windowLog
4035    } else {
4036        pledgedSrcSize as size_t
4037    };
4038    let blockSize = if (*params).maxBlockSize < windowSize {
4039        (*params).maxBlockSize
4040    } else {
4041        windowSize
4042    };
4043    let maxNbSeq = ZSTD_maxNbSeq(
4044        blockSize,
4045        (*params).cParams.minMatch,
4046        ZSTD_hasExtSeqProd(params),
4047    );
4048    let buffOutSize = if zbuff as core::ffi::c_uint
4049        == ZSTDb_buffered as core::ffi::c_int as core::ffi::c_uint
4050        && (*params).outBufferMode as core::ffi::c_uint
4051            == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint
4052    {
4053        (ZSTD_compressBound(blockSize)).wrapping_add(1)
4054    } else {
4055        0
4056    };
4057    let buffInSize = if zbuff as core::ffi::c_uint
4058        == ZSTDb_buffered as core::ffi::c_int as core::ffi::c_uint
4059        && (*params).inBufferMode as core::ffi::c_uint
4060            == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint
4061    {
4062        windowSize.wrapping_add(blockSize)
4063    } else {
4064        0
4065    };
4066    let maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq((*params).ldmParams, blockSize);
4067    let indexTooClose = ZSTD_indexTooCloseToMax((*zc).blockState.matchState.window);
4068    let dictTooBig = ZSTD_dictTooBig(loadedDictSize);
4069    let mut needsIndexReset = (if indexTooClose != 0 || dictTooBig != 0 || (*zc).initialized == 0 {
4070        ZSTDirp_reset as core::ffi::c_int
4071    } else {
4072        ZSTDirp_continue as core::ffi::c_int
4073    }) as ZSTD_indexResetPolicy_e;
4074    let neededSpace = ZSTD_estimateCCtxSize_usingCCtxParams_internal(
4075        &(*params).cParams,
4076        &(*params).ldmParams,
4077        ((*zc).staticSize != 0) as core::ffi::c_int,
4078        (*params).useRowMatchFinder,
4079        buffInSize,
4080        buffOutSize,
4081        pledgedSrcSize,
4082        ZSTD_hasExtSeqProd(params),
4083        (*params).maxBlockSize,
4084    );
4085    let err_code = neededSpace;
4086    if ERR_isError(err_code) {
4087        return err_code;
4088    }
4089    if (*zc).staticSize == 0 {
4090        ZSTD_cwksp_bump_oversized_duration(ws, 0);
4091    }
4092    let workspaceTooSmall = (ZSTD_cwksp_sizeof(ws) < neededSpace) as core::ffi::c_int;
4093    let workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
4094    let resizeWorkspace = (workspaceTooSmall != 0 || workspaceWasteful != 0) as core::ffi::c_int;
4095    if resizeWorkspace != 0 {
4096        if (*zc).staticSize != 0 {
4097            return Error::memory_allocation.to_error_code();
4098        }
4099        needsIndexReset = ZSTDirp_reset;
4100        ZSTD_cwksp_free(ws, (*zc).customMem);
4101        let err_code_0 = ZSTD_cwksp_create(ws, neededSpace, (*zc).customMem);
4102        if ERR_isError(err_code_0) {
4103            return err_code_0;
4104        }
4105        (*zc).blockState.prevCBlock =
4106            ZSTD_cwksp_reserve_object(ws, ::core::mem::size_of::<ZSTD_compressedBlockState_t>())
4107                as *mut ZSTD_compressedBlockState_t;
4108        if ((*zc).blockState.prevCBlock).is_null() {
4109            return Error::memory_allocation.to_error_code();
4110        }
4111        (*zc).blockState.nextCBlock =
4112            ZSTD_cwksp_reserve_object(ws, ::core::mem::size_of::<ZSTD_compressedBlockState_t>())
4113                as *mut ZSTD_compressedBlockState_t;
4114        if ((*zc).blockState.nextCBlock).is_null() {
4115            return Error::memory_allocation.to_error_code();
4116        }
4117        (*zc).tmpWorkspace = ZSTD_cwksp_reserve_object(
4118            ws,
4119            if ((((8) << 10) + 512) as size_t).wrapping_add(
4120                (::core::mem::size_of::<core::ffi::c_uint>())
4121                    .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
4122            ) > 8208
4123            {
4124                ((((8) << 10) + 512) as size_t).wrapping_add(
4125                    (::core::mem::size_of::<core::ffi::c_uint>())
4126                        .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
4127                )
4128            } else {
4129                8208
4130            },
4131        );
4132        if ((*zc).tmpWorkspace).is_null() {
4133            return Error::memory_allocation.to_error_code();
4134        }
4135        (*zc).tmpWkspSize = if ((((8) << 10) + 512) as size_t).wrapping_add(
4136            (::core::mem::size_of::<core::ffi::c_uint>())
4137                .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
4138        ) > 8208
4139        {
4140            ((((8) << 10) + 512) as size_t).wrapping_add(
4141                (::core::mem::size_of::<core::ffi::c_uint>())
4142                    .wrapping_mul(((if 35 > 52 { 35 } else { 52 }) + 2) as size_t),
4143            )
4144        } else {
4145            8208
4146        };
4147    }
4148    ZSTD_cwksp_clear(ws);
4149    (*zc).blockState.matchState.cParams = (*params).cParams;
4150    (*zc).blockState.matchState.prefetchCDictTables =
4151        ((*params).prefetchCDictTables == ZSTD_ParamSwitch_e::ZSTD_ps_enable) as core::ffi::c_int;
4152    (*zc).pledgedSrcSizePlusOne = pledgedSrcSize.wrapping_add(1) as core::ffi::c_ulonglong;
4153    (*zc).consumedSrcSize = 0;
4154    (*zc).producedCSize = 0;
4155    if pledgedSrcSize as core::ffi::c_ulonglong == ZSTD_CONTENTSIZE_UNKNOWN {
4156        (*zc).appliedParams.fParams.contentSizeFlag = 0;
4157    }
4158    (*zc).blockSizeMax = blockSize;
4159    ZSTD_XXH64_reset(&mut (*zc).xxhState, 0);
4160    (*zc).stage = ZSTDcs_init;
4161    (*zc).dictID = 0;
4162    (*zc).dictContentSize = 0;
4163    ZSTD_reset_compressedBlockState((*zc).blockState.prevCBlock);
4164    let err_code_1 = ZSTD_reset_matchState(
4165        &mut (*zc).blockState.matchState,
4166        ws,
4167        &(*params).cParams,
4168        (*params).useRowMatchFinder,
4169        crp,
4170        needsIndexReset,
4171        ZSTD_resetTarget_CCtx,
4172    );
4173    if ERR_isError(err_code_1) {
4174        return err_code_1;
4175    }
4176    (*zc).seqStore.sequencesStart =
4177        ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq.wrapping_mul(::core::mem::size_of::<SeqDef>()))
4178            as *mut SeqDef;
4179    if (*params).ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
4180        let ldmHSize = (1 as size_t) << (*params).ldmParams.hashLog;
4181        (*zc).ldmState.hashTable = ZSTD_cwksp_reserve_aligned64(
4182            ws,
4183            ldmHSize.wrapping_mul(::core::mem::size_of::<ldmEntry_t>()),
4184        ) as *mut ldmEntry_t;
4185        ptr::write_bytes(
4186            (*zc).ldmState.hashTable as *mut u8,
4187            0,
4188            ldmHSize.wrapping_mul(::core::mem::size_of::<ldmEntry_t>()),
4189        );
4190        (*zc).ldmSequences = ZSTD_cwksp_reserve_aligned64(
4191            ws,
4192            maxNbLdmSeq.wrapping_mul(::core::mem::size_of::<rawSeq>()),
4193        ) as *mut rawSeq;
4194        (*zc).maxNbLdmSequences = maxNbLdmSeq;
4195        ZSTD_window_init(&mut (*zc).ldmState.window);
4196        (*zc).ldmState.loadedDictEnd = 0;
4197    }
4198    if ZSTD_hasExtSeqProd(params) != 0 {
4199        let maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
4200        (*zc).extSeqBufCapacity = maxNbExternalSeq;
4201        (*zc).extSeqBuf = ZSTD_cwksp_reserve_aligned64(
4202            ws,
4203            maxNbExternalSeq.wrapping_mul(::core::mem::size_of::<ZSTD_Sequence>()),
4204        ) as *mut ZSTD_Sequence;
4205    }
4206    (*zc).seqStore.litStart =
4207        ZSTD_cwksp_reserve_buffer(ws, blockSize.wrapping_add(WILDCOPY_OVERLENGTH));
4208    (*zc).seqStore.maxNbLit = blockSize;
4209    (*zc).bufferedPolicy = zbuff;
4210    (*zc).inBuffSize = buffInSize;
4211    (*zc).inBuff = ZSTD_cwksp_reserve_buffer(ws, buffInSize);
4212    (*zc).outBuffSize = buffOutSize;
4213    (*zc).outBuff = ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
4214    if (*params).ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
4215        let numBuckets =
4216            (1) << ((*params).ldmParams.hashLog).wrapping_sub((*params).ldmParams.bucketSizeLog);
4217        (*zc).ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
4218        ptr::write_bytes((*zc).ldmState.bucketOffsets, 0, numBuckets);
4219    }
4220    ZSTD_referenceExternalSequences(zc, core::ptr::null_mut(), 0);
4221    (*zc).seqStore.maxNbSeq = maxNbSeq;
4222    (*zc).seqStore.llCode =
4223        ZSTD_cwksp_reserve_buffer(ws, maxNbSeq.wrapping_mul(::core::mem::size_of::<u8>()));
4224    (*zc).seqStore.mlCode =
4225        ZSTD_cwksp_reserve_buffer(ws, maxNbSeq.wrapping_mul(::core::mem::size_of::<u8>()));
4226    (*zc).seqStore.ofCode =
4227        ZSTD_cwksp_reserve_buffer(ws, maxNbSeq.wrapping_mul(::core::mem::size_of::<u8>()));
4228    (*zc).initialized = 1;
4229    0
4230}
4231pub unsafe fn ZSTD_invalidateRepCodes(cctx: *mut ZSTD_CCtx) {
4232    let mut i: core::ffi::c_int = 0;
4233    i = 0;
4234    while i < ZSTD_REP_NUM {
4235        *((*(*cctx).blockState.prevCBlock).rep)
4236            .as_mut_ptr()
4237            .offset(i as isize) = 0;
4238        i += 1;
4239    }
4240}
4241static attachDictSizeCutoffs: [size_t; 10] = [
4242    (8 * ((1) << 10)) as size_t,
4243    (8 * ((1) << 10)) as size_t,
4244    (16 * ((1) << 10)) as size_t,
4245    (32 * ((1) << 10)) as size_t,
4246    (32 * ((1) << 10)) as size_t,
4247    (32 * ((1) << 10)) as size_t,
4248    (32 * ((1) << 10)) as size_t,
4249    (32 * ((1) << 10)) as size_t,
4250    (8 * ((1) << 10)) as size_t,
4251    (8 * ((1) << 10)) as size_t,
4252];
4253unsafe fn ZSTD_shouldAttachDict(
4254    cdict: *const ZSTD_CDict,
4255    params: *const ZSTD_CCtx_params,
4256    pledgedSrcSize: u64,
4257) -> core::ffi::c_int {
4258    let cutoff = *attachDictSizeCutoffs
4259        .as_ptr()
4260        .offset((*cdict).matchState.cParams.strategy as isize);
4261    let dedicatedDictSearch = (*cdict).matchState.dedicatedDictSearch;
4262    (dedicatedDictSearch != 0
4263        || (pledgedSrcSize <= cutoff as u64
4264            || pledgedSrcSize as core::ffi::c_ulonglong == ZSTD_CONTENTSIZE_UNKNOWN
4265            || (*params).attachDictPref == ZSTD_dictAttachPref_e::ZSTD_dictForceAttach)
4266            && (*params).attachDictPref != ZSTD_dictAttachPref_e::ZSTD_dictForceCopy
4267            && (*params).forceWindow == 0) as core::ffi::c_int
4268}
4269unsafe fn ZSTD_resetCCtx_byAttachingCDict(
4270    cctx: *mut ZSTD_CCtx,
4271    cdict: *const ZSTD_CDict,
4272    mut params: ZSTD_CCtx_params,
4273    pledgedSrcSize: u64,
4274    zbuff: ZSTD_buffered_policy_e,
4275) -> size_t {
4276    let mut adjusted_cdict_cParams = (*cdict).matchState.cParams;
4277    let windowLog = params.cParams.windowLog;
4278    if (*cdict).matchState.dedicatedDictSearch != 0 {
4279        ZSTD_dedicatedDictSearch_revertCParams(&mut adjusted_cdict_cParams);
4280    }
4281    params.cParams = ZSTD_adjustCParams_internal(
4282        adjusted_cdict_cParams,
4283        pledgedSrcSize as core::ffi::c_ulonglong,
4284        (*cdict).dictContentSize,
4285        ZSTD_cpm_attachDict,
4286        params.useRowMatchFinder,
4287    );
4288    params.cParams.windowLog = windowLog;
4289    params.useRowMatchFinder = (*cdict).useRowMatchFinder;
4290    let err_code =
4291        ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize, 0, ZSTDcrp_makeClean, zbuff);
4292    if ERR_isError(err_code) {
4293        return err_code;
4294    }
4295    let cdictEnd = ((*cdict).matchState.window.nextSrc).offset_from((*cdict).matchState.window.base)
4296        as core::ffi::c_long as u32;
4297    let cdictLen = cdictEnd.wrapping_sub((*cdict).matchState.window.dictLimit);
4298    if cdictLen != 0 {
4299        (*cctx).blockState.matchState.dictMatchState = &(*cdict).matchState;
4300        if (*cctx).blockState.matchState.window.dictLimit < cdictEnd {
4301            (*cctx).blockState.matchState.window.nextSrc =
4302                ((*cctx).blockState.matchState.window.base).wrapping_offset(cdictEnd as isize);
4303            ZSTD_window_clear(&mut (*cctx).blockState.matchState.window);
4304        }
4305        (*cctx).blockState.matchState.loadedDictEnd =
4306            (*cctx).blockState.matchState.window.dictLimit;
4307    }
4308    (*cctx).dictID = (*cdict).dictID;
4309    (*cctx).dictContentSize = (*cdict).dictContentSize;
4310    libc::memcpy(
4311        (*cctx).blockState.prevCBlock as *mut core::ffi::c_void,
4312        &(*cdict).cBlockState as *const ZSTD_compressedBlockState_t as *const core::ffi::c_void,
4313        ::core::mem::size_of::<ZSTD_compressedBlockState_t>(),
4314    );
4315    0
4316}
4317unsafe fn ZSTD_copyCDictTableIntoCCtx(
4318    dst: *mut u32,
4319    src: *const u32,
4320    tableSize: size_t,
4321    cParams: *const ZSTD_compressionParameters,
4322) {
4323    if ZSTD_CDictIndicesAreTagged(cParams) != 0 {
4324        let mut i: size_t = 0;
4325        i = 0;
4326        while i < tableSize {
4327            let taggedIndex = *src.add(i);
4328            let index = taggedIndex >> ZSTD_SHORT_CACHE_TAG_BITS;
4329            *dst.add(i) = index;
4330            i = i.wrapping_add(1);
4331        }
4332    } else {
4333        libc::memcpy(
4334            dst as *mut core::ffi::c_void,
4335            src as *const core::ffi::c_void,
4336            tableSize.wrapping_mul(::core::mem::size_of::<u32>()),
4337        );
4338    }
4339}
4340unsafe fn ZSTD_resetCCtx_byCopyingCDict(
4341    cctx: *mut ZSTD_CCtx,
4342    cdict: *const ZSTD_CDict,
4343    mut params: ZSTD_CCtx_params,
4344    pledgedSrcSize: u64,
4345    zbuff: ZSTD_buffered_policy_e,
4346) -> size_t {
4347    let cdict_cParams: *const ZSTD_compressionParameters = &(*cdict).matchState.cParams;
4348    let windowLog = params.cParams.windowLog;
4349    params.cParams = *cdict_cParams;
4350    params.cParams.windowLog = windowLog;
4351    params.useRowMatchFinder = (*cdict).useRowMatchFinder;
4352    let err_code =
4353        ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize, 0, ZSTDcrp_leaveDirty, zbuff);
4354    if ERR_isError(err_code) {
4355        return err_code;
4356    }
4357    ZSTD_cwksp_mark_tables_dirty(&mut (*cctx).workspace);
4358    let chainSize =
4359        if ZSTD_allocateChainTable((*cdict_cParams).strategy, (*cdict).useRowMatchFinder, 0) != 0 {
4360            (1) << (*cdict_cParams).chainLog
4361        } else {
4362            0
4363        };
4364    let hSize = (1) << (*cdict_cParams).hashLog;
4365    ZSTD_copyCDictTableIntoCCtx(
4366        (*cctx).blockState.matchState.hashTable,
4367        (*cdict).matchState.hashTable,
4368        hSize,
4369        cdict_cParams,
4370    );
4371    if ZSTD_allocateChainTable(
4372        (*cctx).appliedParams.cParams.strategy,
4373        (*cctx).appliedParams.useRowMatchFinder,
4374        0,
4375    ) != 0
4376    {
4377        ZSTD_copyCDictTableIntoCCtx(
4378            (*cctx).blockState.matchState.chainTable,
4379            (*cdict).matchState.chainTable,
4380            chainSize,
4381            cdict_cParams,
4382        );
4383    }
4384    if ZSTD_rowMatchFinderUsed((*cdict_cParams).strategy, (*cdict).useRowMatchFinder) != 0 {
4385        let tagTableSize = hSize;
4386        libc::memcpy(
4387            (*cctx).blockState.matchState.tagTable as *mut core::ffi::c_void,
4388            (*cdict).matchState.tagTable as *const core::ffi::c_void,
4389            tagTableSize as libc::size_t,
4390        );
4391        (*cctx).blockState.matchState.hashSalt = (*cdict).matchState.hashSalt;
4392    }
4393    let h3log = (*cctx).blockState.matchState.hashLog3;
4394    let h3Size = if h3log != 0 {
4395        (1 as size_t) << h3log
4396    } else {
4397        0 as size_t
4398    };
4399    ptr::write_bytes(
4400        (*cctx).blockState.matchState.hashTable3 as *mut u8,
4401        0,
4402        h3Size.wrapping_mul(::core::mem::size_of::<u32>()),
4403    );
4404    ZSTD_cwksp_mark_tables_clean(&mut (*cctx).workspace);
4405    let srcMatchState: *const ZSTD_MatchState_t = &(*cdict).matchState;
4406    let dstMatchState: &mut ZSTD_MatchState_t = &mut (*cctx).blockState.matchState;
4407    dstMatchState.window = (*srcMatchState).window;
4408    dstMatchState.nextToUpdate = (*srcMatchState).nextToUpdate;
4409    dstMatchState.loadedDictEnd = (*srcMatchState).loadedDictEnd;
4410    (*cctx).dictID = (*cdict).dictID;
4411    (*cctx).dictContentSize = (*cdict).dictContentSize;
4412    libc::memcpy(
4413        (*cctx).blockState.prevCBlock as *mut core::ffi::c_void,
4414        &(*cdict).cBlockState as *const ZSTD_compressedBlockState_t as *const core::ffi::c_void,
4415        ::core::mem::size_of::<ZSTD_compressedBlockState_t>(),
4416    );
4417    0
4418}
4419unsafe fn ZSTD_resetCCtx_usingCDict(
4420    cctx: *mut ZSTD_CCtx,
4421    cdict: *const ZSTD_CDict,
4422    params: *const ZSTD_CCtx_params,
4423    pledgedSrcSize: u64,
4424    zbuff: ZSTD_buffered_policy_e,
4425) -> size_t {
4426    if ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize) != 0 {
4427        ZSTD_resetCCtx_byAttachingCDict(cctx, cdict, *params, pledgedSrcSize, zbuff)
4428    } else {
4429        ZSTD_resetCCtx_byCopyingCDict(cctx, cdict, *params, pledgedSrcSize, zbuff)
4430    }
4431}
4432unsafe fn ZSTD_copyCCtx_internal(
4433    dstCCtx: *mut ZSTD_CCtx,
4434    srcCCtx: *const ZSTD_CCtx,
4435    fParams: ZSTD_frameParameters,
4436    pledgedSrcSize: u64,
4437    zbuff: ZSTD_buffered_policy_e,
4438) -> size_t {
4439    if (*srcCCtx).stage as core::ffi::c_uint != ZSTDcs_init as core::ffi::c_int as core::ffi::c_uint
4440    {
4441        return Error::stage_wrong.to_error_code();
4442    }
4443    libc::memcpy(
4444        &mut (*dstCCtx).customMem as *mut ZSTD_customMem as *mut core::ffi::c_void,
4445        &(*srcCCtx).customMem as *const ZSTD_customMem as *const core::ffi::c_void,
4446        ::core::mem::size_of::<ZSTD_customMem>(),
4447    );
4448    let mut params = (*dstCCtx).requestedParams;
4449    params.cParams = (*srcCCtx).appliedParams.cParams;
4450    params.useRowMatchFinder = (*srcCCtx).appliedParams.useRowMatchFinder;
4451    params.postBlockSplitter = (*srcCCtx).appliedParams.postBlockSplitter;
4452    params.ldmParams = (*srcCCtx).appliedParams.ldmParams;
4453    params.fParams = fParams;
4454    params.maxBlockSize = (*srcCCtx).appliedParams.maxBlockSize;
4455    ZSTD_resetCCtx_internal(
4456        dstCCtx,
4457        &params,
4458        pledgedSrcSize,
4459        0,
4460        ZSTDcrp_leaveDirty,
4461        zbuff,
4462    );
4463    ZSTD_cwksp_mark_tables_dirty(&mut (*dstCCtx).workspace);
4464    let chainSize = if ZSTD_allocateChainTable(
4465        (*srcCCtx).appliedParams.cParams.strategy,
4466        (*srcCCtx).appliedParams.useRowMatchFinder,
4467        0,
4468    ) != 0
4469    {
4470        (1 as size_t) << (*srcCCtx).appliedParams.cParams.chainLog
4471    } else {
4472        0 as size_t
4473    };
4474    let hSize = (1 as size_t) << (*srcCCtx).appliedParams.cParams.hashLog;
4475    let h3log = (*srcCCtx).blockState.matchState.hashLog3;
4476    let h3Size = if h3log != 0 {
4477        (1 as size_t) << h3log
4478    } else {
4479        0 as size_t
4480    };
4481    libc::memcpy(
4482        (*dstCCtx).blockState.matchState.hashTable as *mut core::ffi::c_void,
4483        (*srcCCtx).blockState.matchState.hashTable as *const core::ffi::c_void,
4484        hSize.wrapping_mul(::core::mem::size_of::<u32>()) as libc::size_t,
4485    );
4486    libc::memcpy(
4487        (*dstCCtx).blockState.matchState.chainTable as *mut core::ffi::c_void,
4488        (*srcCCtx).blockState.matchState.chainTable as *const core::ffi::c_void,
4489        chainSize.wrapping_mul(::core::mem::size_of::<u32>()) as libc::size_t,
4490    );
4491    libc::memcpy(
4492        (*dstCCtx).blockState.matchState.hashTable3 as *mut core::ffi::c_void,
4493        (*srcCCtx).blockState.matchState.hashTable3 as *const core::ffi::c_void,
4494        h3Size.wrapping_mul(::core::mem::size_of::<u32>()) as libc::size_t,
4495    );
4496    ZSTD_cwksp_mark_tables_clean(&mut (*dstCCtx).workspace);
4497    let srcMatchState: *const ZSTD_MatchState_t = &(*srcCCtx).blockState.matchState;
4498    let dstMatchState: &mut ZSTD_MatchState_t = &mut (*dstCCtx).blockState.matchState;
4499    dstMatchState.window = (*srcMatchState).window;
4500    dstMatchState.nextToUpdate = (*srcMatchState).nextToUpdate;
4501    dstMatchState.loadedDictEnd = (*srcMatchState).loadedDictEnd;
4502    (*dstCCtx).dictID = (*srcCCtx).dictID;
4503    (*dstCCtx).dictContentSize = (*srcCCtx).dictContentSize;
4504    libc::memcpy(
4505        (*dstCCtx).blockState.prevCBlock as *mut core::ffi::c_void,
4506        (*srcCCtx).blockState.prevCBlock as *const core::ffi::c_void,
4507        ::core::mem::size_of::<ZSTD_compressedBlockState_t>() as libc::size_t,
4508    );
4509    0
4510}
4511#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_copyCCtx))]
4512pub unsafe extern "C" fn ZSTD_copyCCtx(
4513    dstCCtx: *mut ZSTD_CCtx,
4514    srcCCtx: *const ZSTD_CCtx,
4515    mut pledgedSrcSize: core::ffi::c_ulonglong,
4516) -> size_t {
4517    let mut fParams = {
4518        ZSTD_frameParameters {
4519            contentSizeFlag: 1,
4520            checksumFlag: 0,
4521            noDictIDFlag: 0,
4522        }
4523    };
4524    let zbuff = (*srcCCtx).bufferedPolicy;
4525    if pledgedSrcSize == 0 {
4526        pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
4527    }
4528    fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) as core::ffi::c_int;
4529    ZSTD_copyCCtx_internal(dstCCtx, srcCCtx, fParams, pledgedSrcSize, zbuff)
4530}
4531pub const ZSTD_ROWSIZE: core::ffi::c_int = 16;
4532#[inline(always)]
4533unsafe fn ZSTD_reduceTable_internal(
4534    table: *mut u32,
4535    size: u32,
4536    reducerValue: u32,
4537    preserveMark: core::ffi::c_int,
4538) {
4539    let nbRows = size as core::ffi::c_int / ZSTD_ROWSIZE;
4540    let mut cellNb = 0;
4541    let mut rowNb: core::ffi::c_int = 0;
4542    let reducerThreshold = reducerValue.wrapping_add(ZSTD_WINDOW_START_INDEX as u32);
4543    rowNb = 0;
4544    while rowNb < nbRows {
4545        let mut column: core::ffi::c_int = 0;
4546        column = 0;
4547        while column < ZSTD_ROWSIZE {
4548            let mut newVal: u32 = 0;
4549            if preserveMark != 0 && *table.offset(cellNb as isize) == ZSTD_DUBT_UNSORTED_MARK as u32
4550            {
4551                newVal = ZSTD_DUBT_UNSORTED_MARK as u32;
4552            } else if *table.offset(cellNb as isize) < reducerThreshold {
4553                newVal = 0;
4554            } else {
4555                newVal = (*table.offset(cellNb as isize)).wrapping_sub(reducerValue);
4556            }
4557            *table.offset(cellNb as isize) = newVal;
4558            cellNb += 1;
4559            column += 1;
4560        }
4561        rowNb += 1;
4562    }
4563}
4564unsafe fn ZSTD_reduceTable(table: *mut u32, size: u32, reducerValue: u32) {
4565    ZSTD_reduceTable_internal(table, size, reducerValue, 0);
4566}
4567unsafe fn ZSTD_reduceTable_btlazy2(table: *mut u32, size: u32, reducerValue: u32) {
4568    ZSTD_reduceTable_internal(table, size, reducerValue, 1);
4569}
4570unsafe fn ZSTD_reduceIndex(
4571    ms: &mut ZSTD_MatchState_t,
4572    params: *const ZSTD_CCtx_params,
4573    reducerValue: u32,
4574) {
4575    let hSize = (1) << (*params).cParams.hashLog;
4576    ZSTD_reduceTable(ms.hashTable, hSize, reducerValue);
4577    if ZSTD_allocateChainTable(
4578        (*params).cParams.strategy,
4579        (*params).useRowMatchFinder,
4580        ms.dedicatedDictSearch as u32,
4581    ) != 0
4582    {
4583        let chainSize = (1) << (*params).cParams.chainLog;
4584        if (*params).cParams.strategy as core::ffi::c_uint
4585            == ZSTD_btlazy2 as core::ffi::c_int as core::ffi::c_uint
4586        {
4587            ZSTD_reduceTable_btlazy2(ms.chainTable, chainSize, reducerValue);
4588        } else {
4589            ZSTD_reduceTable(ms.chainTable, chainSize, reducerValue);
4590        }
4591    }
4592    if ms.hashLog3 != 0 {
4593        let h3Size = (1) << ms.hashLog3;
4594        ZSTD_reduceTable(ms.hashTable3, h3Size, reducerValue);
4595    }
4596}
4597pub unsafe fn ZSTD_seqToCodes(seqStorePtr: *const SeqStore_t) -> core::ffi::c_int {
4598    let sequences: *const SeqDef = (*seqStorePtr).sequencesStart;
4599    let llCodeTable = (*seqStorePtr).llCode;
4600    let ofCodeTable = (*seqStorePtr).ofCode;
4601    let mlCodeTable = (*seqStorePtr).mlCode;
4602    let nbSeq = ((*seqStorePtr).sequences).offset_from((*seqStorePtr).sequencesStart)
4603        as core::ffi::c_long as u32;
4604    let mut u: u32 = 0;
4605    let mut longOffsets = 0;
4606    u = 0;
4607    while u < nbSeq {
4608        let llv = (*sequences.offset(u as isize)).litLength as u32;
4609        let ofCode = ZSTD_highbit32((*sequences.offset(u as isize)).offBase);
4610        let mlv = (*sequences.offset(u as isize)).mlBase as u32;
4611        *llCodeTable.offset(u as isize) = ZSTD_LLcode(llv) as u8;
4612        *ofCodeTable.offset(u as isize) = ofCode as u8;
4613        *mlCodeTable.offset(u as isize) = ZSTD_MLcode(mlv) as u8;
4614        if MEM_32bits()
4615            && ofCode
4616                >= (if MEM_32bits() {
4617                    STREAM_ACCUMULATOR_MIN_32
4618                } else {
4619                    STREAM_ACCUMULATOR_MIN_64
4620                }) as u32
4621        {
4622            longOffsets = 1;
4623        }
4624        u = u.wrapping_add(1);
4625    }
4626    if (*seqStorePtr).longLengthType == ZSTD_llt_literalLength {
4627        *llCodeTable.offset((*seqStorePtr).longLengthPos as isize) = MaxLL as u8;
4628    }
4629    if (*seqStorePtr).longLengthType == ZSTD_llt_matchLength {
4630        *mlCodeTable.offset((*seqStorePtr).longLengthPos as isize) = MaxML as u8;
4631    }
4632    longOffsets
4633}
4634unsafe fn ZSTD_useTargetCBlockSize(cctxParams: *const ZSTD_CCtx_params) -> core::ffi::c_int {
4635    ((*cctxParams).targetCBlockSize != 0) as core::ffi::c_int
4636}
4637unsafe fn ZSTD_blockSplitterEnabled(cctxParams: *mut ZSTD_CCtx_params) -> core::ffi::c_int {
4638    ((*cctxParams).postBlockSplitter == ZSTD_ParamSwitch_e::ZSTD_ps_enable) as core::ffi::c_int
4639}
4640unsafe fn ZSTD_buildSequencesStatistics(
4641    seqStorePtr: *const SeqStore_t,
4642    nbSeq: size_t,
4643    prevEntropy: *const ZSTD_fseCTables_t,
4644    nextEntropy: *mut ZSTD_fseCTables_t,
4645    dst: *mut u8,
4646    dstEnd: *const u8,
4647    strategy: ZSTD_strategy,
4648    countWorkspace: *mut core::ffi::c_uint,
4649    entropyWorkspace: *mut core::ffi::c_void,
4650    entropyWkspSize: size_t,
4651) -> ZSTD_symbolEncodingTypeStats_t {
4652    let ostart = dst;
4653    let oend = dstEnd;
4654    let mut op = ostart;
4655    let CTable_LitLength = ((*nextEntropy).litlengthCTable).as_mut_ptr();
4656    let CTable_OffsetBits = ((*nextEntropy).offcodeCTable).as_mut_ptr();
4657    let CTable_MatchLength = ((*nextEntropy).matchlengthCTable).as_mut_ptr();
4658    let ofCodeTable: *const u8 = (*seqStorePtr).ofCode;
4659    let llCodeTable: *const u8 = (*seqStorePtr).llCode;
4660    let mlCodeTable: *const u8 = (*seqStorePtr).mlCode;
4661    let mut stats = ZSTD_symbolEncodingTypeStats_t {
4662        LLtype: 0,
4663        Offtype: 0,
4664        MLtype: 0,
4665        size: 0,
4666        lastCountSize: 0,
4667        longOffsets: 0,
4668    };
4669    stats.lastCountSize = 0;
4670    stats.longOffsets = ZSTD_seqToCodes(seqStorePtr);
4671    let mut max = MaxLL;
4672    let mostFrequent = HIST_countFast_wksp(
4673        countWorkspace,
4674        &mut max,
4675        llCodeTable as *const core::ffi::c_void,
4676        nbSeq,
4677        entropyWorkspace,
4678        entropyWkspSize,
4679    );
4680    (*nextEntropy).litlength_repeatMode = (*prevEntropy).litlength_repeatMode;
4681    stats.LLtype = ZSTD_selectEncodingType(
4682        &mut (*nextEntropy).litlength_repeatMode,
4683        countWorkspace,
4684        max,
4685        mostFrequent,
4686        nbSeq,
4687        LLFSELog,
4688        ((*prevEntropy).litlengthCTable).as_ptr(),
4689        LL_defaultNorm.as_ptr(),
4690        LL_defaultNormLog,
4691        ZSTD_defaultAllowed,
4692        strategy,
4693    ) as u32;
4694    let countSize = ZSTD_buildCTable(
4695        op as *mut core::ffi::c_void,
4696        oend.offset_from_unsigned(op),
4697        CTable_LitLength,
4698        LLFSELog,
4699        stats.LLtype as SymbolEncodingType_e,
4700        countWorkspace,
4701        max,
4702        llCodeTable,
4703        nbSeq,
4704        LL_defaultNorm.as_ptr(),
4705        LL_defaultNormLog,
4706        MaxLL,
4707        ((*prevEntropy).litlengthCTable).as_ptr(),
4708        ::core::mem::size_of::<[FSE_CTable; 329]>(),
4709        entropyWorkspace,
4710        entropyWkspSize,
4711    );
4712    if ERR_isError(countSize) {
4713        stats.size = countSize;
4714        return stats;
4715    }
4716    if stats.LLtype == set_compressed as core::ffi::c_int as u32 {
4717        stats.lastCountSize = countSize;
4718    }
4719    op = op.add(countSize);
4720    let mut max_0 = MaxOff;
4721    let mostFrequent_0 = HIST_countFast_wksp(
4722        countWorkspace,
4723        &mut max_0,
4724        ofCodeTable as *const core::ffi::c_void,
4725        nbSeq,
4726        entropyWorkspace,
4727        entropyWkspSize,
4728    );
4729    let defaultPolicy = (if max_0 <= DefaultMaxOff {
4730        ZSTD_defaultAllowed as core::ffi::c_int
4731    } else {
4732        ZSTD_defaultDisallowed as core::ffi::c_int
4733    }) as ZSTD_DefaultPolicy_e;
4734    (*nextEntropy).offcode_repeatMode = (*prevEntropy).offcode_repeatMode;
4735    stats.Offtype = ZSTD_selectEncodingType(
4736        &mut (*nextEntropy).offcode_repeatMode,
4737        countWorkspace,
4738        max_0,
4739        mostFrequent_0,
4740        nbSeq,
4741        OffFSELog,
4742        ((*prevEntropy).offcodeCTable).as_ptr(),
4743        OF_defaultNorm.as_ptr(),
4744        OF_defaultNormLog,
4745        defaultPolicy,
4746        strategy,
4747    ) as u32;
4748    let countSize_0 = ZSTD_buildCTable(
4749        op as *mut core::ffi::c_void,
4750        oend.offset_from_unsigned(op),
4751        CTable_OffsetBits,
4752        OffFSELog,
4753        stats.Offtype as SymbolEncodingType_e,
4754        countWorkspace,
4755        max_0,
4756        ofCodeTable,
4757        nbSeq,
4758        OF_defaultNorm.as_ptr(),
4759        OF_defaultNormLog,
4760        DefaultMaxOff,
4761        ((*prevEntropy).offcodeCTable).as_ptr(),
4762        ::core::mem::size_of::<[FSE_CTable; 193]>(),
4763        entropyWorkspace,
4764        entropyWkspSize,
4765    );
4766    if ERR_isError(countSize_0) {
4767        stats.size = countSize_0;
4768        return stats;
4769    }
4770    if stats.Offtype == set_compressed as core::ffi::c_int as u32 {
4771        stats.lastCountSize = countSize_0;
4772    }
4773    op = op.add(countSize_0);
4774    let mut max_1 = MaxML;
4775    let mostFrequent_1 = HIST_countFast_wksp(
4776        countWorkspace,
4777        &mut max_1,
4778        mlCodeTable as *const core::ffi::c_void,
4779        nbSeq,
4780        entropyWorkspace,
4781        entropyWkspSize,
4782    );
4783    (*nextEntropy).matchlength_repeatMode = (*prevEntropy).matchlength_repeatMode;
4784    stats.MLtype = ZSTD_selectEncodingType(
4785        &mut (*nextEntropy).matchlength_repeatMode,
4786        countWorkspace,
4787        max_1,
4788        mostFrequent_1,
4789        nbSeq,
4790        MLFSELog,
4791        ((*prevEntropy).matchlengthCTable).as_ptr(),
4792        ML_defaultNorm.as_ptr(),
4793        ML_defaultNormLog,
4794        ZSTD_defaultAllowed,
4795        strategy,
4796    ) as u32;
4797    let countSize_1 = ZSTD_buildCTable(
4798        op as *mut core::ffi::c_void,
4799        oend.offset_from_unsigned(op),
4800        CTable_MatchLength,
4801        MLFSELog,
4802        stats.MLtype as SymbolEncodingType_e,
4803        countWorkspace,
4804        max_1,
4805        mlCodeTable,
4806        nbSeq,
4807        ML_defaultNorm.as_ptr(),
4808        ML_defaultNormLog,
4809        MaxML,
4810        ((*prevEntropy).matchlengthCTable).as_ptr(),
4811        ::core::mem::size_of::<[FSE_CTable; 363]>(),
4812        entropyWorkspace,
4813        entropyWkspSize,
4814    );
4815    if ERR_isError(countSize_1) {
4816        stats.size = countSize_1;
4817        return stats;
4818    }
4819    if stats.MLtype == set_compressed as core::ffi::c_int as u32 {
4820        stats.lastCountSize = countSize_1;
4821    }
4822    op = op.add(countSize_1);
4823    stats.size = op.offset_from_unsigned(ostart);
4824    stats
4825}
4826pub const SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO: core::ffi::c_int = 20;
4827#[inline]
4828unsafe fn ZSTD_entropyCompressSeqStore_internal(
4829    dst: *mut core::ffi::c_void,
4830    dstCapacity: size_t,
4831    literals: *const core::ffi::c_void,
4832    litSize: size_t,
4833    seqStorePtr: *const SeqStore_t,
4834    prevEntropy: *const ZSTD_entropyCTables_t,
4835    nextEntropy: *mut ZSTD_entropyCTables_t,
4836    cctxParams: *const ZSTD_CCtx_params,
4837    mut entropyWorkspace: *mut core::ffi::c_void,
4838    mut entropyWkspSize: size_t,
4839    bmi2: core::ffi::c_int,
4840) -> size_t {
4841    let strategy = (*cctxParams).cParams.strategy;
4842    let count = entropyWorkspace as *mut core::ffi::c_uint;
4843    let CTable_LitLength = (&raw const ((*nextEntropy).fse.litlengthCTable)).cast::<u32>();
4844    let CTable_OffsetBits = (&raw const ((*nextEntropy).fse.offcodeCTable)).cast::<u32>();
4845    let CTable_MatchLength = (&raw const ((*nextEntropy).fse.matchlengthCTable)).cast::<u32>();
4846    let sequences: *const SeqDef = (*seqStorePtr).sequencesStart;
4847    let nbSeq = ((*seqStorePtr).sequences).offset_from((*seqStorePtr).sequencesStart) as size_t;
4848    let ofCodeTable: *const u8 = (*seqStorePtr).ofCode;
4849    let llCodeTable: *const u8 = (*seqStorePtr).llCode;
4850    let mlCodeTable: *const u8 = (*seqStorePtr).mlCode;
4851    let ostart = dst as *mut u8;
4852    let oend = ostart.add(dstCapacity);
4853    let mut op = ostart;
4854    let mut lastCountSize: size_t = 0;
4855    let mut longOffsets = 0;
4856    entropyWorkspace =
4857        count.offset(((if 35 > 52 { 35 } else { 52 }) + 1) as isize) as *mut core::ffi::c_void;
4858    entropyWkspSize = (entropyWkspSize as size_t).wrapping_sub(
4859        ((if 35 > 52 { 35 as size_t } else { 52 }) + 1)
4860            .wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>()),
4861    );
4862    let numSequences =
4863        ((*seqStorePtr).sequences).offset_from((*seqStorePtr).sequencesStart) as size_t;
4864    let suspectUncompressible = (numSequences == 0
4865        || litSize / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO as size_t)
4866        as core::ffi::c_int;
4867    let cSize = ZSTD_compressLiterals(
4868        op as *mut core::ffi::c_void,
4869        dstCapacity,
4870        literals,
4871        litSize,
4872        entropyWorkspace,
4873        entropyWkspSize,
4874        &(*prevEntropy).huf,
4875        &mut (*nextEntropy).huf,
4876        (*cctxParams).cParams.strategy,
4877        ZSTD_literalsCompressionIsDisabled(cctxParams),
4878        suspectUncompressible,
4879        bmi2,
4880    );
4881    let err_code = cSize;
4882    if ERR_isError(err_code) {
4883        return err_code;
4884    }
4885    op = op.add(cSize);
4886    if (oend.offset_from(op) as core::ffi::c_long) < (3 + 1) as core::ffi::c_long {
4887        return Error::dstSize_tooSmall.to_error_code();
4888    }
4889    if nbSeq < 128 {
4890        let fresh2 = op;
4891        op = op.add(1);
4892        *fresh2 = nbSeq as u8;
4893    } else if nbSeq < LONGNBSEQ as size_t {
4894        *op = (nbSeq >> 8).wrapping_add(0x80 as core::ffi::c_int as size_t) as u8;
4895        *op.add(1) = nbSeq as u8;
4896        op = op.add(2);
4897    } else {
4898        *op = 0xff as core::ffi::c_int as u8;
4899        MEM_writeLE16(
4900            op.add(1) as *mut core::ffi::c_void,
4901            nbSeq.wrapping_sub(LONGNBSEQ as size_t) as u16,
4902        );
4903        op = op.add(3);
4904    }
4905    if nbSeq == 0 {
4906        libc::memcpy(
4907            &mut (*nextEntropy).fse as *mut ZSTD_fseCTables_t as *mut core::ffi::c_void,
4908            &(*prevEntropy).fse as *const ZSTD_fseCTables_t as *const core::ffi::c_void,
4909            ::core::mem::size_of::<ZSTD_fseCTables_t>(),
4910        );
4911        return op.offset_from_unsigned(ostart);
4912    }
4913    let fresh3 = op;
4914    op = op.add(1);
4915    let seqHead = fresh3;
4916    let stats = ZSTD_buildSequencesStatistics(
4917        seqStorePtr,
4918        nbSeq,
4919        &(*prevEntropy).fse,
4920        &mut (*nextEntropy).fse,
4921        op,
4922        oend,
4923        strategy,
4924        count,
4925        entropyWorkspace,
4926        entropyWkspSize,
4927    );
4928    let err_code_0 = stats.size;
4929    if ERR_isError(err_code_0) {
4930        return err_code_0;
4931    }
4932    *seqHead = (stats.LLtype << 6)
4933        .wrapping_add(stats.Offtype << 4)
4934        .wrapping_add(stats.MLtype << 2) as u8;
4935    lastCountSize = stats.lastCountSize;
4936    op = op.add(stats.size);
4937    longOffsets = stats.longOffsets;
4938    let bitstreamSize = ZSTD_encodeSequences(
4939        op as *mut core::ffi::c_void,
4940        oend.offset_from_unsigned(op),
4941        CTable_MatchLength,
4942        mlCodeTable,
4943        CTable_OffsetBits,
4944        ofCodeTable,
4945        CTable_LitLength,
4946        llCodeTable,
4947        sequences,
4948        nbSeq,
4949        longOffsets,
4950        bmi2,
4951    );
4952    let err_code_1 = bitstreamSize;
4953    if ERR_isError(err_code_1) {
4954        return err_code_1;
4955    }
4956    op = op.add(bitstreamSize);
4957    if lastCountSize != 0 && lastCountSize.wrapping_add(bitstreamSize) < 4 {
4958        return 0;
4959    }
4960    op.offset_from_unsigned(ostart)
4961}
4962unsafe fn ZSTD_entropyCompressSeqStore_wExtLitBuffer(
4963    dst: *mut core::ffi::c_void,
4964    dstCapacity: size_t,
4965    literals: *const core::ffi::c_void,
4966    litSize: size_t,
4967    blockSize: size_t,
4968    seqStorePtr: *const SeqStore_t,
4969    prevEntropy: *const ZSTD_entropyCTables_t,
4970    nextEntropy: *mut ZSTD_entropyCTables_t,
4971    cctxParams: *const ZSTD_CCtx_params,
4972    entropyWorkspace: *mut core::ffi::c_void,
4973    entropyWkspSize: size_t,
4974    bmi2: core::ffi::c_int,
4975) -> size_t {
4976    let cSize = ZSTD_entropyCompressSeqStore_internal(
4977        dst,
4978        dstCapacity,
4979        literals,
4980        litSize,
4981        seqStorePtr,
4982        prevEntropy,
4983        nextEntropy,
4984        cctxParams,
4985        entropyWorkspace,
4986        entropyWkspSize,
4987        bmi2,
4988    );
4989    if cSize == 0 {
4990        return 0;
4991    }
4992    if (cSize == Error::dstSize_tooSmall.to_error_code()) as core::ffi::c_int
4993        & (blockSize <= dstCapacity) as core::ffi::c_int
4994        != 0
4995    {
4996        return 0;
4997    }
4998    let err_code = cSize;
4999    if ERR_isError(err_code) {
5000        return err_code;
5001    }
5002    let maxCSize = blockSize.wrapping_sub(ZSTD_minGain(blockSize, (*cctxParams).cParams.strategy));
5003    if cSize >= maxCSize {
5004        return 0;
5005    }
5006    cSize
5007}
5008unsafe fn ZSTD_entropyCompressSeqStore(
5009    seqStorePtr: *const SeqStore_t,
5010    prevEntropy: *const ZSTD_entropyCTables_t,
5011    nextEntropy: *mut ZSTD_entropyCTables_t,
5012    cctxParams: *const ZSTD_CCtx_params,
5013    dst: *mut core::ffi::c_void,
5014    dstCapacity: size_t,
5015    srcSize: size_t,
5016    entropyWorkspace: *mut core::ffi::c_void,
5017    entropyWkspSize: size_t,
5018    bmi2: core::ffi::c_int,
5019) -> size_t {
5020    ZSTD_entropyCompressSeqStore_wExtLitBuffer(
5021        dst,
5022        dstCapacity,
5023        (*seqStorePtr).litStart as *const core::ffi::c_void,
5024        ((*seqStorePtr).lit).offset_from((*seqStorePtr).litStart) as size_t,
5025        srcSize,
5026        seqStorePtr,
5027        prevEntropy,
5028        nextEntropy,
5029        cctxParams,
5030        entropyWorkspace,
5031        entropyWkspSize,
5032        bmi2,
5033    )
5034}
5035pub unsafe fn ZSTD_selectBlockCompressor(
5036    strat: ZSTD_strategy,
5037    useRowMatchFinder: ZSTD_ParamSwitch_e,
5038    dictMode: ZSTD_dictMode_e,
5039) -> ZSTD_BlockCompressor_f {
5040    static blockCompressor: [[ZSTD_BlockCompressor_f; 10]; 4] = [
5041        [
5042            Some(
5043                ZSTD_compressBlock_fast
5044                    as unsafe fn(
5045                        &mut ZSTD_MatchState_t,
5046                        &mut SeqStore_t,
5047                        *mut u32,
5048                        *const core::ffi::c_void,
5049                        size_t,
5050                    ) -> size_t,
5051            ),
5052            Some(
5053                ZSTD_compressBlock_fast
5054                    as unsafe fn(
5055                        &mut ZSTD_MatchState_t,
5056                        &mut SeqStore_t,
5057                        *mut u32,
5058                        *const core::ffi::c_void,
5059                        size_t,
5060                    ) -> size_t,
5061            ),
5062            Some(ZSTD_COMPRESSBLOCK_DOUBLEFAST),
5063            Some(ZSTD_COMPRESSBLOCK_GREEDY),
5064            Some(ZSTD_COMPRESSBLOCK_LAZY),
5065            Some(ZSTD_COMPRESSBLOCK_LAZY2),
5066            Some(ZSTD_COMPRESSBLOCK_BTLAZY2),
5067            Some(ZSTD_COMPRESSBLOCK_BTOPT),
5068            Some(ZSTD_COMPRESSBLOCK_BTULTRA),
5069            Some(ZSTD_COMPRESSBLOCK_BTULTRA2),
5070        ],
5071        [
5072            Some(
5073                ZSTD_compressBlock_fast_extDict
5074                    as unsafe fn(
5075                        &mut ZSTD_MatchState_t,
5076                        &mut SeqStore_t,
5077                        *mut u32,
5078                        *const core::ffi::c_void,
5079                        size_t,
5080                    ) -> size_t,
5081            ),
5082            Some(
5083                ZSTD_compressBlock_fast_extDict
5084                    as unsafe fn(
5085                        &mut ZSTD_MatchState_t,
5086                        &mut SeqStore_t,
5087                        *mut u32,
5088                        *const core::ffi::c_void,
5089                        size_t,
5090                    ) -> size_t,
5091            ),
5092            Some(ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT),
5093            Some(ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT),
5094            Some(ZSTD_COMPRESSBLOCK_LAZY_EXTDICT),
5095            Some(ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT),
5096            Some(ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT),
5097            Some(ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT),
5098            Some(ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT),
5099            Some(ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT),
5100        ],
5101        [
5102            Some(
5103                ZSTD_compressBlock_fast_dictMatchState
5104                    as unsafe fn(
5105                        &mut ZSTD_MatchState_t,
5106                        &mut SeqStore_t,
5107                        *mut u32,
5108                        *const core::ffi::c_void,
5109                        size_t,
5110                    ) -> size_t,
5111            ),
5112            Some(
5113                ZSTD_compressBlock_fast_dictMatchState
5114                    as unsafe fn(
5115                        &mut ZSTD_MatchState_t,
5116                        &mut SeqStore_t,
5117                        *mut u32,
5118                        *const core::ffi::c_void,
5119                        size_t,
5120                    ) -> size_t,
5121            ),
5122            Some(ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE),
5123            Some(ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE),
5124            Some(ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE),
5125            Some(ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE),
5126            Some(ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE),
5127            Some(ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE),
5128            Some(ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE),
5129            Some(ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE),
5130        ],
5131        [
5132            None,
5133            None,
5134            None,
5135            Some(ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH),
5136            Some(ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH),
5137            Some(ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH),
5138            None,
5139            None,
5140            None,
5141            None,
5142        ],
5143    ];
5144    let mut selectedCompressor: ZSTD_BlockCompressor_f = None;
5145    if ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder) != 0 {
5146        static rowBasedBlockCompressors: [[ZSTD_BlockCompressor_f; 3]; 4] = [
5147            [
5148                Some(ZSTD_COMPRESSBLOCK_GREEDY_ROW),
5149                Some(ZSTD_COMPRESSBLOCK_LAZY_ROW),
5150                Some(ZSTD_COMPRESSBLOCK_LAZY2_ROW),
5151            ],
5152            [
5153                Some(ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW),
5154                Some(ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW),
5155                Some(ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW),
5156            ],
5157            [
5158                Some(ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW),
5159                Some(ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW),
5160                Some(ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW),
5161            ],
5162            [
5163                Some(ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW),
5164                Some(ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW),
5165                Some(ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW),
5166            ],
5167        ];
5168        selectedCompressor = *(*rowBasedBlockCompressors
5169            .as_ptr()
5170            .offset(dictMode as core::ffi::c_int as isize))
5171        .as_ptr()
5172        .offset((strat as core::ffi::c_int - ZSTD_greedy as core::ffi::c_int) as isize);
5173    } else {
5174        selectedCompressor = *(*blockCompressor
5175            .as_ptr()
5176            .offset(dictMode as core::ffi::c_int as isize))
5177        .as_ptr()
5178        .offset(strat as core::ffi::c_int as isize);
5179    }
5180    selectedCompressor
5181}
5182unsafe fn ZSTD_storeLastLiterals(
5183    seqStorePtr: &mut SeqStore_t,
5184    anchor: *const u8,
5185    lastLLSize: size_t,
5186) {
5187    libc::memcpy(
5188        seqStorePtr.lit as *mut core::ffi::c_void,
5189        anchor as *const core::ffi::c_void,
5190        lastLLSize as libc::size_t,
5191    );
5192    seqStorePtr.lit = (seqStorePtr.lit).add(lastLLSize);
5193}
5194pub unsafe fn ZSTD_resetSeqStore(ssPtr: &mut SeqStore_t) {
5195    ssPtr.lit = ssPtr.litStart;
5196    ssPtr.sequences = ssPtr.sequencesStart;
5197    ssPtr.longLengthType = ZSTD_llt_none;
5198}
5199unsafe fn ZSTD_postProcessSequenceProducerResult(
5200    outSeqs: *mut ZSTD_Sequence,
5201    nbExternalSeqs: size_t,
5202    outSeqsCapacity: size_t,
5203    srcSize: size_t,
5204) -> size_t {
5205    if nbExternalSeqs > outSeqsCapacity {
5206        return Error::sequenceProducer_failed.to_error_code();
5207    }
5208    if nbExternalSeqs == 0 && srcSize > 0 {
5209        return Error::sequenceProducer_failed.to_error_code();
5210    }
5211    if srcSize == 0 {
5212        ptr::write_bytes(
5213            &mut *outSeqs as *mut ZSTD_Sequence as *mut u8,
5214            0,
5215            ::core::mem::size_of::<ZSTD_Sequence>(),
5216        );
5217        return 1;
5218    }
5219    let lastSeq = *outSeqs.add(nbExternalSeqs.wrapping_sub(1));
5220    if lastSeq.offset == 0 && lastSeq.matchLength == 0 {
5221        return nbExternalSeqs;
5222    }
5223    if nbExternalSeqs == outSeqsCapacity {
5224        return Error::sequenceProducer_failed.to_error_code();
5225    }
5226    ptr::write_bytes(
5227        &mut *outSeqs.add(nbExternalSeqs) as *mut ZSTD_Sequence as *mut u8,
5228        0,
5229        ::core::mem::size_of::<ZSTD_Sequence>(),
5230    );
5231    nbExternalSeqs.wrapping_add(1)
5232}
5233unsafe fn ZSTD_fastSequenceLengthSum(seqBuf: *const ZSTD_Sequence, seqBufSize: size_t) -> size_t {
5234    let mut matchLenSum: size_t = 0;
5235    let mut litLenSum: size_t = 0;
5236    let mut i: size_t = 0;
5237    matchLenSum = 0;
5238    litLenSum = 0;
5239    i = 0;
5240    while i < seqBufSize {
5241        litLenSum = litLenSum.wrapping_add((*seqBuf.add(i)).litLength as size_t);
5242        matchLenSum = matchLenSum.wrapping_add((*seqBuf.add(i)).matchLength as size_t);
5243        i = i.wrapping_add(1);
5244    }
5245    litLenSum.wrapping_add(matchLenSum)
5246}
5247
5248unsafe fn ZSTD_validateSeqStore(
5249    seqStore: *const SeqStore_t,
5250    cParams: *const ZSTD_compressionParameters,
5251) {
5252    let matchLenLowerBound = match (*cParams).minMatch {
5253        3 => 3,
5254        _ => 4,
5255    };
5256
5257    let start = (*seqStore).sequences;
5258    let end = (*seqStore).sequences;
5259
5260    if cfg!(debug_assertions) {
5261        for n in 0..end as usize - start as usize {
5262            let seqLength = ZSTD_getSequenceLength(seqStore, start.add(n));
5263            debug_assert!(seqLength.matchLength >= matchLenLowerBound);
5264        }
5265    }
5266}
5267unsafe fn ZSTD_buildSeqStore(
5268    zc: *mut ZSTD_CCtx,
5269    src: *const core::ffi::c_void,
5270    srcSize: size_t,
5271) -> size_t {
5272    let ms: &mut ZSTD_MatchState_t = &mut (*zc).blockState.matchState;
5273    ZSTD_assertEqualCParams((*zc).appliedParams.cParams, ms.cParams);
5274    if srcSize
5275        < (MIN_CBLOCK_SIZE as size_t)
5276            .wrapping_add(ZSTD_blockHeaderSize)
5277            .wrapping_add(1)
5278            .wrapping_add(1)
5279    {
5280        if (*zc).appliedParams.cParams.strategy as core::ffi::c_uint
5281            >= ZSTD_btopt as core::ffi::c_int as core::ffi::c_uint
5282        {
5283            ZSTD_ldm_skipRawSeqStoreBytes(&mut (*zc).externSeqStore, srcSize);
5284        } else {
5285            ZSTD_ldm_skipSequences(
5286                &mut (*zc).externSeqStore,
5287                srcSize,
5288                (*zc).appliedParams.cParams.minMatch,
5289            );
5290        }
5291        return ZSTDbss_noCompress as core::ffi::c_int as size_t;
5292    }
5293    ZSTD_resetSeqStore(&mut (*zc).seqStore);
5294    ms.opt.symbolCosts = &mut (*(*zc).blockState.prevCBlock).entropy;
5295    ms.opt.literalCompressionMode = (*zc).appliedParams.literalCompressionMode;
5296    let base = ms.window.base;
5297    let istart = src as *const u8;
5298    let curr = istart.wrapping_offset_from(base) as core::ffi::c_long as u32;
5299
5300    if size_of::<ptrdiff_t>() == 8 {
5301        assert!(istart.wrapping_offset_from(base) < u32::MAX as ptrdiff_t); /* ensure no overflow */
5302    }
5303
5304    if curr > (ms.nextToUpdate).wrapping_add(384) {
5305        ms.nextToUpdate = curr.wrapping_sub(Ord::min(
5306            192,
5307            curr.wrapping_sub(ms.nextToUpdate).wrapping_sub(384),
5308        ));
5309    }
5310
5311    /* select and store sequences */
5312    let dictMode = ZSTD_matchState_dictMode(ms);
5313    let mut lastLLSize: size_t = 0;
5314    let mut i: core::ffi::c_int = 0;
5315    i = 0;
5316    while i < ZSTD_REP_NUM {
5317        *((*(*zc).blockState.nextCBlock).rep)
5318            .as_mut_ptr()
5319            .offset(i as isize) = *((*(*zc).blockState.prevCBlock).rep)
5320            .as_mut_ptr()
5321            .offset(i as isize);
5322        i += 1;
5323    }
5324    if (*zc).externSeqStore.pos < (*zc).externSeqStore.size {
5325        if ZSTD_hasExtSeqProd(&(*zc).appliedParams) != 0 {
5326            return Error::parameter_combination_unsupported.to_error_code();
5327        }
5328        lastLLSize = ZSTD_ldm_blockCompress(
5329            &mut (*zc).externSeqStore,
5330            ms,
5331            &mut (*zc).seqStore,
5332            ((*(*zc).blockState.nextCBlock).rep).as_mut_ptr(),
5333            (*zc).appliedParams.useRowMatchFinder,
5334            src,
5335            srcSize,
5336        );
5337    } else if (*zc).appliedParams.ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
5338        let mut ldmSeqStore = kNullRawSeqStore;
5339        if ZSTD_hasExtSeqProd(&(*zc).appliedParams) != 0 {
5340            return Error::parameter_combination_unsupported.to_error_code();
5341        }
5342        ldmSeqStore.seq = (*zc).ldmSequences;
5343        ldmSeqStore.capacity = (*zc).maxNbLdmSequences;
5344        let err_code = ZSTD_ldm_generateSequences(
5345            &mut (*zc).ldmState,
5346            &mut ldmSeqStore,
5347            &(*zc).appliedParams.ldmParams,
5348            src,
5349            srcSize,
5350        );
5351        if ERR_isError(err_code) {
5352            return err_code;
5353        }
5354        lastLLSize = ZSTD_ldm_blockCompress(
5355            &mut ldmSeqStore,
5356            ms,
5357            &mut (*zc).seqStore,
5358            ((*(*zc).blockState.nextCBlock).rep).as_mut_ptr(),
5359            (*zc).appliedParams.useRowMatchFinder,
5360            src,
5361            srcSize,
5362        );
5363    } else if ZSTD_hasExtSeqProd(&(*zc).appliedParams) != 0 {
5364        let windowSize = (1) << (*zc).appliedParams.cParams.windowLog;
5365        let nbExternalSeqs = ((*zc).appliedParams.extSeqProdFunc).unwrap_unchecked()(
5366            (*zc).appliedParams.extSeqProdState,
5367            (*zc).extSeqBuf,
5368            (*zc).extSeqBufCapacity,
5369            src,
5370            srcSize,
5371            core::ptr::null(),
5372            0,
5373            (*zc).appliedParams.compressionLevel,
5374            windowSize as size_t,
5375        );
5376        let nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
5377            (*zc).extSeqBuf,
5378            nbExternalSeqs,
5379            (*zc).extSeqBufCapacity,
5380            srcSize,
5381        );
5382        if !ERR_isError(nbPostProcessedSeqs) {
5383            let mut seqPos = {
5384                ZSTD_SequencePosition {
5385                    idx: 0,
5386                    posInSequence: 0,
5387                    posInSrc: 0,
5388                }
5389            };
5390            let seqLenSum = ZSTD_fastSequenceLengthSum((*zc).extSeqBuf, nbPostProcessedSeqs);
5391            if seqLenSum > srcSize {
5392                return Error::externalSequences_invalid.to_error_code();
5393            }
5394            let err_code_0 = ZSTD_transferSequences_wBlockDelim(
5395                zc,
5396                &mut seqPos,
5397                (*zc).extSeqBuf,
5398                nbPostProcessedSeqs,
5399                src,
5400                srcSize,
5401                (*zc).appliedParams.searchForExternalRepcodes,
5402            );
5403            if ERR_isError(err_code_0) {
5404                return err_code_0;
5405            }
5406            ms.ldmSeqStore = core::ptr::null();
5407            return ZSTDbss_compress as core::ffi::c_int as size_t;
5408        }
5409        if (*zc).appliedParams.enableMatchFinderFallback == 0 {
5410            return nbPostProcessedSeqs;
5411        }
5412        let blockCompressor = ZSTD_selectBlockCompressor(
5413            (*zc).appliedParams.cParams.strategy,
5414            (*zc).appliedParams.useRowMatchFinder,
5415            dictMode,
5416        );
5417        ms.ldmSeqStore = core::ptr::null();
5418        lastLLSize = blockCompressor.unwrap_unchecked()(
5419            ms,
5420            &mut (*zc).seqStore,
5421            ((*(*zc).blockState.nextCBlock).rep).as_mut_ptr(),
5422            src,
5423            srcSize,
5424        );
5425    } else {
5426        let blockCompressor_0 = ZSTD_selectBlockCompressor(
5427            (*zc).appliedParams.cParams.strategy,
5428            (*zc).appliedParams.useRowMatchFinder,
5429            dictMode,
5430        );
5431        ms.ldmSeqStore = core::ptr::null();
5432        lastLLSize = blockCompressor_0.unwrap_unchecked()(
5433            ms,
5434            &mut (*zc).seqStore,
5435            ((*(*zc).blockState.nextCBlock).rep).as_mut_ptr(),
5436            src,
5437            srcSize,
5438        );
5439    }
5440    let lastLiterals = (src as *const u8)
5441        .add(srcSize)
5442        .offset(-(lastLLSize as isize));
5443    ZSTD_storeLastLiterals(&mut (*zc).seqStore, lastLiterals, lastLLSize);
5444    ZSTD_validateSeqStore(&(*zc).seqStore, &(*zc).appliedParams.cParams);
5445    ZSTDbss_compress as core::ffi::c_int as size_t
5446}
5447unsafe fn ZSTD_copyBlockSequences(
5448    seqCollector: *mut SeqCollector,
5449    seqStore: *const SeqStore_t,
5450    prevRepcodes: *const u32,
5451) -> size_t {
5452    let inSeqs: *const SeqDef = (*seqStore).sequencesStart;
5453    let nbInSequences = ((*seqStore).sequences).offset_from_unsigned(inSeqs);
5454    let nbInLiterals = ((*seqStore).lit).offset_from((*seqStore).litStart) as size_t;
5455    let outSeqs = if (*seqCollector).seqIndex == 0 {
5456        (*seqCollector).seqStart
5457    } else {
5458        ((*seqCollector).seqStart).add((*seqCollector).seqIndex)
5459    };
5460    let nbOutSequences = nbInSequences.wrapping_add(1);
5461    let mut nbOutLiterals = 0 as size_t;
5462    let mut repcodes = repcodes_s { rep: [0; 3] };
5463    let mut i: size_t = 0;
5464    if nbOutSequences > ((*seqCollector).maxSequences).wrapping_sub((*seqCollector).seqIndex) {
5465        return Error::dstSize_tooSmall.to_error_code();
5466    }
5467    libc::memcpy(
5468        &mut repcodes as *mut Repcodes_t as *mut core::ffi::c_void,
5469        prevRepcodes as *const core::ffi::c_void,
5470        ::core::mem::size_of::<Repcodes_t>(),
5471    );
5472    i = 0;
5473    while i < nbInSequences {
5474        let mut rawOffset: u32 = 0;
5475        (*outSeqs.add(i)).litLength = (*inSeqs.add(i)).litLength as core::ffi::c_uint;
5476        (*outSeqs.add(i)).matchLength =
5477            ((*inSeqs.add(i)).mlBase as core::ffi::c_int + MINMATCH) as core::ffi::c_uint;
5478        (*outSeqs.add(i)).rep = 0;
5479        if i == (*seqStore).longLengthPos as size_t {
5480            if (*seqStore).longLengthType == ZSTD_llt_literalLength {
5481                let fresh4 = &mut (*outSeqs.add(i)).litLength;
5482                *fresh4 = (*fresh4).wrapping_add(0x10000 as core::ffi::c_int as core::ffi::c_uint);
5483            } else if (*seqStore).longLengthType == ZSTD_llt_matchLength {
5484                let fresh5 = &mut (*outSeqs.add(i)).matchLength;
5485                *fresh5 = (*fresh5).wrapping_add(0x10000 as core::ffi::c_int as core::ffi::c_uint);
5486            }
5487        }
5488        if 1 <= (*inSeqs.add(i)).offBase && (*inSeqs.add(i)).offBase <= ZSTD_REP_NUM as u32 {
5489            let repcode = (*inSeqs.add(i)).offBase;
5490            (*outSeqs.add(i)).rep = repcode;
5491            if (*outSeqs.add(i)).litLength != 0 {
5492                rawOffset = *(repcodes.rep)
5493                    .as_mut_ptr()
5494                    .offset(repcode.wrapping_sub(1) as isize);
5495            } else if repcode == 3 {
5496                rawOffset = (*(repcodes.rep).as_mut_ptr()).wrapping_sub(1);
5497            } else {
5498                rawOffset = *(repcodes.rep).as_mut_ptr().offset(repcode as isize);
5499            }
5500        } else {
5501            rawOffset = ((*inSeqs.add(i)).offBase).wrapping_sub(ZSTD_REP_NUM as u32);
5502        }
5503        (*outSeqs.add(i)).offset = rawOffset;
5504        ZSTD_updateRep(
5505            (repcodes.rep).as_mut_ptr(),
5506            (*inSeqs.add(i)).offBase,
5507            ((*inSeqs.add(i)).litLength as core::ffi::c_int == 0) as core::ffi::c_int as u32,
5508        );
5509        nbOutLiterals = nbOutLiterals.wrapping_add((*outSeqs.add(i)).litLength as size_t);
5510        i = i.wrapping_add(1);
5511    }
5512    let lastLLSize = nbInLiterals.wrapping_sub(nbOutLiterals);
5513    (*outSeqs.add(nbInSequences)).litLength = lastLLSize as u32;
5514    (*outSeqs.add(nbInSequences)).matchLength = 0;
5515    (*outSeqs.add(nbInSequences)).offset = 0;
5516    (*seqCollector).seqIndex = ((*seqCollector).seqIndex).wrapping_add(nbOutSequences);
5517    0
5518}
5519#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_sequenceBound))]
5520pub unsafe extern "C" fn ZSTD_sequenceBound(srcSize: size_t) -> size_t {
5521    let maxNbSeq = (srcSize / ZSTD_MINMATCH_MIN as size_t).wrapping_add(1);
5522    let maxNbDelims = (srcSize / ZSTD_BLOCKSIZE_MAX_MIN as size_t).wrapping_add(1);
5523    maxNbSeq.wrapping_add(maxNbDelims)
5524}
5525#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_generateSequences))]
5526pub unsafe extern "C" fn ZSTD_generateSequences(
5527    zc: *mut ZSTD_CCtx,
5528    outSeqs: *mut ZSTD_Sequence,
5529    outSeqsSize: size_t,
5530    src: *const core::ffi::c_void,
5531    srcSize: size_t,
5532) -> size_t {
5533    let dstCapacity = ZSTD_compressBound(srcSize);
5534    let mut dst = core::ptr::null_mut::<core::ffi::c_void>();
5535    let mut seqCollector = SeqCollector {
5536        collectSequences: 0,
5537        seqStart: core::ptr::null_mut::<ZSTD_Sequence>(),
5538        seqIndex: 0,
5539        maxSequences: 0,
5540    };
5541    let mut targetCBlockSize: core::ffi::c_int = 0;
5542    let err_code = ZSTD_CCtx_getParameter(
5543        zc,
5544        ZSTD_cParameter::ZSTD_c_targetCBlockSize,
5545        &mut targetCBlockSize,
5546    );
5547    if ERR_isError(err_code) {
5548        return err_code;
5549    }
5550    if targetCBlockSize != 0 {
5551        return Error::parameter_unsupported.to_error_code();
5552    }
5553    let mut nbWorkers: core::ffi::c_int = 0;
5554    let err_code_0 = ZSTD_CCtx_getParameter(zc, ZSTD_cParameter::ZSTD_c_nbWorkers, &mut nbWorkers);
5555    if ERR_isError(err_code_0) {
5556        return err_code_0;
5557    }
5558    if nbWorkers != 0 {
5559        return Error::parameter_unsupported.to_error_code();
5560    }
5561    dst = ZSTD_customMalloc(dstCapacity, ZSTD_customMem::default());
5562    if dst.is_null() {
5563        return Error::memory_allocation.to_error_code();
5564    }
5565    seqCollector.collectSequences = 1;
5566    seqCollector.seqStart = outSeqs;
5567    seqCollector.seqIndex = 0;
5568    seqCollector.maxSequences = outSeqsSize;
5569    (*zc).seqCollector = seqCollector;
5570    let ret = ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
5571    ZSTD_customFree(dst, dstCapacity, ZSTD_customMem::default());
5572    let err_code_1 = ret;
5573    if ERR_isError(err_code_1) {
5574        return err_code_1;
5575    }
5576    (*zc).seqCollector.seqIndex
5577}
5578#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_mergeBlockDelimiters))]
5579pub unsafe extern "C" fn ZSTD_mergeBlockDelimiters(
5580    sequences: *mut ZSTD_Sequence,
5581    seqsSize: size_t,
5582) -> size_t {
5583    let mut in_0 = 0;
5584    let mut out = 0 as size_t;
5585    while in_0 < seqsSize {
5586        if (*sequences.add(in_0)).offset == 0 && (*sequences.add(in_0)).matchLength == 0 {
5587            if in_0 != seqsSize.wrapping_sub(1) {
5588                let fresh6 = &mut (*sequences.add(in_0.wrapping_add(1))).litLength;
5589                *fresh6 = (*fresh6).wrapping_add((*sequences.add(in_0)).litLength);
5590            }
5591        } else {
5592            *sequences.add(out) = *sequences.add(in_0);
5593            out = out.wrapping_add(1);
5594        }
5595        in_0 = in_0.wrapping_add(1);
5596    }
5597    out
5598}
5599unsafe fn ZSTD_isRLE(src: *const u8, length: size_t) -> core::ffi::c_int {
5600    let ip = src;
5601    let value = *ip;
5602    let valueST = (value as u64 as core::ffi::c_ulonglong)
5603        .wrapping_mul(0x101010101010101 as core::ffi::c_ulonglong) as size_t;
5604    let unrollSize = ::core::mem::size_of::<size_t>().wrapping_mul(4);
5605    let unrollMask = unrollSize.wrapping_sub(1);
5606    let prefixLength = length & unrollMask;
5607    let mut i: size_t = 0;
5608    if length == 1 {
5609        return 1;
5610    }
5611    if prefixLength != 0
5612        && ZSTD_count(ip.add(1), ip, ip.add(prefixLength)) != prefixLength.wrapping_sub(1)
5613    {
5614        return 0;
5615    }
5616    i = prefixLength;
5617    while i != length {
5618        let mut u: size_t = 0;
5619        u = 0;
5620        while u < unrollSize {
5621            if MEM_readST(ip.add(i).add(u) as *const core::ffi::c_void) != valueST {
5622                return 0;
5623            }
5624            u = (u as size_t).wrapping_add(::core::mem::size_of::<size_t>());
5625        }
5626        i = i.wrapping_add(unrollSize);
5627    }
5628    1
5629}
5630unsafe fn ZSTD_maybeRLE(seqStore: *const SeqStore_t) -> core::ffi::c_int {
5631    let nbSeqs = ((*seqStore).sequences).offset_from((*seqStore).sequencesStart) as size_t;
5632    let nbLits = ((*seqStore).lit).offset_from((*seqStore).litStart) as size_t;
5633    (nbSeqs < 4 && nbLits < 10) as core::ffi::c_int
5634}
5635unsafe fn ZSTD_blockState_confirmRepcodesAndEntropyTables(bs: *mut ZSTD_blockState_t) {
5636    core::mem::swap(&mut (*bs).prevCBlock, &mut (*bs).nextCBlock);
5637}
5638unsafe fn writeBlockHeader(
5639    op: *mut core::ffi::c_void,
5640    cSize: size_t,
5641    blockSize: size_t,
5642    lastBlock: u32,
5643) {
5644    let cBlockHeader = if cSize == 1 {
5645        lastBlock
5646            .wrapping_add((bt_rle as core::ffi::c_int as u32) << 1)
5647            .wrapping_add((blockSize << 3) as u32)
5648    } else {
5649        lastBlock
5650            .wrapping_add((bt_compressed as core::ffi::c_int as u32) << 1)
5651            .wrapping_add((cSize << 3) as u32)
5652    };
5653    MEM_writeLE24(op, cBlockHeader);
5654}
5655unsafe fn ZSTD_buildBlockEntropyStats_literals(
5656    src: *mut core::ffi::c_void,
5657    srcSize: size_t,
5658    prevHuf: *const ZSTD_hufCTables_t,
5659    nextHuf: *mut ZSTD_hufCTables_t,
5660    hufMetadata: *mut ZSTD_hufCTablesMetadata_t,
5661    literalsCompressionIsDisabled: core::ffi::c_int,
5662    workspace: *mut core::ffi::c_void,
5663    wkspSize: size_t,
5664    hufFlags: core::ffi::c_int,
5665) -> size_t {
5666    let wkspStart = workspace as *mut u8;
5667    let wkspEnd = wkspStart.add(wkspSize);
5668    let countWkspStart = wkspStart;
5669    let countWksp = workspace as *mut core::ffi::c_uint;
5670    let countWkspSize = ((HUF_SYMBOLVALUE_MAX + 1) as size_t)
5671        .wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>());
5672    let nodeWksp = countWkspStart.add(countWkspSize);
5673    let nodeWkspSize = wkspEnd.offset_from_unsigned(nodeWksp);
5674    let mut maxSymbolValue = HUF_SYMBOLVALUE_MAX;
5675    let mut huffLog = LitHufLog;
5676    let mut repeat = (*prevHuf).repeatMode;
5677    libc::memcpy(
5678        nextHuf as *mut core::ffi::c_void,
5679        prevHuf as *const core::ffi::c_void,
5680        ::core::mem::size_of::<ZSTD_hufCTables_t>(),
5681    );
5682    if literalsCompressionIsDisabled != 0 {
5683        (*hufMetadata).hType = set_basic;
5684        return 0;
5685    }
5686    let minLitSize = (if (*prevHuf).repeatMode as core::ffi::c_uint
5687        == HUF_repeat_valid as core::ffi::c_int as core::ffi::c_uint
5688    {
5689        6
5690    } else {
5691        COMPRESS_LITERALS_SIZE_MIN
5692    }) as size_t;
5693    if srcSize <= minLitSize {
5694        (*hufMetadata).hType = set_basic;
5695        return 0;
5696    }
5697    let largest = HIST_count_wksp(
5698        countWksp,
5699        &mut maxSymbolValue,
5700        src as *const u8 as *const core::ffi::c_void,
5701        srcSize,
5702        workspace,
5703        wkspSize,
5704    );
5705    let err_code = largest;
5706    if ERR_isError(err_code) {
5707        return err_code;
5708    }
5709    if largest == srcSize {
5710        (*hufMetadata).hType = set_rle;
5711        return 0;
5712    }
5713    if largest <= (srcSize >> 7).wrapping_add(4) {
5714        (*hufMetadata).hType = set_basic;
5715        return 0;
5716    }
5717    if repeat as core::ffi::c_uint == HUF_repeat_check as core::ffi::c_int as core::ffi::c_uint
5718        && HUF_validateCTable(((*prevHuf).CTable).as_ptr(), countWksp, maxSymbolValue) == 0
5719    {
5720        repeat = HUF_repeat_none;
5721    }
5722    ptr::write_bytes(
5723        ((*nextHuf).CTable).as_mut_ptr() as *mut u8,
5724        0,
5725        ::core::mem::size_of::<[HUF_CElt; 257]>(),
5726    );
5727    huffLog = HUF_optimalTableLog(
5728        huffLog,
5729        srcSize,
5730        maxSymbolValue,
5731        nodeWksp as *mut core::ffi::c_void,
5732        nodeWkspSize,
5733        ((*nextHuf).CTable).as_mut_ptr(),
5734        countWksp,
5735        hufFlags,
5736    );
5737    let maxBits = HUF_buildCTable_wksp(
5738        ((*nextHuf).CTable).as_mut_ptr(),
5739        countWksp,
5740        maxSymbolValue,
5741        huffLog,
5742        nodeWksp as *mut core::ffi::c_void,
5743        nodeWkspSize,
5744    );
5745    let err_code_0 = maxBits;
5746    if ERR_isError(err_code_0) {
5747        return err_code_0;
5748    }
5749    huffLog = maxBits as u32;
5750    let newCSize =
5751        HUF_estimateCompressedSize(((*nextHuf).CTable).as_mut_ptr(), countWksp, maxSymbolValue);
5752    let hSize = HUF_writeCTable_wksp(
5753        ((*hufMetadata).hufDesBuffer).as_mut_ptr() as *mut core::ffi::c_void,
5754        ::core::mem::size_of::<[u8; 128]>(),
5755        ((*nextHuf).CTable).as_mut_ptr(),
5756        maxSymbolValue,
5757        huffLog,
5758        nodeWksp as *mut core::ffi::c_void,
5759        nodeWkspSize,
5760    );
5761    if repeat as core::ffi::c_uint != HUF_repeat_none as core::ffi::c_int as core::ffi::c_uint {
5762        let oldCSize =
5763            HUF_estimateCompressedSize(((*prevHuf).CTable).as_ptr(), countWksp, maxSymbolValue);
5764        if oldCSize < srcSize
5765            && (oldCSize <= hSize.wrapping_add(newCSize) || hSize.wrapping_add(12) >= srcSize)
5766        {
5767            libc::memcpy(
5768                nextHuf as *mut core::ffi::c_void,
5769                prevHuf as *const core::ffi::c_void,
5770                ::core::mem::size_of::<ZSTD_hufCTables_t>(),
5771            );
5772            (*hufMetadata).hType = set_repeat;
5773            return 0;
5774        }
5775    }
5776    if newCSize.wrapping_add(hSize) >= srcSize {
5777        libc::memcpy(
5778            nextHuf as *mut core::ffi::c_void,
5779            prevHuf as *const core::ffi::c_void,
5780            ::core::mem::size_of::<ZSTD_hufCTables_t>(),
5781        );
5782        (*hufMetadata).hType = set_basic;
5783        return 0;
5784    }
5785    (*hufMetadata).hType = set_compressed;
5786    (*nextHuf).repeatMode = HUF_repeat_check;
5787    hSize
5788}
5789pub const COMPRESS_LITERALS_SIZE_MIN: core::ffi::c_int = 63;
5790unsafe fn ZSTD_buildDummySequencesStatistics(
5791    nextEntropy: *mut ZSTD_fseCTables_t,
5792) -> ZSTD_symbolEncodingTypeStats_t {
5793    let stats = {
5794        ZSTD_symbolEncodingTypeStats_t {
5795            LLtype: set_basic as core::ffi::c_int as u32,
5796            Offtype: set_basic as core::ffi::c_int as u32,
5797            MLtype: set_basic as core::ffi::c_int as u32,
5798            size: 0,
5799            lastCountSize: 0,
5800            longOffsets: 0,
5801        }
5802    };
5803    (*nextEntropy).litlength_repeatMode = FSE_repeat_none;
5804    (*nextEntropy).offcode_repeatMode = FSE_repeat_none;
5805    (*nextEntropy).matchlength_repeatMode = FSE_repeat_none;
5806    stats
5807}
5808unsafe fn ZSTD_buildBlockEntropyStats_sequences(
5809    seqStorePtr: *const SeqStore_t,
5810    prevEntropy: *const ZSTD_fseCTables_t,
5811    nextEntropy: *mut ZSTD_fseCTables_t,
5812    cctxParams: *const ZSTD_CCtx_params,
5813    fseMetadata: *mut ZSTD_fseCTablesMetadata_t,
5814    workspace: *mut core::ffi::c_void,
5815    wkspSize: size_t,
5816) -> size_t {
5817    let strategy = (*cctxParams).cParams.strategy;
5818    let nbSeq = ((*seqStorePtr).sequences).offset_from((*seqStorePtr).sequencesStart) as size_t;
5819    let ostart = ((*fseMetadata).fseTablesBuffer).as_mut_ptr();
5820    let oend = ostart.add(::core::mem::size_of::<[u8; 133]>());
5821    let op = ostart;
5822    let countWorkspace = workspace as *mut core::ffi::c_uint;
5823    let entropyWorkspace = countWorkspace.offset(((if 35 > 52 { 35 } else { 52 }) + 1) as isize);
5824    let entropyWorkspaceSize = wkspSize.wrapping_sub(
5825        ((if 35 > 52 { 35 as size_t } else { 52 }) + 1)
5826            .wrapping_mul(::core::mem::size_of::<core::ffi::c_uint>()),
5827    );
5828    let mut stats = ZSTD_symbolEncodingTypeStats_t {
5829        LLtype: 0,
5830        Offtype: 0,
5831        MLtype: 0,
5832        size: 0,
5833        lastCountSize: 0,
5834        longOffsets: 0,
5835    };
5836    stats = if nbSeq != 0 {
5837        ZSTD_buildSequencesStatistics(
5838            seqStorePtr,
5839            nbSeq,
5840            prevEntropy,
5841            nextEntropy,
5842            op,
5843            oend,
5844            strategy,
5845            countWorkspace,
5846            entropyWorkspace as *mut core::ffi::c_void,
5847            entropyWorkspaceSize,
5848        )
5849    } else {
5850        ZSTD_buildDummySequencesStatistics(nextEntropy)
5851    };
5852    let err_code = stats.size;
5853    if ERR_isError(err_code) {
5854        return err_code;
5855    }
5856    (*fseMetadata).llType = stats.LLtype as SymbolEncodingType_e;
5857    (*fseMetadata).ofType = stats.Offtype as SymbolEncodingType_e;
5858    (*fseMetadata).mlType = stats.MLtype as SymbolEncodingType_e;
5859    (*fseMetadata).lastCountSize = stats.lastCountSize;
5860    stats.size
5861}
5862pub unsafe fn ZSTD_buildBlockEntropyStats(
5863    seqStorePtr: *const SeqStore_t,
5864    prevEntropy: *const ZSTD_entropyCTables_t,
5865    nextEntropy: *mut ZSTD_entropyCTables_t,
5866    cctxParams: *const ZSTD_CCtx_params,
5867    entropyMetadata: *mut ZSTD_entropyCTablesMetadata_t,
5868    workspace: *mut core::ffi::c_void,
5869    wkspSize: size_t,
5870) -> size_t {
5871    let litSize = ((*seqStorePtr).lit).offset_from((*seqStorePtr).litStart) as size_t;
5872    let huf_useOptDepth = ((*cctxParams).cParams.strategy as core::ffi::c_uint
5873        >= HUF_OPTIMAL_DEPTH_THRESHOLD as core::ffi::c_uint)
5874        as core::ffi::c_int;
5875    let hufFlags = if huf_useOptDepth != 0 {
5876        HUF_flags_optimalDepth as core::ffi::c_int
5877    } else {
5878        0
5879    };
5880    (*entropyMetadata).hufMetadata.hufDesSize = ZSTD_buildBlockEntropyStats_literals(
5881        (*seqStorePtr).litStart as *mut core::ffi::c_void,
5882        litSize,
5883        &(*prevEntropy).huf,
5884        &mut (*nextEntropy).huf,
5885        &mut (*entropyMetadata).hufMetadata,
5886        ZSTD_literalsCompressionIsDisabled(cctxParams),
5887        workspace,
5888        wkspSize,
5889        hufFlags,
5890    );
5891    let err_code = (*entropyMetadata).hufMetadata.hufDesSize;
5892    if ERR_isError(err_code) {
5893        return err_code;
5894    }
5895    (*entropyMetadata).fseMetadata.fseTablesSize = ZSTD_buildBlockEntropyStats_sequences(
5896        seqStorePtr,
5897        &(*prevEntropy).fse,
5898        &mut (*nextEntropy).fse,
5899        cctxParams,
5900        &mut (*entropyMetadata).fseMetadata,
5901        workspace,
5902        wkspSize,
5903    );
5904    let err_code_0 = (*entropyMetadata).fseMetadata.fseTablesSize;
5905    if ERR_isError(err_code_0) {
5906        return err_code_0;
5907    }
5908    0
5909}
5910unsafe fn ZSTD_estimateBlockSize_literal(
5911    literals: *const u8,
5912    litSize: size_t,
5913    huf: *const ZSTD_hufCTables_t,
5914    hufMetadata: *const ZSTD_hufCTablesMetadata_t,
5915    workspace: *mut core::ffi::c_void,
5916    wkspSize: size_t,
5917    writeEntropy: core::ffi::c_int,
5918) -> size_t {
5919    let countWksp = workspace as *mut core::ffi::c_uint;
5920    let mut maxSymbolValue = HUF_SYMBOLVALUE_MAX;
5921    let literalSectionHeaderSize =
5922        (3 + (litSize >= ((1) << 10) as size_t) as core::ffi::c_int
5923            + (litSize >= (16 * ((1) << 10)) as size_t) as core::ffi::c_int) as size_t;
5924    let singleStream = (litSize < 256) as core::ffi::c_int as u32;
5925    if (*hufMetadata).hType as core::ffi::c_uint
5926        == set_basic as core::ffi::c_int as core::ffi::c_uint
5927    {
5928        return litSize;
5929    } else if (*hufMetadata).hType as core::ffi::c_uint
5930        == set_rle as core::ffi::c_int as core::ffi::c_uint
5931    {
5932        return 1;
5933    } else if (*hufMetadata).hType as core::ffi::c_uint
5934        == set_compressed as core::ffi::c_int as core::ffi::c_uint
5935        || (*hufMetadata).hType as core::ffi::c_uint
5936            == set_repeat as core::ffi::c_int as core::ffi::c_uint
5937    {
5938        let largest = HIST_count_wksp(
5939            countWksp,
5940            &mut maxSymbolValue,
5941            literals as *const core::ffi::c_void,
5942            litSize,
5943            workspace,
5944            wkspSize,
5945        );
5946        if ERR_isError(largest) {
5947            return litSize;
5948        }
5949        let mut cLitSizeEstimate =
5950            HUF_estimateCompressedSize(((*huf).CTable).as_ptr(), countWksp, maxSymbolValue);
5951        if writeEntropy != 0 {
5952            cLitSizeEstimate = cLitSizeEstimate.wrapping_add((*hufMetadata).hufDesSize);
5953        }
5954        if singleStream == 0 {
5955            cLitSizeEstimate = cLitSizeEstimate.wrapping_add(6);
5956        }
5957        return cLitSizeEstimate.wrapping_add(literalSectionHeaderSize);
5958    }
5959    0
5960}
5961unsafe fn ZSTD_estimateBlockSize_symbolType(
5962    type_0: SymbolEncodingType_e,
5963    codeTable: *const u8,
5964    nbSeq: size_t,
5965    maxCode: core::ffi::c_uint,
5966    fseCTable: *const FSE_CTable,
5967    additionalBits: *const u8,
5968    defaultNorm: *const core::ffi::c_short,
5969    defaultNormLog: u32,
5970    defaultMax: u32,
5971    workspace: *mut core::ffi::c_void,
5972    wkspSize: size_t,
5973) -> size_t {
5974    let countWksp = workspace as *mut core::ffi::c_uint;
5975    let mut ctp = codeTable;
5976    let ctStart = ctp;
5977    let ctEnd = ctStart.add(nbSeq);
5978    let mut cSymbolTypeSizeEstimateInBits = 0;
5979    let mut max = maxCode;
5980    HIST_countFast_wksp(
5981        countWksp,
5982        &mut max,
5983        codeTable as *const core::ffi::c_void,
5984        nbSeq,
5985        workspace,
5986        wkspSize,
5987    );
5988    if type_0 as core::ffi::c_uint == set_basic as core::ffi::c_int as core::ffi::c_uint {
5989        /* We selected this encoding type, so it must be valid. */
5990        assert!(max <= defaultMax);
5991
5992        cSymbolTypeSizeEstimateInBits =
5993            ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);
5994    } else if type_0 as core::ffi::c_uint == set_rle as core::ffi::c_int as core::ffi::c_uint {
5995        cSymbolTypeSizeEstimateInBits = 0;
5996    } else if type_0 as core::ffi::c_uint == set_compressed as core::ffi::c_int as core::ffi::c_uint
5997        || type_0 as core::ffi::c_uint == set_repeat as core::ffi::c_int as core::ffi::c_uint
5998    {
5999        cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
6000    }
6001    if ERR_isError(cSymbolTypeSizeEstimateInBits) {
6002        return nbSeq * 10;
6003    }
6004    while ctp < ctEnd {
6005        if !additionalBits.is_null() {
6006            cSymbolTypeSizeEstimateInBits = cSymbolTypeSizeEstimateInBits
6007                .wrapping_add(*additionalBits.offset(*ctp as isize) as size_t);
6008        } else {
6009            cSymbolTypeSizeEstimateInBits =
6010                cSymbolTypeSizeEstimateInBits.wrapping_add(*ctp as size_t);
6011        }
6012        ctp = ctp.add(1);
6013    }
6014    cSymbolTypeSizeEstimateInBits >> 3
6015}
6016unsafe fn ZSTD_estimateBlockSize_sequences(
6017    ofCodeTable: *const u8,
6018    llCodeTable: *const u8,
6019    mlCodeTable: *const u8,
6020    nbSeq: size_t,
6021    fseTables: *const ZSTD_fseCTables_t,
6022    fseMetadata: *const ZSTD_fseCTablesMetadata_t,
6023    workspace: *mut core::ffi::c_void,
6024    wkspSize: size_t,
6025    writeEntropy: core::ffi::c_int,
6026) -> size_t {
6027    let sequencesSectionHeaderSize =
6028        (1 + 1
6029            + (nbSeq >= 128) as core::ffi::c_int
6030            + (nbSeq >= LONGNBSEQ as size_t) as core::ffi::c_int) as size_t;
6031    let mut cSeqSizeEstimate = 0 as size_t;
6032    cSeqSizeEstimate = cSeqSizeEstimate.wrapping_add(ZSTD_estimateBlockSize_symbolType(
6033        (*fseMetadata).ofType,
6034        ofCodeTable,
6035        nbSeq,
6036        MaxOff,
6037        ((*fseTables).offcodeCTable).as_ptr(),
6038        core::ptr::null(),
6039        OF_defaultNorm.as_ptr(),
6040        OF_defaultNormLog,
6041        DefaultMaxOff,
6042        workspace,
6043        wkspSize,
6044    ));
6045    cSeqSizeEstimate = cSeqSizeEstimate.wrapping_add(ZSTD_estimateBlockSize_symbolType(
6046        (*fseMetadata).llType,
6047        llCodeTable,
6048        nbSeq,
6049        MaxLL,
6050        ((*fseTables).litlengthCTable).as_ptr(),
6051        LL_bits.as_ptr(),
6052        LL_defaultNorm.as_ptr(),
6053        LL_defaultNormLog,
6054        MaxLL,
6055        workspace,
6056        wkspSize,
6057    ));
6058    cSeqSizeEstimate = cSeqSizeEstimate.wrapping_add(ZSTD_estimateBlockSize_symbolType(
6059        (*fseMetadata).mlType,
6060        mlCodeTable,
6061        nbSeq,
6062        MaxML,
6063        ((*fseTables).matchlengthCTable).as_ptr(),
6064        ML_bits.as_ptr(),
6065        ML_defaultNorm.as_ptr(),
6066        ML_defaultNormLog,
6067        MaxML,
6068        workspace,
6069        wkspSize,
6070    ));
6071    if writeEntropy != 0 {
6072        cSeqSizeEstimate = cSeqSizeEstimate.wrapping_add((*fseMetadata).fseTablesSize);
6073    }
6074    cSeqSizeEstimate.wrapping_add(sequencesSectionHeaderSize)
6075}
6076unsafe fn ZSTD_estimateBlockSize(
6077    literals: *const u8,
6078    litSize: size_t,
6079    ofCodeTable: *const u8,
6080    llCodeTable: *const u8,
6081    mlCodeTable: *const u8,
6082    nbSeq: size_t,
6083    entropy: *const ZSTD_entropyCTables_t,
6084    entropyMetadata: *const ZSTD_entropyCTablesMetadata_t,
6085    workspace: *mut core::ffi::c_void,
6086    wkspSize: size_t,
6087    writeLitEntropy: core::ffi::c_int,
6088    writeSeqEntropy: core::ffi::c_int,
6089) -> size_t {
6090    let literalsSize = ZSTD_estimateBlockSize_literal(
6091        literals,
6092        litSize,
6093        &(*entropy).huf,
6094        &(*entropyMetadata).hufMetadata,
6095        workspace,
6096        wkspSize,
6097        writeLitEntropy,
6098    );
6099    let seqSize = ZSTD_estimateBlockSize_sequences(
6100        ofCodeTable,
6101        llCodeTable,
6102        mlCodeTable,
6103        nbSeq,
6104        &(*entropy).fse,
6105        &(*entropyMetadata).fseMetadata,
6106        workspace,
6107        wkspSize,
6108        writeSeqEntropy,
6109    );
6110    seqSize
6111        .wrapping_add(literalsSize)
6112        .wrapping_add(ZSTD_blockHeaderSize)
6113}
6114unsafe fn ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(
6115    seqStore: &mut SeqStore_t,
6116    zc: *mut ZSTD_CCtx,
6117) -> size_t {
6118    let entropyMetadata: *mut ZSTD_entropyCTablesMetadata_t =
6119        &mut (*zc).blockSplitCtx.entropyMetadata;
6120    let err_code = ZSTD_buildBlockEntropyStats(
6121        seqStore,
6122        &(*(*zc).blockState.prevCBlock).entropy,
6123        &mut (*(*zc).blockState.nextCBlock).entropy,
6124        &(*zc).appliedParams,
6125        entropyMetadata,
6126        (*zc).tmpWorkspace,
6127        (*zc).tmpWkspSize,
6128    );
6129    if ERR_isError(err_code) {
6130        return err_code;
6131    }
6132    ZSTD_estimateBlockSize(
6133        seqStore.litStart,
6134        (seqStore.lit).offset_from_unsigned(seqStore.litStart),
6135        seqStore.ofCode,
6136        seqStore.llCode,
6137        seqStore.mlCode,
6138        (seqStore.sequences).offset_from(seqStore.sequencesStart) as core::ffi::c_long as size_t,
6139        &(*(*zc).blockState.nextCBlock).entropy,
6140        entropyMetadata,
6141        (*zc).tmpWorkspace,
6142        (*zc).tmpWkspSize,
6143        ((*entropyMetadata).hufMetadata.hType as core::ffi::c_uint
6144            == set_compressed as core::ffi::c_int as core::ffi::c_uint) as core::ffi::c_int,
6145        1,
6146    )
6147}
6148unsafe fn ZSTD_countSeqStoreLiteralsBytes(seqStore: *const SeqStore_t) -> size_t {
6149    let mut literalsBytes = 0 as size_t;
6150    let nbSeqs = ((*seqStore).sequences).offset_from((*seqStore).sequencesStart) as size_t;
6151    let mut i: size_t = 0;
6152    i = 0;
6153    while i < nbSeqs {
6154        let seq = *((*seqStore).sequencesStart).add(i);
6155        literalsBytes = literalsBytes.wrapping_add(seq.litLength as size_t);
6156        if i == (*seqStore).longLengthPos as size_t
6157            && (*seqStore).longLengthType == ZSTD_llt_literalLength
6158        {
6159            literalsBytes = literalsBytes.wrapping_add(0x10000 as core::ffi::c_int as size_t);
6160        }
6161        i = i.wrapping_add(1);
6162    }
6163    literalsBytes
6164}
6165unsafe fn ZSTD_countSeqStoreMatchBytes(seqStore: *const SeqStore_t) -> size_t {
6166    let mut matchBytes = 0 as size_t;
6167    let nbSeqs = ((*seqStore).sequences).offset_from((*seqStore).sequencesStart) as size_t;
6168    let mut i: size_t = 0;
6169    i = 0;
6170    while i < nbSeqs {
6171        let seq = *((*seqStore).sequencesStart).add(i);
6172        matchBytes = matchBytes.wrapping_add((seq.mlBase as core::ffi::c_int + MINMATCH) as size_t);
6173        if i == (*seqStore).longLengthPos as size_t
6174            && (*seqStore).longLengthType == ZSTD_llt_matchLength
6175        {
6176            matchBytes = matchBytes.wrapping_add(0x10000 as core::ffi::c_int as size_t);
6177        }
6178        i = i.wrapping_add(1);
6179    }
6180    matchBytes
6181}
6182unsafe fn ZSTD_deriveSeqStoreChunk(
6183    resultSeqStore: &mut SeqStore_t,
6184    originalSeqStore: *const SeqStore_t,
6185    startIdx: size_t,
6186    endIdx: size_t,
6187) {
6188    *resultSeqStore = *originalSeqStore;
6189    if startIdx > 0 {
6190        resultSeqStore.sequences = ((*originalSeqStore).sequencesStart).add(startIdx);
6191        resultSeqStore.litStart =
6192            (resultSeqStore.litStart).add(ZSTD_countSeqStoreLiteralsBytes(resultSeqStore));
6193    }
6194    if (*originalSeqStore).longLengthType != ZSTD_llt_none {
6195        if ((*originalSeqStore).longLengthPos as size_t) < startIdx
6196            || (*originalSeqStore).longLengthPos as size_t > endIdx
6197        {
6198            resultSeqStore.longLengthType = ZSTD_llt_none;
6199        } else {
6200            resultSeqStore.longLengthPos =
6201                (resultSeqStore.longLengthPos).wrapping_sub(startIdx as u32);
6202        }
6203    }
6204    resultSeqStore.sequencesStart = ((*originalSeqStore).sequencesStart).add(startIdx);
6205    resultSeqStore.sequences = ((*originalSeqStore).sequencesStart).add(endIdx);
6206    if endIdx
6207        != ((*originalSeqStore).sequences).offset_from((*originalSeqStore).sequencesStart) as size_t
6208    {
6209        let literalsBytes = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
6210        resultSeqStore.lit = (resultSeqStore.litStart).add(literalsBytes);
6211    }
6212    resultSeqStore.llCode = (resultSeqStore.llCode).add(startIdx);
6213    resultSeqStore.mlCode = (resultSeqStore.mlCode).add(startIdx);
6214    resultSeqStore.ofCode = (resultSeqStore.ofCode).add(startIdx);
6215}
6216unsafe fn ZSTD_resolveRepcodeToRawOffset(rep: *const u32, offBase: u32, ll0: u32) -> u32 {
6217    let adjustedRepCode = offBase.wrapping_sub(1).wrapping_add(ll0);
6218    if adjustedRepCode == ZSTD_REP_NUM as u32 {
6219        return (*rep).wrapping_sub(1);
6220    }
6221    *rep.offset(adjustedRepCode as isize)
6222}
6223unsafe fn ZSTD_seqStore_resolveOffCodes(
6224    dRepcodes: *mut Repcodes_t,
6225    cRepcodes: *mut Repcodes_t,
6226    seqStore: *const SeqStore_t,
6227    nbSeq: u32,
6228) {
6229    let mut idx = 0;
6230    let longLitLenIdx = if (*seqStore).longLengthType == ZSTD_llt_literalLength {
6231        (*seqStore).longLengthPos
6232    } else {
6233        nbSeq
6234    };
6235    while idx < nbSeq {
6236        let seq = ((*seqStore).sequencesStart).offset(idx as isize);
6237        let ll0 = ((*seq).litLength as core::ffi::c_int == 0 && idx != longLitLenIdx)
6238            as core::ffi::c_int as u32;
6239        let offBase = (*seq).offBase;
6240        if 1 <= offBase && offBase <= ZSTD_REP_NUM as u32 {
6241            let dRawOffset = ZSTD_resolveRepcodeToRawOffset(
6242                ((*dRepcodes).rep).as_mut_ptr() as *const u32,
6243                offBase,
6244                ll0,
6245            );
6246            let cRawOffset = ZSTD_resolveRepcodeToRawOffset(
6247                ((*cRepcodes).rep).as_mut_ptr() as *const u32,
6248                offBase,
6249                ll0,
6250            );
6251            if dRawOffset != cRawOffset {
6252                (*seq).offBase = cRawOffset.wrapping_add(ZSTD_REP_NUM as u32);
6253            }
6254        }
6255        ZSTD_updateRep(((*dRepcodes).rep).as_mut_ptr(), (*seq).offBase, ll0);
6256        ZSTD_updateRep(((*cRepcodes).rep).as_mut_ptr(), offBase, ll0);
6257        idx = idx.wrapping_add(1);
6258    }
6259}
6260unsafe fn ZSTD_compressSeqStore_singleBlock(
6261    zc: *mut ZSTD_CCtx,
6262    seqStore: *const SeqStore_t,
6263    dRep: *mut Repcodes_t,
6264    cRep: *mut Repcodes_t,
6265    dst: *mut core::ffi::c_void,
6266    dstCapacity: size_t,
6267    src: *const core::ffi::c_void,
6268    srcSize: size_t,
6269    lastBlock: u32,
6270    isPartition: u32,
6271) -> size_t {
6272    let rleMaxLength = 25;
6273    let op = dst as *mut u8;
6274    let ip = src as *const u8;
6275    let mut cSize: size_t = 0;
6276    let mut cSeqsSize: size_t = 0;
6277    let dRepOriginal = *dRep;
6278    if isPartition != 0 {
6279        ZSTD_seqStore_resolveOffCodes(
6280            dRep,
6281            cRep,
6282            seqStore,
6283            ((*seqStore).sequences).offset_from((*seqStore).sequencesStart) as core::ffi::c_long
6284                as u32,
6285        );
6286    }
6287    if dstCapacity < ZSTD_blockHeaderSize {
6288        return Error::dstSize_tooSmall.to_error_code();
6289    }
6290    cSeqsSize = ZSTD_entropyCompressSeqStore(
6291        seqStore,
6292        &(*(*zc).blockState.prevCBlock).entropy,
6293        &mut (*(*zc).blockState.nextCBlock).entropy,
6294        &(*zc).appliedParams,
6295        op.add(ZSTD_blockHeaderSize) as *mut core::ffi::c_void,
6296        dstCapacity.wrapping_sub(ZSTD_blockHeaderSize),
6297        srcSize,
6298        (*zc).tmpWorkspace,
6299        (*zc).tmpWkspSize,
6300        (*zc).bmi2,
6301    );
6302    let err_code = cSeqsSize;
6303    if ERR_isError(err_code) {
6304        return err_code;
6305    }
6306    if (*zc).isFirstBlock == 0
6307        && cSeqsSize < rleMaxLength as size_t
6308        && ZSTD_isRLE(src as *const u8, srcSize) != 0
6309    {
6310        cSeqsSize = 1;
6311    }
6312    if (*zc).seqCollector.collectSequences != 0 {
6313        let err_code_0 = ZSTD_copyBlockSequences(
6314            &mut (*zc).seqCollector,
6315            seqStore,
6316            (dRepOriginal.rep).as_ptr(),
6317        );
6318        if ERR_isError(err_code_0) {
6319            return err_code_0;
6320        }
6321        ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*zc).blockState);
6322        return 0;
6323    }
6324    if cSeqsSize == 0 {
6325        cSize = ZSTD_noCompressBlock(
6326            op as *mut core::ffi::c_void,
6327            dstCapacity,
6328            ip as *const core::ffi::c_void,
6329            srcSize,
6330            lastBlock,
6331        );
6332        let err_code_1 = cSize;
6333        if ERR_isError(err_code_1) {
6334            return err_code_1;
6335        }
6336        *dRep = dRepOriginal;
6337    } else if cSeqsSize == 1 {
6338        cSize = ZSTD_rleCompressBlock(
6339            op as *mut core::ffi::c_void,
6340            dstCapacity,
6341            *ip,
6342            srcSize,
6343            lastBlock,
6344        );
6345        let err_code_2 = cSize;
6346        if ERR_isError(err_code_2) {
6347            return err_code_2;
6348        }
6349        *dRep = dRepOriginal;
6350    } else {
6351        ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*zc).blockState);
6352        writeBlockHeader(op as *mut core::ffi::c_void, cSeqsSize, srcSize, lastBlock);
6353        cSize = ZSTD_blockHeaderSize.wrapping_add(cSeqsSize);
6354    }
6355    if (*(*zc).blockState.prevCBlock)
6356        .entropy
6357        .fse
6358        .offcode_repeatMode as core::ffi::c_uint
6359        == FSE_repeat_valid as core::ffi::c_int as core::ffi::c_uint
6360    {
6361        (*(*zc).blockState.prevCBlock)
6362            .entropy
6363            .fse
6364            .offcode_repeatMode = FSE_repeat_check;
6365    }
6366    cSize
6367}
6368pub const MIN_SEQUENCES_BLOCK_SPLITTING: core::ffi::c_int = 300;
6369unsafe fn ZSTD_deriveBlockSplitsHelper(
6370    splits: *mut seqStoreSplits,
6371    startIdx: size_t,
6372    endIdx: size_t,
6373    zc: *mut ZSTD_CCtx,
6374    origSeqStore: *const SeqStore_t,
6375) {
6376    let fullSeqStoreChunk: &mut SeqStore_t = &mut (*zc).blockSplitCtx.fullSeqStoreChunk;
6377    let firstHalfSeqStore: &mut SeqStore_t = &mut (*zc).blockSplitCtx.firstHalfSeqStore;
6378    let secondHalfSeqStore: &mut SeqStore_t = &mut (*zc).blockSplitCtx.secondHalfSeqStore;
6379    let mut estimatedOriginalSize: size_t = 0;
6380    let mut estimatedFirstHalfSize: size_t = 0;
6381    let mut estimatedSecondHalfSize: size_t = 0;
6382    let midIdx = startIdx.wrapping_add(endIdx) / 2;
6383    if endIdx.wrapping_sub(startIdx) < MIN_SEQUENCES_BLOCK_SPLITTING as size_t
6384        || (*splits).idx >= ZSTD_MAX_NB_BLOCK_SPLITS as size_t
6385    {
6386        return;
6387    }
6388    ZSTD_deriveSeqStoreChunk(fullSeqStoreChunk, origSeqStore, startIdx, endIdx);
6389    ZSTD_deriveSeqStoreChunk(firstHalfSeqStore, origSeqStore, startIdx, midIdx);
6390    ZSTD_deriveSeqStoreChunk(secondHalfSeqStore, origSeqStore, midIdx, endIdx);
6391    estimatedOriginalSize =
6392        ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(fullSeqStoreChunk, zc);
6393    estimatedFirstHalfSize =
6394        ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(firstHalfSeqStore, zc);
6395    estimatedSecondHalfSize =
6396        ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(secondHalfSeqStore, zc);
6397    if ERR_isError(estimatedOriginalSize)
6398        || ERR_isError(estimatedFirstHalfSize)
6399        || ERR_isError(estimatedSecondHalfSize)
6400    {
6401        return;
6402    }
6403    if estimatedFirstHalfSize.wrapping_add(estimatedSecondHalfSize) < estimatedOriginalSize {
6404        ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);
6405        *((*splits).splitLocations).add((*splits).idx) = midIdx as u32;
6406        (*splits).idx = ((*splits).idx).wrapping_add(1);
6407        ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);
6408    }
6409}
6410unsafe fn ZSTD_deriveBlockSplits(zc: *mut ZSTD_CCtx, partitions: *mut u32, nbSeq: u32) -> size_t {
6411    let mut splits = seqStoreSplits {
6412        splitLocations: core::ptr::null_mut::<u32>(),
6413        idx: 0,
6414    };
6415    splits.splitLocations = partitions;
6416    splits.idx = 0;
6417    if nbSeq <= 4 {
6418        return 0;
6419    }
6420    ZSTD_deriveBlockSplitsHelper(&mut splits, 0, nbSeq as size_t, zc, &(*zc).seqStore);
6421    *(splits.splitLocations).add(splits.idx) = nbSeq;
6422    splits.idx
6423}
6424unsafe fn ZSTD_compressBlock_splitBlock_internal(
6425    zc: *mut ZSTD_CCtx,
6426    dst: *mut core::ffi::c_void,
6427    mut dstCapacity: size_t,
6428    src: *const core::ffi::c_void,
6429    blockSize: size_t,
6430    lastBlock: u32,
6431    nbSeq: u32,
6432) -> size_t {
6433    let mut cSize = 0 as size_t;
6434    let mut ip = src as *const u8;
6435    let mut op = dst as *mut u8;
6436    let mut i = 0;
6437    let mut srcBytesTotal = 0 as size_t;
6438    let partitions = ((*zc).blockSplitCtx.partitions).as_mut_ptr();
6439    let nextSeqStore: &mut SeqStore_t = &mut (*zc).blockSplitCtx.nextSeqStore;
6440    let currSeqStore: &mut SeqStore_t = &mut (*zc).blockSplitCtx.currSeqStore;
6441    let numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
6442    let mut dRep = repcodes_s { rep: [0; 3] };
6443    let mut cRep = repcodes_s { rep: [0; 3] };
6444    libc::memcpy(
6445        (dRep.rep).as_mut_ptr() as *mut core::ffi::c_void,
6446        ((*(*zc).blockState.prevCBlock).rep).as_mut_ptr() as *const core::ffi::c_void,
6447        ::core::mem::size_of::<Repcodes_t>(),
6448    );
6449    libc::memcpy(
6450        (cRep.rep).as_mut_ptr() as *mut core::ffi::c_void,
6451        ((*(*zc).blockState.prevCBlock).rep).as_mut_ptr() as *const core::ffi::c_void,
6452        ::core::mem::size_of::<Repcodes_t>(),
6453    );
6454    ptr::write_bytes(
6455        nextSeqStore as *mut SeqStore_t as *mut u8,
6456        0,
6457        ::core::mem::size_of::<SeqStore_t>(),
6458    );
6459    if numSplits == 0 {
6460        let cSizeSingleBlock = ZSTD_compressSeqStore_singleBlock(
6461            zc,
6462            &(*zc).seqStore,
6463            &mut dRep,
6464            &mut cRep,
6465            op as *mut core::ffi::c_void,
6466            dstCapacity,
6467            ip as *const core::ffi::c_void,
6468            blockSize,
6469            lastBlock,
6470            0,
6471        );
6472        let err_code = cSizeSingleBlock;
6473        if ERR_isError(err_code) {
6474            return err_code;
6475        }
6476        return cSizeSingleBlock;
6477    }
6478    ZSTD_deriveSeqStoreChunk(currSeqStore, &(*zc).seqStore, 0, *partitions as size_t);
6479    i = 0;
6480    while i <= numSplits {
6481        let mut cSizeChunk: size_t = 0;
6482        let lastPartition = (i == numSplits) as core::ffi::c_int as u32;
6483        let mut lastBlockEntireSrc = 0;
6484        let mut srcBytes = (ZSTD_countSeqStoreLiteralsBytes(currSeqStore))
6485            .wrapping_add(ZSTD_countSeqStoreMatchBytes(currSeqStore));
6486        srcBytesTotal = srcBytesTotal.wrapping_add(srcBytes);
6487        if lastPartition != 0 {
6488            srcBytes = srcBytes.wrapping_add(blockSize.wrapping_sub(srcBytesTotal));
6489            lastBlockEntireSrc = lastBlock;
6490        } else {
6491            ZSTD_deriveSeqStoreChunk(
6492                nextSeqStore,
6493                &(*zc).seqStore,
6494                *partitions.add(i) as size_t,
6495                *partitions.add(i.wrapping_add(1)) as size_t,
6496            );
6497        }
6498        cSizeChunk = ZSTD_compressSeqStore_singleBlock(
6499            zc,
6500            currSeqStore,
6501            &mut dRep,
6502            &mut cRep,
6503            op as *mut core::ffi::c_void,
6504            dstCapacity,
6505            ip as *const core::ffi::c_void,
6506            srcBytes,
6507            lastBlockEntireSrc,
6508            1,
6509        );
6510        let err_code_0 = cSizeChunk;
6511        if ERR_isError(err_code_0) {
6512            return err_code_0;
6513        }
6514        ip = ip.add(srcBytes);
6515        op = op.add(cSizeChunk);
6516        dstCapacity = dstCapacity.wrapping_sub(cSizeChunk);
6517        cSize = cSize.wrapping_add(cSizeChunk);
6518        *currSeqStore = *nextSeqStore;
6519        i = i.wrapping_add(1);
6520    }
6521    libc::memcpy(
6522        ((*(*zc).blockState.prevCBlock).rep).as_mut_ptr() as *mut core::ffi::c_void,
6523        (dRep.rep).as_mut_ptr() as *const core::ffi::c_void,
6524        ::core::mem::size_of::<Repcodes_t>(),
6525    );
6526    cSize
6527}
6528unsafe fn ZSTD_compressBlock_splitBlock(
6529    zc: *mut ZSTD_CCtx,
6530    dst: *mut core::ffi::c_void,
6531    dstCapacity: size_t,
6532    src: *const core::ffi::c_void,
6533    srcSize: size_t,
6534    lastBlock: u32,
6535) -> size_t {
6536    let mut nbSeq: u32 = 0;
6537    let mut cSize: size_t = 0;
6538    let bss = ZSTD_buildSeqStore(zc, src, srcSize);
6539    let err_code = bss;
6540    if ERR_isError(err_code) {
6541        return err_code;
6542    }
6543    if bss == ZSTDbss_noCompress as core::ffi::c_int as size_t {
6544        if (*(*zc).blockState.prevCBlock)
6545            .entropy
6546            .fse
6547            .offcode_repeatMode as core::ffi::c_uint
6548            == FSE_repeat_valid as core::ffi::c_int as core::ffi::c_uint
6549        {
6550            (*(*zc).blockState.prevCBlock)
6551                .entropy
6552                .fse
6553                .offcode_repeatMode = FSE_repeat_check;
6554        }
6555        if (*zc).seqCollector.collectSequences != 0 {
6556            return Error::sequenceProducer_failed.to_error_code();
6557        }
6558        cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
6559        let err_code_0 = cSize;
6560        if ERR_isError(err_code_0) {
6561            return err_code_0;
6562        }
6563        return cSize;
6564    }
6565    nbSeq = ((*zc).seqStore.sequences).offset_from((*zc).seqStore.sequencesStart)
6566        as core::ffi::c_long as u32;
6567    cSize = ZSTD_compressBlock_splitBlock_internal(
6568        zc,
6569        dst,
6570        dstCapacity,
6571        src,
6572        srcSize,
6573        lastBlock,
6574        nbSeq,
6575    );
6576    let err_code_1 = cSize;
6577    if ERR_isError(err_code_1) {
6578        return err_code_1;
6579    }
6580    cSize
6581}
6582unsafe fn ZSTD_compressBlock_internal(
6583    zc: *mut ZSTD_CCtx,
6584    dst: *mut core::ffi::c_void,
6585    dstCapacity: size_t,
6586    src: *const core::ffi::c_void,
6587    srcSize: size_t,
6588    frame: u32,
6589) -> size_t {
6590    let rleMaxLength = 25;
6591    let mut cSize: size_t = 0;
6592    let ip = src as *const u8;
6593    let op = dst as *mut u8;
6594    let bss = ZSTD_buildSeqStore(zc, src, srcSize);
6595    let err_code = bss;
6596    if ERR_isError(err_code) {
6597        return err_code;
6598    }
6599    if bss == ZSTDbss_noCompress as core::ffi::c_int as size_t {
6600        if (*zc).seqCollector.collectSequences != 0 {
6601            return Error::sequenceProducer_failed.to_error_code();
6602        }
6603        cSize = 0;
6604    } else {
6605        if (*zc).seqCollector.collectSequences != 0 {
6606            let err_code_0 = ZSTD_copyBlockSequences(
6607                &mut (*zc).seqCollector,
6608                ZSTD_getSeqStore(zc),
6609                ((*(*zc).blockState.prevCBlock).rep).as_mut_ptr() as *const u32,
6610            );
6611            if ERR_isError(err_code_0) {
6612                return err_code_0;
6613            }
6614            ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*zc).blockState);
6615            return 0;
6616        }
6617        cSize = ZSTD_entropyCompressSeqStore(
6618            &(*zc).seqStore,
6619            &(*(*zc).blockState.prevCBlock).entropy,
6620            &mut (*(*zc).blockState.nextCBlock).entropy,
6621            &(*zc).appliedParams,
6622            dst,
6623            dstCapacity,
6624            srcSize,
6625            (*zc).tmpWorkspace,
6626            (*zc).tmpWkspSize,
6627            (*zc).bmi2,
6628        );
6629        if frame != 0
6630            && (*zc).isFirstBlock == 0
6631            && cSize < rleMaxLength as size_t
6632            && ZSTD_isRLE(ip, srcSize) != 0
6633        {
6634            cSize = 1;
6635            *op = *ip;
6636        }
6637    }
6638    if !ERR_isError(cSize) && cSize > 1 {
6639        ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*zc).blockState);
6640    }
6641    if (*(*zc).blockState.prevCBlock)
6642        .entropy
6643        .fse
6644        .offcode_repeatMode as core::ffi::c_uint
6645        == FSE_repeat_valid as core::ffi::c_int as core::ffi::c_uint
6646    {
6647        (*(*zc).blockState.prevCBlock)
6648            .entropy
6649            .fse
6650            .offcode_repeatMode = FSE_repeat_check;
6651    }
6652    cSize
6653}
6654unsafe fn ZSTD_compressBlock_targetCBlockSize_body(
6655    zc: *mut ZSTD_CCtx,
6656    dst: *mut core::ffi::c_void,
6657    dstCapacity: size_t,
6658    src: *const core::ffi::c_void,
6659    srcSize: size_t,
6660    bss: size_t,
6661    lastBlock: u32,
6662) -> size_t {
6663    if bss == ZSTDbss_compress as core::ffi::c_int as size_t {
6664        if (*zc).isFirstBlock == 0
6665            && ZSTD_maybeRLE(&(*zc).seqStore) != 0
6666            && ZSTD_isRLE(src as *const u8, srcSize) != 0
6667        {
6668            return ZSTD_rleCompressBlock(
6669                dst,
6670                dstCapacity,
6671                *(src as *const u8),
6672                srcSize,
6673                lastBlock,
6674            );
6675        }
6676        let cSize = ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
6677        if cSize != Error::dstSize_tooSmall.to_error_code() {
6678            let maxCSize =
6679                srcSize.wrapping_sub(ZSTD_minGain(srcSize, (*zc).appliedParams.cParams.strategy));
6680            let err_code = cSize;
6681            if ERR_isError(err_code) {
6682                return err_code;
6683            }
6684            if cSize != 0 && cSize < maxCSize.wrapping_add(ZSTD_blockHeaderSize) {
6685                ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*zc).blockState);
6686                return cSize;
6687            }
6688        }
6689    }
6690    ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock)
6691}
6692unsafe fn ZSTD_compressBlock_targetCBlockSize(
6693    zc: *mut ZSTD_CCtx,
6694    dst: *mut core::ffi::c_void,
6695    dstCapacity: size_t,
6696    src: *const core::ffi::c_void,
6697    srcSize: size_t,
6698    lastBlock: u32,
6699) -> size_t {
6700    let mut cSize = 0;
6701    let bss = ZSTD_buildSeqStore(zc, src, srcSize);
6702    let err_code = bss;
6703    if ERR_isError(err_code) {
6704        return err_code;
6705    }
6706    cSize = ZSTD_compressBlock_targetCBlockSize_body(
6707        zc,
6708        dst,
6709        dstCapacity,
6710        src,
6711        srcSize,
6712        bss,
6713        lastBlock,
6714    );
6715    let err_code_0 = cSize;
6716    if ERR_isError(err_code_0) {
6717        return err_code_0;
6718    }
6719    if (*(*zc).blockState.prevCBlock)
6720        .entropy
6721        .fse
6722        .offcode_repeatMode as core::ffi::c_uint
6723        == FSE_repeat_valid as core::ffi::c_int as core::ffi::c_uint
6724    {
6725        (*(*zc).blockState.prevCBlock)
6726            .entropy
6727            .fse
6728            .offcode_repeatMode = FSE_repeat_check;
6729    }
6730    cSize
6731}
6732unsafe fn ZSTD_overflowCorrectIfNeeded(
6733    ms: &mut ZSTD_MatchState_t,
6734    ws: *mut ZSTD_cwksp,
6735    params: *const ZSTD_CCtx_params,
6736    ip: *const core::ffi::c_void,
6737    iend: *const core::ffi::c_void,
6738) {
6739    let cycleLog = ZSTD_cycleLog((*params).cParams.chainLog, (*params).cParams.strategy);
6740    let maxDist = (1) << (*params).cParams.windowLog;
6741    if ZSTD_window_needOverflowCorrection(ms.window, cycleLog, maxDist, ms.loadedDictEnd, ip, iend)
6742    {
6743        let correction = ZSTD_window_correctOverflow(&mut ms.window, cycleLog, maxDist, ip);
6744        ZSTD_cwksp_mark_tables_dirty(ws);
6745        ZSTD_reduceIndex(ms, params, correction);
6746        ZSTD_cwksp_mark_tables_clean(ws);
6747        if ms.nextToUpdate < correction {
6748            ms.nextToUpdate = 0;
6749        } else {
6750            ms.nextToUpdate = (ms.nextToUpdate).wrapping_sub(correction);
6751        }
6752        ms.loadedDictEnd = 0;
6753        ms.dictMatchState = core::ptr::null();
6754    }
6755}
6756unsafe fn ZSTD_optimalBlockSize(
6757    cctx: *mut ZSTD_CCtx,
6758    src: *const core::ffi::c_void,
6759    srcSize: size_t,
6760    blockSizeMax: size_t,
6761    mut splitLevel: core::ffi::c_int,
6762    strat: ZSTD_strategy,
6763    savings: S64,
6764) -> size_t {
6765    static splitLevels: [core::ffi::c_int; 10] = [0, 0, 1, 2, 2, 3, 3, 4, 4, 4];
6766    if srcSize < (128 * ((1) << 10)) as size_t || blockSizeMax < (128 * ((1) << 10)) as size_t {
6767        return if srcSize < blockSizeMax {
6768            srcSize
6769        } else {
6770            blockSizeMax
6771        };
6772    }
6773    if savings < 3 {
6774        return (128 * ((1) << 10)) as size_t;
6775    }
6776    if splitLevel == 1 {
6777        return (128 * ((1) << 10)) as size_t;
6778    }
6779    if splitLevel == 0 {
6780        splitLevel = *splitLevels.as_ptr().offset(strat as isize);
6781    } else {
6782        splitLevel -= 2;
6783    }
6784    ZSTD_splitBlock(
6785        src,
6786        blockSizeMax,
6787        splitLevel,
6788        (*cctx).tmpWorkspace,
6789        (*cctx).tmpWkspSize,
6790    )
6791}
6792unsafe fn ZSTD_compress_frameChunk(
6793    cctx: *mut ZSTD_CCtx,
6794    dst: *mut core::ffi::c_void,
6795    mut dstCapacity: size_t,
6796    src: *const core::ffi::c_void,
6797    srcSize: size_t,
6798    lastFrameChunk: u32,
6799) -> size_t {
6800    let blockSizeMax = (*cctx).blockSizeMax;
6801    let mut remaining = srcSize;
6802    let mut ip = src as *const u8;
6803    let ostart = dst as *mut u8;
6804    let mut op = ostart;
6805    let maxDist = (1) << (*cctx).appliedParams.cParams.windowLog;
6806    let mut savings = (*cctx).consumedSrcSize as S64 - (*cctx).producedCSize as S64;
6807    if (*cctx).appliedParams.fParams.checksumFlag != 0 && srcSize != 0 {
6808        ZSTD_XXH64_update_slice(
6809            &mut (*cctx).xxhState,
6810            core::slice::from_raw_parts(src as *const u8, srcSize),
6811        );
6812    }
6813    while remaining != 0 {
6814        let ms: &mut ZSTD_MatchState_t = &mut (*cctx).blockState.matchState;
6815        let blockSize = ZSTD_optimalBlockSize(
6816            cctx,
6817            ip as *const core::ffi::c_void,
6818            remaining,
6819            blockSizeMax,
6820            (*cctx).appliedParams.preBlockSplitter_level,
6821            (*cctx).appliedParams.cParams.strategy,
6822            savings,
6823        );
6824        let lastBlock = lastFrameChunk & (blockSize == remaining) as core::ffi::c_int as u32;
6825        if dstCapacity
6826            < ZSTD_blockHeaderSize
6827                .wrapping_add((1 + 1) as size_t)
6828                .wrapping_add(1)
6829        {
6830            return Error::dstSize_tooSmall.to_error_code();
6831        }
6832        ZSTD_overflowCorrectIfNeeded(
6833            ms,
6834            &mut (*cctx).workspace,
6835            &(*cctx).appliedParams,
6836            ip as *const core::ffi::c_void,
6837            ip.add(blockSize) as *const core::ffi::c_void,
6838        );
6839        ZSTD_checkDictValidity(
6840            &ms.window,
6841            ip.add(blockSize) as *const core::ffi::c_void,
6842            maxDist,
6843            &mut ms.loadedDictEnd,
6844            &mut ms.dictMatchState,
6845        );
6846        ZSTD_window_enforceMaxDist(
6847            &mut ms.window,
6848            ip as *const core::ffi::c_void,
6849            maxDist,
6850            &mut ms.loadedDictEnd,
6851            &mut ms.dictMatchState,
6852        );
6853        if ms.nextToUpdate < ms.window.lowLimit {
6854            ms.nextToUpdate = ms.window.lowLimit;
6855        }
6856        let mut cSize: size_t = 0;
6857        if ZSTD_useTargetCBlockSize(&(*cctx).appliedParams) != 0 {
6858            cSize = ZSTD_compressBlock_targetCBlockSize(
6859                cctx,
6860                op as *mut core::ffi::c_void,
6861                dstCapacity,
6862                ip as *const core::ffi::c_void,
6863                blockSize,
6864                lastBlock,
6865            );
6866            let err_code = cSize;
6867            if ERR_isError(err_code) {
6868                return err_code;
6869            }
6870        } else if ZSTD_blockSplitterEnabled(&mut (*cctx).appliedParams) != 0 {
6871            cSize = ZSTD_compressBlock_splitBlock(
6872                cctx,
6873                op as *mut core::ffi::c_void,
6874                dstCapacity,
6875                ip as *const core::ffi::c_void,
6876                blockSize,
6877                lastBlock,
6878            );
6879            let err_code_0 = cSize;
6880            if ERR_isError(err_code_0) {
6881                return err_code_0;
6882            }
6883        } else {
6884            cSize = ZSTD_compressBlock_internal(
6885                cctx,
6886                op.add(ZSTD_blockHeaderSize) as *mut core::ffi::c_void,
6887                dstCapacity.wrapping_sub(ZSTD_blockHeaderSize),
6888                ip as *const core::ffi::c_void,
6889                blockSize,
6890                1,
6891            );
6892            let err_code_1 = cSize;
6893            if ERR_isError(err_code_1) {
6894                return err_code_1;
6895            }
6896            if cSize == 0 {
6897                cSize = ZSTD_noCompressBlock(
6898                    op as *mut core::ffi::c_void,
6899                    dstCapacity,
6900                    ip as *const core::ffi::c_void,
6901                    blockSize,
6902                    lastBlock,
6903                );
6904                let err_code_2 = cSize;
6905                if ERR_isError(err_code_2) {
6906                    return err_code_2;
6907                }
6908            } else {
6909                let cBlockHeader = if cSize == 1 {
6910                    lastBlock
6911                        .wrapping_add((bt_rle as core::ffi::c_int as u32) << 1)
6912                        .wrapping_add((blockSize << 3) as u32)
6913                } else {
6914                    lastBlock
6915                        .wrapping_add((bt_compressed as core::ffi::c_int as u32) << 1)
6916                        .wrapping_add((cSize << 3) as u32)
6917                };
6918                MEM_writeLE24(op as *mut core::ffi::c_void, cBlockHeader);
6919                cSize = cSize.wrapping_add(ZSTD_blockHeaderSize);
6920            }
6921        }
6922        savings += blockSize as S64 - cSize as S64;
6923        ip = ip.add(blockSize);
6924        remaining = remaining.wrapping_sub(blockSize);
6925        op = op.add(cSize);
6926        dstCapacity = dstCapacity.wrapping_sub(cSize);
6927        (*cctx).isFirstBlock = 0;
6928    }
6929    if lastFrameChunk != 0 && op > ostart {
6930        (*cctx).stage = ZSTDcs_ending;
6931    }
6932    op.offset_from_unsigned(ostart)
6933}
6934unsafe fn ZSTD_writeFrameHeader(
6935    dst: *mut core::ffi::c_void,
6936    dstCapacity: size_t,
6937    params: *const ZSTD_CCtx_params,
6938    pledgedSrcSize: u64,
6939    dictID: u32,
6940) -> size_t {
6941    let op = dst as *mut u8;
6942    let dictIDSizeCodeLength = ((dictID > 0) as core::ffi::c_int
6943        + (dictID >= 256) as core::ffi::c_int
6944        + (dictID >= 65536) as core::ffi::c_int) as u32;
6945    let dictIDSizeCode = if (*params).fParams.noDictIDFlag != 0 {
6946        0
6947    } else {
6948        dictIDSizeCodeLength
6949    };
6950    let checksumFlag = ((*params).fParams.checksumFlag > 0) as core::ffi::c_int as u32;
6951    let windowSize = (1) << (*params).cParams.windowLog;
6952    let singleSegment = ((*params).fParams.contentSizeFlag != 0
6953        && windowSize as u64 >= pledgedSrcSize) as core::ffi::c_int as u32;
6954    let windowLogByte = (((*params).cParams.windowLog)
6955        .wrapping_sub(ZSTD_WINDOWLOG_ABSOLUTEMIN as core::ffi::c_uint)
6956        << 3) as u8;
6957    let fcsCode = (if (*params).fParams.contentSizeFlag != 0 {
6958        (pledgedSrcSize >= 256) as core::ffi::c_int
6959            + (pledgedSrcSize >= (65536 + 256) as u64) as core::ffi::c_int
6960            + (pledgedSrcSize >= 0xffffffff as core::ffi::c_uint as u64) as core::ffi::c_int
6961    } else {
6962        0
6963    }) as u32;
6964    let frameHeaderDescriptionByte = dictIDSizeCode
6965        .wrapping_add(checksumFlag << 2)
6966        .wrapping_add(singleSegment << 5)
6967        .wrapping_add(fcsCode << 6) as u8;
6968    let mut pos = 0 as size_t;
6969    if dstCapacity < 18 {
6970        return Error::dstSize_tooSmall.to_error_code();
6971    }
6972    if (*params).format == Format::ZSTD_f_zstd1 {
6973        MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
6974        pos = 4;
6975    }
6976    let fresh7 = pos;
6977    pos = pos.wrapping_add(1);
6978    *op.add(fresh7) = frameHeaderDescriptionByte;
6979    if singleSegment == 0 {
6980        let fresh8 = pos;
6981        pos = pos.wrapping_add(1);
6982        *op.add(fresh8) = windowLogByte;
6983    }
6984    match dictIDSizeCode {
6985        1 => {
6986            *op.add(pos) = dictID as u8;
6987            pos = pos.wrapping_add(1);
6988        }
6989        2 => {
6990            MEM_writeLE16(op.add(pos) as *mut core::ffi::c_void, dictID as u16);
6991            pos = pos.wrapping_add(2);
6992        }
6993        3 => {
6994            MEM_writeLE32(op.add(pos) as *mut core::ffi::c_void, dictID);
6995            pos = pos.wrapping_add(4);
6996        }
6997        0 | _ => {}
6998    }
6999    match fcsCode {
7000        1 => {
7001            MEM_writeLE16(
7002                op.add(pos) as *mut core::ffi::c_void,
7003                pledgedSrcSize.wrapping_sub(256) as u16,
7004            );
7005            pos = pos.wrapping_add(2);
7006        }
7007        2 => {
7008            MEM_writeLE32(op.add(pos) as *mut core::ffi::c_void, pledgedSrcSize as u32);
7009            pos = pos.wrapping_add(4);
7010        }
7011        3 => {
7012            MEM_writeLE64(op.add(pos) as *mut core::ffi::c_void, pledgedSrcSize);
7013            pos = pos.wrapping_add(8);
7014        }
7015        0 | _ => {
7016            if singleSegment != 0 {
7017                let fresh9 = pos;
7018                pos = pos.wrapping_add(1);
7019                *op.add(fresh9) = pledgedSrcSize as u8;
7020            }
7021        }
7022    }
7023    pos
7024}
7025#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_writeSkippableFrame))]
7026pub unsafe extern "C" fn ZSTD_writeSkippableFrame(
7027    dst: *mut core::ffi::c_void,
7028    dstCapacity: size_t,
7029    src: *const core::ffi::c_void,
7030    srcSize: size_t,
7031    magicVariant: core::ffi::c_uint,
7032) -> size_t {
7033    let op = dst as *mut u8;
7034    if dstCapacity < srcSize.wrapping_add(8) {
7035        return Error::dstSize_tooSmall.to_error_code();
7036    }
7037    if srcSize > 0xffffffff as core::ffi::c_uint as size_t {
7038        return Error::srcSize_wrong.to_error_code();
7039    }
7040    if magicVariant > 15 {
7041        return Error::parameter_outOfBound.to_error_code();
7042    }
7043    MEM_writeLE32(
7044        op as *mut core::ffi::c_void,
7045        ZSTD_MAGIC_SKIPPABLE_START.wrapping_add(magicVariant),
7046    );
7047    MEM_writeLE32(op.add(4) as *mut core::ffi::c_void, srcSize as u32);
7048    libc::memcpy(
7049        op.add(8) as *mut core::ffi::c_void,
7050        src,
7051        srcSize as libc::size_t,
7052    );
7053    srcSize.wrapping_add(ZSTD_SKIPPABLEHEADERSIZE as size_t)
7054}
7055pub unsafe fn ZSTD_writeLastEmptyBlock(dst: *mut core::ffi::c_void, dstCapacity: size_t) -> size_t {
7056    if dstCapacity < ZSTD_blockHeaderSize {
7057        return Error::dstSize_tooSmall.to_error_code();
7058    }
7059    let cBlockHeader24 = (1u32).wrapping_add((bt_raw as core::ffi::c_int as u32) << 1);
7060    MEM_writeLE24(dst, cBlockHeader24);
7061    ZSTD_blockHeaderSize
7062}
7063pub unsafe fn ZSTD_referenceExternalSequences(
7064    cctx: *mut ZSTD_CCtx,
7065    seq: *mut rawSeq,
7066    nbSeq: size_t,
7067) {
7068    (*cctx).externSeqStore.seq = seq;
7069    (*cctx).externSeqStore.size = nbSeq;
7070    (*cctx).externSeqStore.capacity = nbSeq;
7071    (*cctx).externSeqStore.pos = 0;
7072    (*cctx).externSeqStore.posInSequence = 0;
7073}
7074unsafe extern "C" fn ZSTD_compressContinue_internal(
7075    cctx: *mut ZSTD_CCtx,
7076    mut dst: *mut core::ffi::c_void,
7077    mut dstCapacity: size_t,
7078    src: *const core::ffi::c_void,
7079    srcSize: size_t,
7080    frame: u32,
7081    lastFrameChunk: u32,
7082) -> size_t {
7083    let ms: &mut ZSTD_MatchState_t = &mut (*cctx).blockState.matchState;
7084    let mut fhSize = 0;
7085    if (*cctx).stage as core::ffi::c_uint == ZSTDcs_created as core::ffi::c_int as core::ffi::c_uint
7086    {
7087        return Error::stage_wrong.to_error_code();
7088    }
7089    if frame != 0
7090        && (*cctx).stage as core::ffi::c_uint
7091            == ZSTDcs_init as core::ffi::c_int as core::ffi::c_uint
7092    {
7093        fhSize = ZSTD_writeFrameHeader(
7094            dst,
7095            dstCapacity,
7096            &(*cctx).appliedParams,
7097            ((*cctx).pledgedSrcSizePlusOne).wrapping_sub(1),
7098            (*cctx).dictID,
7099        );
7100        let err_code = fhSize;
7101        if ERR_isError(err_code) {
7102            return err_code;
7103        }
7104        dstCapacity = dstCapacity.wrapping_sub(fhSize);
7105        dst = (dst as *mut core::ffi::c_char).add(fhSize) as *mut core::ffi::c_void;
7106        (*cctx).stage = ZSTDcs_ongoing;
7107    }
7108    if srcSize == 0 {
7109        return fhSize;
7110    }
7111    if ZSTD_window_update(&mut ms.window, src, srcSize, ms.forceNonContiguous) == 0 {
7112        ms.forceNonContiguous = 0;
7113        ms.nextToUpdate = ms.window.dictLimit;
7114    }
7115    if (*cctx).appliedParams.ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
7116        ZSTD_window_update(&mut (*cctx).ldmState.window, src, srcSize, 0);
7117    }
7118    if frame == 0 {
7119        ZSTD_overflowCorrectIfNeeded(
7120            ms,
7121            &mut (*cctx).workspace,
7122            &(*cctx).appliedParams,
7123            src,
7124            (src as *const u8).add(srcSize) as *const core::ffi::c_void,
7125        );
7126    }
7127    let cSize = if frame != 0 {
7128        ZSTD_compress_frameChunk(cctx, dst, dstCapacity, src, srcSize, lastFrameChunk)
7129    } else {
7130        ZSTD_compressBlock_internal(cctx, dst, dstCapacity, src, srcSize, 0)
7131    };
7132    let err_code_0 = cSize;
7133    if ERR_isError(err_code_0) {
7134        return err_code_0;
7135    }
7136    (*cctx).consumedSrcSize =
7137        ((*cctx).consumedSrcSize).wrapping_add(srcSize as core::ffi::c_ulonglong);
7138    (*cctx).producedCSize =
7139        ((*cctx).producedCSize).wrapping_add(cSize.wrapping_add(fhSize) as core::ffi::c_ulonglong);
7140    if (*cctx).pledgedSrcSizePlusOne != 0
7141        && ((*cctx).consumedSrcSize).wrapping_add(1) > (*cctx).pledgedSrcSizePlusOne
7142    {
7143        return Error::srcSize_wrong.to_error_code();
7144    }
7145    cSize.wrapping_add(fhSize)
7146}
7147#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressContinue_public))]
7148pub unsafe extern "C" fn ZSTD_compressContinue_public(
7149    cctx: *mut ZSTD_CCtx,
7150    dst: *mut core::ffi::c_void,
7151    dstCapacity: size_t,
7152    src: *const core::ffi::c_void,
7153    srcSize: size_t,
7154) -> size_t {
7155    ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1, 0)
7156}
7157#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressContinue))]
7158pub unsafe extern "C" fn ZSTD_compressContinue(
7159    cctx: *mut ZSTD_CCtx,
7160    dst: *mut core::ffi::c_void,
7161    dstCapacity: size_t,
7162    src: *const core::ffi::c_void,
7163    srcSize: size_t,
7164) -> size_t {
7165    ZSTD_compressContinue_public(cctx, dst, dstCapacity, src, srcSize)
7166}
7167unsafe fn ZSTD_getBlockSize_deprecated(cctx: *const ZSTD_CCtx) -> size_t {
7168    let cParams = (*cctx).appliedParams.cParams;
7169    if (*cctx).appliedParams.maxBlockSize < (1) << cParams.windowLog {
7170        (*cctx).appliedParams.maxBlockSize
7171    } else {
7172        (1) << cParams.windowLog
7173    }
7174}
7175#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getBlockSize))]
7176pub unsafe extern "C" fn ZSTD_getBlockSize(cctx: *const ZSTD_CCtx) -> size_t {
7177    ZSTD_getBlockSize_deprecated(cctx)
7178}
7179#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBlock_deprecated))]
7180pub unsafe extern "C" fn ZSTD_compressBlock_deprecated(
7181    cctx: *mut ZSTD_CCtx,
7182    dst: *mut core::ffi::c_void,
7183    dstCapacity: size_t,
7184    src: *const core::ffi::c_void,
7185    srcSize: size_t,
7186) -> size_t {
7187    let blockSizeMax = ZSTD_getBlockSize_deprecated(cctx);
7188    if srcSize > blockSizeMax {
7189        return Error::srcSize_wrong.to_error_code();
7190    }
7191    ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0, 0)
7192}
7193#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBlock))]
7194pub unsafe extern "C" fn ZSTD_compressBlock(
7195    cctx: *mut ZSTD_CCtx,
7196    dst: *mut core::ffi::c_void,
7197    dstCapacity: size_t,
7198    src: *const core::ffi::c_void,
7199    srcSize: size_t,
7200) -> size_t {
7201    ZSTD_compressBlock_deprecated(cctx, dst, dstCapacity, src, srcSize)
7202}
7203unsafe fn ZSTD_loadDictionaryContent(
7204    ms: &mut ZSTD_MatchState_t,
7205    ls: *mut ldmState_t,
7206    ws: *mut ZSTD_cwksp,
7207    params: *const ZSTD_CCtx_params,
7208    mut src: *const core::ffi::c_void,
7209    mut srcSize: size_t,
7210    dtlm: ZSTD_dictTableLoadMethod_e,
7211    tfp: ZSTD_tableFillPurpose_e,
7212) -> size_t {
7213    let mut ip = src as *const u8;
7214    let iend = ip.add(srcSize);
7215    let loadLdmDict = ((*params).ldmParams.enableLdm == ZSTD_ParamSwitch_e::ZSTD_ps_enable
7216        && !ls.is_null()) as core::ffi::c_int;
7217    ZSTD_assertEqualCParams((*params).cParams, ms.cParams);
7218    let mut maxDictSize = (if MEM_64bits() {
7219        (3500 as core::ffi::c_uint)
7220            .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
7221    } else {
7222        (2000 as core::ffi::c_uint)
7223            .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
7224    })
7225    .wrapping_sub(ZSTD_WINDOW_START_INDEX as core::ffi::c_uint);
7226    let CDictTaggedIndices = ZSTD_CDictIndicesAreTagged(&(*params).cParams);
7227    if CDictTaggedIndices != 0
7228        && tfp as core::ffi::c_uint == ZSTD_tfp_forCDict as core::ffi::c_int as core::ffi::c_uint
7229    {
7230        let shortCacheMaxDictSize = ((1 as core::ffi::c_uint) << (32 - ZSTD_SHORT_CACHE_TAG_BITS))
7231            .wrapping_sub(ZSTD_WINDOW_START_INDEX as core::ffi::c_uint);
7232        maxDictSize = if maxDictSize < shortCacheMaxDictSize {
7233            maxDictSize
7234        } else {
7235            shortCacheMaxDictSize
7236        };
7237    }
7238    if srcSize > maxDictSize as size_t {
7239        ip = iend.offset(-(maxDictSize as isize));
7240        src = ip as *const core::ffi::c_void;
7241        srcSize = maxDictSize as size_t;
7242    }
7243    if srcSize
7244        > (-(1 as core::ffi::c_int) as u32).wrapping_sub(if MEM_64bits() {
7245            (3500 as core::ffi::c_uint)
7246                .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
7247        } else {
7248            (2000 as core::ffi::c_uint)
7249                .wrapping_mul(((1 as core::ffi::c_int) << 20) as core::ffi::c_uint)
7250        }) as size_t
7251    {
7252        assert!(loadLdmDict != 0);
7253    }
7254    ZSTD_window_update(&mut ms.window, src, srcSize, 0);
7255    if loadLdmDict != 0 {
7256        ZSTD_window_update(&mut (*ls).window, src, srcSize, 0);
7257        (*ls).loadedDictEnd = if (*params).forceWindow != 0 {
7258            0
7259        } else {
7260            iend.offset_from((*ls).window.base) as core::ffi::c_long as u32
7261        };
7262        ZSTD_ldm_fillHashTable(ls, ip, iend, &(*params).ldmParams);
7263    }
7264    let maxDictSize_0 = (1)
7265        << (if (if ((*params).cParams.hashLog).wrapping_add(3)
7266            > ((*params).cParams.chainLog).wrapping_add(1)
7267        {
7268            ((*params).cParams.hashLog).wrapping_add(3)
7269        } else {
7270            ((*params).cParams.chainLog).wrapping_add(1)
7271        }) < 31
7272        {
7273            if ((*params).cParams.hashLog).wrapping_add(3)
7274                > ((*params).cParams.chainLog).wrapping_add(1)
7275            {
7276                ((*params).cParams.hashLog).wrapping_add(3)
7277            } else {
7278                ((*params).cParams.chainLog).wrapping_add(1)
7279            }
7280        } else {
7281            31
7282        });
7283    if srcSize > maxDictSize_0 as size_t {
7284        ip = iend.offset(-(maxDictSize_0 as isize));
7285        src = ip as *const core::ffi::c_void;
7286        srcSize = maxDictSize_0 as size_t;
7287    }
7288    ms.nextToUpdate = ip.offset_from(ms.window.base) as core::ffi::c_long as u32;
7289    ms.loadedDictEnd = if (*params).forceWindow != 0 {
7290        0
7291    } else {
7292        iend.offset_from(ms.window.base) as core::ffi::c_long as u32
7293    };
7294    ms.forceNonContiguous = (*params).deterministicRefPrefix;
7295    if srcSize <= HASH_READ_SIZE as size_t {
7296        return 0;
7297    }
7298    ZSTD_overflowCorrectIfNeeded(
7299        ms,
7300        ws,
7301        params,
7302        ip as *const core::ffi::c_void,
7303        iend as *const core::ffi::c_void,
7304    );
7305    match (*params).cParams.strategy as core::ffi::c_uint {
7306        1 => {
7307            ZSTD_fillHashTable(ms, iend as *const core::ffi::c_void, dtlm, tfp);
7308        }
7309        2 => {
7310            ZSTD_fillDoubleHashTable(ms, iend as *const core::ffi::c_void, dtlm, tfp);
7311        }
7312        3..=5 => {
7313            if ms.dedicatedDictSearch != 0 {
7314                ZSTD_dedicatedDictSearch_lazy_loadDictionary(
7315                    ms,
7316                    iend.offset(-(HASH_READ_SIZE as isize)),
7317                );
7318            } else if (*params).useRowMatchFinder == ZSTD_ParamSwitch_e::ZSTD_ps_enable {
7319                let tagTableSize = (1) << (*params).cParams.hashLog;
7320                ptr::write_bytes(ms.tagTable, 0, tagTableSize as usize);
7321                ZSTD_row_update(ms, iend.offset(-(HASH_READ_SIZE as isize)));
7322            } else {
7323                ZSTD_insertAndFindFirstIndex(ms, iend.offset(-(HASH_READ_SIZE as isize)));
7324            }
7325        }
7326        6..=9 => {
7327            ZSTD_updateTree(ms, iend.offset(-(HASH_READ_SIZE as isize)), iend);
7328        }
7329        _ => {}
7330    }
7331    ms.nextToUpdate = iend.offset_from(ms.window.base) as core::ffi::c_long as u32;
7332    0
7333}
7334unsafe fn ZSTD_dictNCountRepeat(
7335    normalizedCounter: *mut core::ffi::c_short,
7336    dictMaxSymbolValue: core::ffi::c_uint,
7337    maxSymbolValue: core::ffi::c_uint,
7338) -> FSE_repeat {
7339    let mut s: u32 = 0;
7340    if dictMaxSymbolValue < maxSymbolValue {
7341        return FSE_repeat_check;
7342    }
7343    s = 0;
7344    while s <= maxSymbolValue {
7345        if *normalizedCounter.offset(s as isize) as core::ffi::c_int == 0 {
7346            return FSE_repeat_check;
7347        }
7348        s = s.wrapping_add(1);
7349    }
7350    FSE_repeat_valid
7351}
7352pub unsafe fn ZSTD_loadCEntropy(
7353    bs: *mut ZSTD_compressedBlockState_t,
7354    workspace: *mut core::ffi::c_void,
7355    dict: *const core::ffi::c_void,
7356    dictSize: size_t,
7357) -> size_t {
7358    let mut offcodeNCount: [core::ffi::c_short; 32] = [0; 32];
7359    let mut offcodeMaxValue = MaxOff;
7360    let mut dictPtr = dict as *const u8;
7361    let dictEnd = dictPtr.add(dictSize);
7362    dictPtr = dictPtr.add(8);
7363    (*bs).entropy.huf.repeatMode = HUF_repeat_check;
7364    let mut maxSymbolValue = 255;
7365    let mut hasZeroWeights = 1;
7366    let hufHeaderSize = HUF_readCTable(
7367        ((*bs).entropy.huf.CTable).as_mut_ptr(),
7368        &mut maxSymbolValue,
7369        dictPtr as *const core::ffi::c_void,
7370        dictEnd.offset_from_unsigned(dictPtr),
7371        &mut hasZeroWeights,
7372    );
7373    if hasZeroWeights == 0 && maxSymbolValue == 255 {
7374        (*bs).entropy.huf.repeatMode = HUF_repeat_valid;
7375    }
7376    if ERR_isError(hufHeaderSize) {
7377        return Error::dictionary_corrupted.to_error_code();
7378    }
7379    dictPtr = dictPtr.add(hufHeaderSize);
7380    let mut offcodeLog: core::ffi::c_uint = 0;
7381    let offcodeHeaderSize = FSE_readNCount(
7382        &mut offcodeNCount,
7383        &mut offcodeMaxValue,
7384        &mut offcodeLog,
7385        dictPtr as *const core::ffi::c_void,
7386        dictEnd.offset_from_unsigned(dictPtr),
7387    );
7388    if ERR_isError(offcodeHeaderSize) {
7389        return Error::dictionary_corrupted.to_error_code();
7390    }
7391    if offcodeLog > 8 {
7392        return Error::dictionary_corrupted.to_error_code();
7393    }
7394    if ERR_isError(FSE_buildCTable_wksp(
7395        ((*bs).entropy.fse.offcodeCTable).as_mut_ptr(),
7396        offcodeNCount.as_mut_ptr(),
7397        31,
7398        offcodeLog,
7399        workspace,
7400        (((8) << 10) + 512) as size_t,
7401    )) {
7402        return Error::dictionary_corrupted.to_error_code();
7403    }
7404    dictPtr = dictPtr.add(offcodeHeaderSize);
7405    let mut matchlengthNCount: [core::ffi::c_short; 53] = [0; 53];
7406    let mut matchlengthMaxValue = MaxML;
7407    let mut matchlengthLog: core::ffi::c_uint = 0;
7408    let matchlengthHeaderSize = FSE_readNCount(
7409        &mut matchlengthNCount,
7410        &mut matchlengthMaxValue,
7411        &mut matchlengthLog,
7412        dictPtr as *const core::ffi::c_void,
7413        dictEnd.offset_from_unsigned(dictPtr),
7414    );
7415    if ERR_isError(matchlengthHeaderSize) {
7416        return Error::dictionary_corrupted.to_error_code();
7417    }
7418    if matchlengthLog > 9 {
7419        return Error::dictionary_corrupted.to_error_code();
7420    }
7421    if ERR_isError(FSE_buildCTable_wksp(
7422        ((*bs).entropy.fse.matchlengthCTable).as_mut_ptr(),
7423        matchlengthNCount.as_mut_ptr(),
7424        matchlengthMaxValue,
7425        matchlengthLog,
7426        workspace,
7427        (((8) << 10) + 512) as size_t,
7428    )) {
7429        return Error::dictionary_corrupted.to_error_code();
7430    }
7431    (*bs).entropy.fse.matchlength_repeatMode =
7432        ZSTD_dictNCountRepeat(matchlengthNCount.as_mut_ptr(), matchlengthMaxValue, MaxML);
7433    dictPtr = dictPtr.add(matchlengthHeaderSize);
7434    let mut litlengthNCount: [core::ffi::c_short; 36] = [0; 36];
7435    let mut litlengthMaxValue = MaxLL;
7436    let mut litlengthLog: core::ffi::c_uint = 0;
7437    let litlengthHeaderSize = FSE_readNCount(
7438        &mut litlengthNCount,
7439        &mut litlengthMaxValue,
7440        &mut litlengthLog,
7441        dictPtr as *const core::ffi::c_void,
7442        dictEnd.offset_from_unsigned(dictPtr),
7443    );
7444    if ERR_isError(litlengthHeaderSize) {
7445        return Error::dictionary_corrupted.to_error_code();
7446    }
7447    if litlengthLog > 9 {
7448        return Error::dictionary_corrupted.to_error_code();
7449    }
7450    if ERR_isError(FSE_buildCTable_wksp(
7451        ((*bs).entropy.fse.litlengthCTable).as_mut_ptr(),
7452        litlengthNCount.as_mut_ptr(),
7453        litlengthMaxValue,
7454        litlengthLog,
7455        workspace,
7456        (((8) << 10) + 512) as size_t,
7457    )) {
7458        return Error::dictionary_corrupted.to_error_code();
7459    }
7460    (*bs).entropy.fse.litlength_repeatMode =
7461        ZSTD_dictNCountRepeat(litlengthNCount.as_mut_ptr(), litlengthMaxValue, MaxLL);
7462    dictPtr = dictPtr.add(litlengthHeaderSize);
7463    if dictPtr.add(12) > dictEnd {
7464        return Error::dictionary_corrupted.to_error_code();
7465    }
7466    *((*bs).rep).as_mut_ptr() = MEM_readLE32(dictPtr as *const core::ffi::c_void);
7467    *((*bs).rep).as_mut_ptr().add(1) = MEM_readLE32(dictPtr.add(4) as *const core::ffi::c_void);
7468    *((*bs).rep).as_mut_ptr().add(2) = MEM_readLE32(dictPtr.add(8) as *const core::ffi::c_void);
7469    dictPtr = dictPtr.add(12);
7470    let dictContentSize = dictEnd.offset_from_unsigned(dictPtr);
7471    let mut offcodeMax = MaxOff;
7472    if dictContentSize
7473        <= (-(1 as core::ffi::c_int) as u32)
7474            .wrapping_sub((128 as core::ffi::c_int * ((1 as core::ffi::c_int) << 10)) as u32)
7475            as size_t
7476    {
7477        let maxOffset = (dictContentSize as u32).wrapping_add((128 * ((1) << 10)) as u32);
7478        offcodeMax = ZSTD_highbit32(maxOffset);
7479    }
7480    (*bs).entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(
7481        offcodeNCount.as_mut_ptr(),
7482        offcodeMaxValue,
7483        if offcodeMax < 31 { offcodeMax } else { 31 },
7484    );
7485    let mut u: u32 = 0;
7486    u = 0;
7487    while u < 3 {
7488        if *((*bs).rep).as_mut_ptr().offset(u as isize) == 0 {
7489            return Error::dictionary_corrupted.to_error_code();
7490        }
7491        if *((*bs).rep).as_mut_ptr().offset(u as isize) as size_t > dictContentSize {
7492            return Error::dictionary_corrupted.to_error_code();
7493        }
7494        u = u.wrapping_add(1);
7495    }
7496    dictPtr.offset_from_unsigned(dict as *const u8)
7497}
7498unsafe fn ZSTD_loadZstdDictionary(
7499    bs: *mut ZSTD_compressedBlockState_t,
7500    ms: &mut ZSTD_MatchState_t,
7501    ws: *mut ZSTD_cwksp,
7502    params: *const ZSTD_CCtx_params,
7503    dict: *const core::ffi::c_void,
7504    dictSize: size_t,
7505    dtlm: ZSTD_dictTableLoadMethod_e,
7506    tfp: ZSTD_tableFillPurpose_e,
7507    workspace: *mut core::ffi::c_void,
7508) -> size_t {
7509    let mut dictPtr = dict as *const u8;
7510    let dictEnd = dictPtr.add(dictSize);
7511    let mut dictID: size_t = 0;
7512    let mut eSize: size_t = 0;
7513    dictID = (if (*params).fParams.noDictIDFlag != 0 {
7514        0
7515    } else {
7516        MEM_readLE32(dictPtr.add(4) as *const core::ffi::c_void)
7517    }) as size_t;
7518    eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
7519    let err_code = eSize;
7520    if ERR_isError(err_code) {
7521        return err_code;
7522    }
7523    dictPtr = dictPtr.add(eSize);
7524    let dictContentSize = dictEnd.offset_from_unsigned(dictPtr);
7525    let err_code_0 = ZSTD_loadDictionaryContent(
7526        ms,
7527        core::ptr::null_mut::<ldmState_t>(),
7528        ws,
7529        params,
7530        dictPtr as *const core::ffi::c_void,
7531        dictContentSize,
7532        dtlm,
7533        tfp,
7534    );
7535    if ERR_isError(err_code_0) {
7536        return err_code_0;
7537    }
7538    dictID
7539}
7540
7541unsafe fn ZSTD_compress_insertDictionary(
7542    bs: *mut ZSTD_compressedBlockState_t,
7543    ms: &mut ZSTD_MatchState_t,
7544    ls: *mut ldmState_t,
7545    ws: *mut ZSTD_cwksp,
7546    params: *const ZSTD_CCtx_params,
7547    dict: *const core::ffi::c_void,
7548    dictSize: size_t,
7549    dictContentType: ZSTD_dictContentType_e,
7550    dtlm: ZSTD_dictTableLoadMethod_e,
7551    tfp: ZSTD_tableFillPurpose_e,
7552    workspace: *mut core::ffi::c_void,
7553) -> size_t {
7554    if dict.is_null() || dictSize < 8 {
7555        if dictContentType as core::ffi::c_uint
7556            == ZSTD_dct_fullDict as core::ffi::c_int as core::ffi::c_uint
7557        {
7558            return Error::dictionary_wrong.to_error_code();
7559        }
7560        return 0;
7561    }
7562    ZSTD_reset_compressedBlockState(bs);
7563    if dictContentType as core::ffi::c_uint
7564        == ZSTD_dct_rawContent as core::ffi::c_int as core::ffi::c_uint
7565    {
7566        return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);
7567    }
7568    if MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY {
7569        if dictContentType as core::ffi::c_uint
7570            == ZSTD_dct_auto as core::ffi::c_int as core::ffi::c_uint
7571        {
7572            return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);
7573        }
7574        if dictContentType as core::ffi::c_uint
7575            == ZSTD_dct_fullDict as core::ffi::c_int as core::ffi::c_uint
7576        {
7577            return Error::dictionary_wrong.to_error_code();
7578        }
7579    }
7580    ZSTD_loadZstdDictionary(bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace)
7581}
7582pub const ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF: core::ffi::c_int = 128 * ((1) << 10);
7583pub const ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER: core::ffi::c_ulonglong = 6;
7584unsafe fn ZSTD_compressBegin_internal(
7585    cctx: *mut ZSTD_CCtx,
7586    dict: *const core::ffi::c_void,
7587    dictSize: size_t,
7588    dictContentType: ZSTD_dictContentType_e,
7589    dtlm: ZSTD_dictTableLoadMethod_e,
7590    cdict: *const ZSTD_CDict,
7591    params: *const ZSTD_CCtx_params,
7592    pledgedSrcSize: u64,
7593    zbuff: ZSTD_buffered_policy_e,
7594) -> size_t {
7595    let dictContentSize = if !cdict.is_null() {
7596        (*cdict).dictContentSize
7597    } else {
7598        dictSize
7599    };
7600    (*cctx).traceCtx = ZSTD_trace_compress_begin(cctx);
7601    if !cdict.is_null()
7602        && (*cdict).dictContentSize > 0
7603        && (pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF as u64
7604            || (pledgedSrcSize as core::ffi::c_ulonglong)
7605                < ((*cdict).dictContentSize as core::ffi::c_ulonglong)
7606                    .wrapping_mul(ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER)
7607            || pledgedSrcSize as core::ffi::c_ulonglong == ZSTD_CONTENTSIZE_UNKNOWN
7608            || (*cdict).compressionLevel == 0)
7609        && (*params).attachDictPref != ZSTD_dictAttachPref_e::ZSTD_dictForceLoad
7610    {
7611        return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
7612    }
7613    let err_code = ZSTD_resetCCtx_internal(
7614        cctx,
7615        params,
7616        pledgedSrcSize,
7617        dictContentSize,
7618        ZSTDcrp_makeClean,
7619        zbuff,
7620    );
7621    if ERR_isError(err_code) {
7622        return err_code;
7623    }
7624    let dictID = if !cdict.is_null() {
7625        ZSTD_compress_insertDictionary(
7626            (*cctx).blockState.prevCBlock,
7627            &mut (*cctx).blockState.matchState,
7628            &mut (*cctx).ldmState,
7629            &mut (*cctx).workspace,
7630            &(*cctx).appliedParams,
7631            (*cdict).dictContent,
7632            (*cdict).dictContentSize,
7633            (*cdict).dictContentType,
7634            dtlm,
7635            ZSTD_tfp_forCCtx,
7636            (*cctx).tmpWorkspace,
7637        )
7638    } else {
7639        ZSTD_compress_insertDictionary(
7640            (*cctx).blockState.prevCBlock,
7641            &mut (*cctx).blockState.matchState,
7642            &mut (*cctx).ldmState,
7643            &mut (*cctx).workspace,
7644            &(*cctx).appliedParams,
7645            dict,
7646            dictSize,
7647            dictContentType,
7648            dtlm,
7649            ZSTD_tfp_forCCtx,
7650            (*cctx).tmpWorkspace,
7651        )
7652    };
7653    let err_code_0 = dictID;
7654    if ERR_isError(err_code_0) {
7655        return err_code_0;
7656    }
7657    (*cctx).dictID = dictID as u32;
7658    (*cctx).dictContentSize = dictContentSize;
7659    0
7660}
7661pub unsafe fn ZSTD_compressBegin_advanced_internal(
7662    cctx: *mut ZSTD_CCtx,
7663    dict: *const core::ffi::c_void,
7664    dictSize: size_t,
7665    dictContentType: ZSTD_dictContentType_e,
7666    dtlm: ZSTD_dictTableLoadMethod_e,
7667    cdict: *const ZSTD_CDict,
7668    params: *const ZSTD_CCtx_params,
7669    pledgedSrcSize: core::ffi::c_ulonglong,
7670) -> size_t {
7671    let err_code = ZSTD_checkCParams((*params).cParams);
7672    if ERR_isError(err_code) {
7673        return err_code;
7674    }
7675    ZSTD_compressBegin_internal(
7676        cctx,
7677        dict,
7678        dictSize,
7679        dictContentType,
7680        dtlm,
7681        cdict,
7682        params,
7683        pledgedSrcSize,
7684        ZSTDb_not_buffered,
7685    )
7686}
7687#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBegin_advanced))]
7688pub unsafe extern "C" fn ZSTD_compressBegin_advanced(
7689    cctx: *mut ZSTD_CCtx,
7690    dict: *const core::ffi::c_void,
7691    dictSize: size_t,
7692    params: ZSTD_parameters,
7693    pledgedSrcSize: core::ffi::c_ulonglong,
7694) -> size_t {
7695    let mut cctxParams = ZSTD_CCtx_params_s {
7696        format: Format::ZSTD_f_zstd1,
7697        cParams: ZSTD_compressionParameters {
7698            windowLog: 0,
7699            chainLog: 0,
7700            hashLog: 0,
7701            searchLog: 0,
7702            minMatch: 0,
7703            targetLength: 0,
7704            strategy: 0,
7705        },
7706        fParams: ZSTD_frameParameters {
7707            contentSizeFlag: 0,
7708            checksumFlag: 0,
7709            noDictIDFlag: 0,
7710        },
7711        compressionLevel: 0,
7712        forceWindow: 0,
7713        targetCBlockSize: 0,
7714        srcSizeHint: 0,
7715        attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
7716        literalCompressionMode: ParamSwitch::Auto,
7717        nbWorkers: 0,
7718        jobSize: 0,
7719        overlapLog: 0,
7720        rsyncable: 0,
7721        ldmParams: ldmParams_t {
7722            enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7723            hashLog: 0,
7724            bucketSizeLog: 0,
7725            minMatchLength: 0,
7726            hashRateLog: 0,
7727            windowLog: 0,
7728        },
7729        enableDedicatedDictSearch: 0,
7730        inBufferMode: ZSTD_bm_buffered,
7731        outBufferMode: ZSTD_bm_buffered,
7732        blockDelimiters: ZSTD_sf_noBlockDelimiters,
7733        validateSequences: 0,
7734        postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7735        preBlockSplitter_level: 0,
7736        maxBlockSize: 0,
7737        useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7738        deterministicRefPrefix: 0,
7739        customMem: ZSTD_customMem::default(),
7740        prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7741        enableMatchFinderFallback: 0,
7742        extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
7743        extSeqProdFunc: None,
7744        searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7745    };
7746    ZSTD_CCtxParams_init_internal(&mut cctxParams, &params, ZSTD_NO_CLEVEL);
7747    ZSTD_compressBegin_advanced_internal(
7748        cctx,
7749        dict,
7750        dictSize,
7751        ZSTD_dct_auto,
7752        ZSTD_dtlm_fast,
7753        core::ptr::null(),
7754        &cctxParams,
7755        pledgedSrcSize,
7756    )
7757}
7758unsafe fn ZSTD_compressBegin_usingDict_deprecated(
7759    cctx: *mut ZSTD_CCtx,
7760    dict: *const core::ffi::c_void,
7761    dictSize: size_t,
7762    compressionLevel: core::ffi::c_int,
7763) -> size_t {
7764    let mut cctxParams = ZSTD_CCtx_params_s {
7765        format: Format::ZSTD_f_zstd1,
7766        cParams: ZSTD_compressionParameters {
7767            windowLog: 0,
7768            chainLog: 0,
7769            hashLog: 0,
7770            searchLog: 0,
7771            minMatch: 0,
7772            targetLength: 0,
7773            strategy: 0,
7774        },
7775        fParams: ZSTD_frameParameters {
7776            contentSizeFlag: 0,
7777            checksumFlag: 0,
7778            noDictIDFlag: 0,
7779        },
7780        compressionLevel: 0,
7781        forceWindow: 0,
7782        targetCBlockSize: 0,
7783        srcSizeHint: 0,
7784        attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
7785        literalCompressionMode: ParamSwitch::Auto,
7786        nbWorkers: 0,
7787        jobSize: 0,
7788        overlapLog: 0,
7789        rsyncable: 0,
7790        ldmParams: ldmParams_t {
7791            enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7792            hashLog: 0,
7793            bucketSizeLog: 0,
7794            minMatchLength: 0,
7795            hashRateLog: 0,
7796            windowLog: 0,
7797        },
7798        enableDedicatedDictSearch: 0,
7799        inBufferMode: ZSTD_bm_buffered,
7800        outBufferMode: ZSTD_bm_buffered,
7801        blockDelimiters: ZSTD_sf_noBlockDelimiters,
7802        validateSequences: 0,
7803        postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7804        preBlockSplitter_level: 0,
7805        maxBlockSize: 0,
7806        useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7807        deterministicRefPrefix: 0,
7808        customMem: ZSTD_customMem::default(),
7809        prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7810        enableMatchFinderFallback: 0,
7811        extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
7812        extSeqProdFunc: None,
7813        searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
7814    };
7815    let params = ZSTD_getParams_internal(
7816        compressionLevel,
7817        ZSTD_CONTENTSIZE_UNKNOWN,
7818        dictSize,
7819        ZSTD_cpm_noAttachDict,
7820    );
7821    ZSTD_CCtxParams_init_internal(
7822        &mut cctxParams,
7823        &params,
7824        if compressionLevel == 0 {
7825            ZSTD_CLEVEL_DEFAULT
7826        } else {
7827            compressionLevel
7828        },
7829    );
7830    ZSTD_compressBegin_internal(
7831        cctx,
7832        dict,
7833        dictSize,
7834        ZSTD_dct_auto,
7835        ZSTD_dtlm_fast,
7836        core::ptr::null(),
7837        &cctxParams,
7838        ZSTD_CONTENTSIZE_UNKNOWN,
7839        ZSTDb_not_buffered,
7840    )
7841}
7842#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBegin_usingDict))]
7843pub unsafe extern "C" fn ZSTD_compressBegin_usingDict(
7844    cctx: *mut ZSTD_CCtx,
7845    dict: *const core::ffi::c_void,
7846    dictSize: size_t,
7847    compressionLevel: core::ffi::c_int,
7848) -> size_t {
7849    ZSTD_compressBegin_usingDict_deprecated(cctx, dict, dictSize, compressionLevel)
7850}
7851#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBegin))]
7852pub unsafe extern "C" fn ZSTD_compressBegin(
7853    cctx: *mut ZSTD_CCtx,
7854    compressionLevel: core::ffi::c_int,
7855) -> size_t {
7856    ZSTD_compressBegin_usingDict_deprecated(cctx, core::ptr::null(), 0, compressionLevel)
7857}
7858unsafe fn ZSTD_writeEpilogue(
7859    cctx: *mut ZSTD_CCtx,
7860    dst: *mut core::ffi::c_void,
7861    mut dstCapacity: size_t,
7862) -> size_t {
7863    let ostart = dst as *mut u8;
7864    let mut op = ostart;
7865    if (*cctx).stage as core::ffi::c_uint == ZSTDcs_created as core::ffi::c_int as core::ffi::c_uint
7866    {
7867        return Error::stage_wrong.to_error_code();
7868    }
7869    if (*cctx).stage as core::ffi::c_uint == ZSTDcs_init as core::ffi::c_int as core::ffi::c_uint {
7870        let fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &(*cctx).appliedParams, 0, 0);
7871        let err_code = fhSize;
7872        if ERR_isError(err_code) {
7873            return err_code;
7874        }
7875        dstCapacity = dstCapacity.wrapping_sub(fhSize);
7876        op = op.add(fhSize);
7877        (*cctx).stage = ZSTDcs_ongoing;
7878    }
7879    if (*cctx).stage as core::ffi::c_uint != ZSTDcs_ending as core::ffi::c_int as core::ffi::c_uint
7880    {
7881        let cBlockHeader24 = 1u32
7882            .wrapping_add((bt_raw as core::ffi::c_int as u32) << 1)
7883            .wrapping_add(0);
7884        if dstCapacity < 3 as size_t {
7885            return Error::dstSize_tooSmall.to_error_code();
7886        }
7887        MEM_writeLE24(op as *mut core::ffi::c_void, cBlockHeader24);
7888        op = op.add(ZSTD_blockHeaderSize);
7889        dstCapacity = dstCapacity.wrapping_sub(ZSTD_blockHeaderSize);
7890    }
7891    if (*cctx).appliedParams.fParams.checksumFlag != 0 {
7892        let checksum = ZSTD_XXH64_digest(&mut (*cctx).xxhState) as u32;
7893        if dstCapacity < 4 {
7894            return Error::dstSize_tooSmall.to_error_code();
7895        }
7896        MEM_writeLE32(op as *mut core::ffi::c_void, checksum);
7897        op = op.add(4);
7898    }
7899    (*cctx).stage = ZSTDcs_created;
7900    op.offset_from_unsigned(ostart)
7901}
7902pub unsafe fn ZSTD_CCtx_trace(cctx: *mut ZSTD_CCtx, extraCSize: size_t) {
7903    if (*cctx).traceCtx != 0 {
7904        let streaming = ((*cctx).inBuffSize > 0
7905            || (*cctx).outBuffSize > 0
7906            || (*cctx).appliedParams.nbWorkers > 0) as core::ffi::c_int;
7907        let mut trace = ZSTD_Trace::default();
7908        trace.version = ZSTD_VERSION_NUMBER as core::ffi::c_uint;
7909        trace.streaming = streaming;
7910        trace.dictionaryID = (*cctx).dictID;
7911        trace.dictionarySize = (*cctx).dictContentSize;
7912        trace.uncompressedSize = (*cctx).consumedSrcSize as size_t;
7913        trace.compressedSize =
7914            ((*cctx).producedCSize).wrapping_add(extraCSize as core::ffi::c_ulonglong) as size_t;
7915        trace.params = &mut (*cctx).appliedParams;
7916        trace.cctx = cctx;
7917        ZSTD_trace_compress_end((*cctx).traceCtx, &trace);
7918    }
7919    (*cctx).traceCtx = 0;
7920}
7921#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressEnd_public))]
7922pub unsafe extern "C" fn ZSTD_compressEnd_public(
7923    cctx: *mut ZSTD_CCtx,
7924    dst: *mut core::ffi::c_void,
7925    dstCapacity: size_t,
7926    src: *const core::ffi::c_void,
7927    srcSize: size_t,
7928) -> size_t {
7929    let mut endResult: size_t = 0;
7930    let cSize = ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1, 1);
7931    let err_code = cSize;
7932    if ERR_isError(err_code) {
7933        return err_code;
7934    }
7935    endResult = ZSTD_writeEpilogue(
7936        cctx,
7937        (dst as *mut core::ffi::c_char).add(cSize) as *mut core::ffi::c_void,
7938        dstCapacity.wrapping_sub(cSize),
7939    );
7940    let err_code_0 = endResult;
7941    if ERR_isError(err_code_0) {
7942        return err_code_0;
7943    }
7944    if (*cctx).pledgedSrcSizePlusOne != 0
7945        && (*cctx).pledgedSrcSizePlusOne != ((*cctx).consumedSrcSize).wrapping_add(1)
7946    {
7947        return Error::srcSize_wrong.to_error_code();
7948    }
7949    ZSTD_CCtx_trace(cctx, endResult);
7950    cSize.wrapping_add(endResult)
7951}
7952#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressEnd))]
7953pub unsafe extern "C" fn ZSTD_compressEnd(
7954    cctx: *mut ZSTD_CCtx,
7955    dst: *mut core::ffi::c_void,
7956    dstCapacity: size_t,
7957    src: *const core::ffi::c_void,
7958    srcSize: size_t,
7959) -> size_t {
7960    ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize)
7961}
7962#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compress_advanced))]
7963pub unsafe extern "C" fn ZSTD_compress_advanced(
7964    cctx: *mut ZSTD_CCtx,
7965    dst: *mut core::ffi::c_void,
7966    dstCapacity: size_t,
7967    src: *const core::ffi::c_void,
7968    srcSize: size_t,
7969    dict: *const core::ffi::c_void,
7970    dictSize: size_t,
7971    params: ZSTD_parameters,
7972) -> size_t {
7973    let err_code = ZSTD_checkCParams(params.cParams);
7974    if ERR_isError(err_code) {
7975        return err_code;
7976    }
7977    ZSTD_CCtxParams_init_internal(&mut (*cctx).simpleApiParams, &params, ZSTD_NO_CLEVEL);
7978    ZSTD_compress_advanced_internal(
7979        cctx,
7980        dst,
7981        dstCapacity,
7982        src,
7983        srcSize,
7984        dict,
7985        dictSize,
7986        &(*cctx).simpleApiParams,
7987    )
7988}
7989pub unsafe fn ZSTD_compress_advanced_internal(
7990    cctx: *mut ZSTD_CCtx,
7991    dst: *mut core::ffi::c_void,
7992    dstCapacity: size_t,
7993    src: *const core::ffi::c_void,
7994    srcSize: size_t,
7995    dict: *const core::ffi::c_void,
7996    dictSize: size_t,
7997    params: *const ZSTD_CCtx_params,
7998) -> size_t {
7999    let err_code = ZSTD_compressBegin_internal(
8000        cctx,
8001        dict,
8002        dictSize,
8003        ZSTD_dct_auto,
8004        ZSTD_dtlm_fast,
8005        core::ptr::null::<ZSTD_CDict>(),
8006        params,
8007        srcSize as u64,
8008        ZSTDb_not_buffered,
8009    );
8010    if ERR_isError(err_code) {
8011        return err_code;
8012    }
8013    ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize)
8014}
8015#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compress_usingDict))]
8016pub unsafe extern "C" fn ZSTD_compress_usingDict(
8017    cctx: *mut ZSTD_CCtx,
8018    dst: *mut core::ffi::c_void,
8019    dstCapacity: size_t,
8020    src: *const core::ffi::c_void,
8021    srcSize: size_t,
8022    dict: *const core::ffi::c_void,
8023    dictSize: size_t,
8024    compressionLevel: core::ffi::c_int,
8025) -> size_t {
8026    let params = ZSTD_getParams_internal(
8027        compressionLevel,
8028        srcSize as core::ffi::c_ulonglong,
8029        if !dict.is_null() { dictSize } else { 0 },
8030        ZSTD_cpm_noAttachDict,
8031    );
8032    ZSTD_CCtxParams_init_internal(
8033        &mut (*cctx).simpleApiParams,
8034        &params,
8035        if compressionLevel == 0 {
8036            ZSTD_CLEVEL_DEFAULT
8037        } else {
8038            compressionLevel
8039        },
8040    );
8041    ZSTD_compress_advanced_internal(
8042        cctx,
8043        dst,
8044        dstCapacity,
8045        src,
8046        srcSize,
8047        dict,
8048        dictSize,
8049        &(*cctx).simpleApiParams,
8050    )
8051}
8052#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressCCtx))]
8053pub unsafe extern "C" fn ZSTD_compressCCtx(
8054    cctx: *mut ZSTD_CCtx,
8055    dst: *mut core::ffi::c_void,
8056    dstCapacity: size_t,
8057    src: *const core::ffi::c_void,
8058    srcSize: size_t,
8059    compressionLevel: core::ffi::c_int,
8060) -> size_t {
8061    ZSTD_compress_usingDict(
8062        cctx,
8063        dst,
8064        dstCapacity,
8065        src,
8066        srcSize,
8067        core::ptr::null(),
8068        0,
8069        compressionLevel,
8070    )
8071}
8072#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compress))]
8073pub unsafe extern "C" fn ZSTD_compress(
8074    dst: *mut core::ffi::c_void,
8075    dstCapacity: size_t,
8076    src: *const core::ffi::c_void,
8077    srcSize: size_t,
8078    compressionLevel: core::ffi::c_int,
8079) -> size_t {
8080    let mut result: size_t = 0;
8081    let mut ctxBody = ZSTD_CCtx_s {
8082        stage: ZSTDcs_created,
8083        cParamsChanged: 0,
8084        bmi2: 0,
8085        requestedParams: ZSTD_CCtx_params_s {
8086            format: Format::ZSTD_f_zstd1,
8087            cParams: ZSTD_compressionParameters {
8088                windowLog: 0,
8089                chainLog: 0,
8090                hashLog: 0,
8091                searchLog: 0,
8092                minMatch: 0,
8093                targetLength: 0,
8094                strategy: 0,
8095            },
8096            fParams: ZSTD_frameParameters {
8097                contentSizeFlag: 0,
8098                checksumFlag: 0,
8099                noDictIDFlag: 0,
8100            },
8101            compressionLevel: 0,
8102            forceWindow: 0,
8103            targetCBlockSize: 0,
8104            srcSizeHint: 0,
8105            attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
8106            literalCompressionMode: ParamSwitch::Auto,
8107            nbWorkers: 0,
8108            jobSize: 0,
8109            overlapLog: 0,
8110            rsyncable: 0,
8111            ldmParams: ldmParams_t {
8112                enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8113                hashLog: 0,
8114                bucketSizeLog: 0,
8115                minMatchLength: 0,
8116                hashRateLog: 0,
8117                windowLog: 0,
8118            },
8119            enableDedicatedDictSearch: 0,
8120            inBufferMode: ZSTD_bm_buffered,
8121            outBufferMode: ZSTD_bm_buffered,
8122            blockDelimiters: ZSTD_sf_noBlockDelimiters,
8123            validateSequences: 0,
8124            postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8125            preBlockSplitter_level: 0,
8126            maxBlockSize: 0,
8127            useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8128            deterministicRefPrefix: 0,
8129            customMem: ZSTD_customMem::default(),
8130            prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8131            enableMatchFinderFallback: 0,
8132            extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
8133            extSeqProdFunc: None,
8134            searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8135        },
8136        appliedParams: ZSTD_CCtx_params_s {
8137            format: Format::ZSTD_f_zstd1,
8138            cParams: ZSTD_compressionParameters {
8139                windowLog: 0,
8140                chainLog: 0,
8141                hashLog: 0,
8142                searchLog: 0,
8143                minMatch: 0,
8144                targetLength: 0,
8145                strategy: 0,
8146            },
8147            fParams: ZSTD_frameParameters {
8148                contentSizeFlag: 0,
8149                checksumFlag: 0,
8150                noDictIDFlag: 0,
8151            },
8152            compressionLevel: 0,
8153            forceWindow: 0,
8154            targetCBlockSize: 0,
8155            srcSizeHint: 0,
8156            attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
8157            literalCompressionMode: ParamSwitch::Auto,
8158            nbWorkers: 0,
8159            jobSize: 0,
8160            overlapLog: 0,
8161            rsyncable: 0,
8162            ldmParams: ldmParams_t {
8163                enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8164                hashLog: 0,
8165                bucketSizeLog: 0,
8166                minMatchLength: 0,
8167                hashRateLog: 0,
8168                windowLog: 0,
8169            },
8170            enableDedicatedDictSearch: 0,
8171            inBufferMode: ZSTD_bm_buffered,
8172            outBufferMode: ZSTD_bm_buffered,
8173            blockDelimiters: ZSTD_sf_noBlockDelimiters,
8174            validateSequences: 0,
8175            postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8176            preBlockSplitter_level: 0,
8177            maxBlockSize: 0,
8178            useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8179            deterministicRefPrefix: 0,
8180            customMem: ZSTD_customMem::default(),
8181            prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8182            enableMatchFinderFallback: 0,
8183            extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
8184            extSeqProdFunc: None,
8185            searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8186        },
8187        simpleApiParams: ZSTD_CCtx_params_s {
8188            format: Format::ZSTD_f_zstd1,
8189            cParams: ZSTD_compressionParameters {
8190                windowLog: 0,
8191                chainLog: 0,
8192                hashLog: 0,
8193                searchLog: 0,
8194                minMatch: 0,
8195                targetLength: 0,
8196                strategy: 0,
8197            },
8198            fParams: ZSTD_frameParameters {
8199                contentSizeFlag: 0,
8200                checksumFlag: 0,
8201                noDictIDFlag: 0,
8202            },
8203            compressionLevel: 0,
8204            forceWindow: 0,
8205            targetCBlockSize: 0,
8206            srcSizeHint: 0,
8207            attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
8208            literalCompressionMode: ParamSwitch::Auto,
8209            nbWorkers: 0,
8210            jobSize: 0,
8211            overlapLog: 0,
8212            rsyncable: 0,
8213            ldmParams: ldmParams_t {
8214                enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8215                hashLog: 0,
8216                bucketSizeLog: 0,
8217                minMatchLength: 0,
8218                hashRateLog: 0,
8219                windowLog: 0,
8220            },
8221            enableDedicatedDictSearch: 0,
8222            inBufferMode: ZSTD_bm_buffered,
8223            outBufferMode: ZSTD_bm_buffered,
8224            blockDelimiters: ZSTD_sf_noBlockDelimiters,
8225            validateSequences: 0,
8226            postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8227            preBlockSplitter_level: 0,
8228            maxBlockSize: 0,
8229            useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8230            deterministicRefPrefix: 0,
8231            customMem: ZSTD_customMem::default(),
8232            prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8233            enableMatchFinderFallback: 0,
8234            extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
8235            extSeqProdFunc: None,
8236            searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8237        },
8238        dictID: 0,
8239        dictContentSize: 0,
8240        workspace: ZSTD_cwksp {
8241            workspace: core::ptr::null_mut::<core::ffi::c_void>(),
8242            workspaceEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8243            objectEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8244            tableEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8245            tableValidEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8246            allocStart: core::ptr::null_mut::<core::ffi::c_void>(),
8247            initOnceStart: core::ptr::null_mut::<core::ffi::c_void>(),
8248            allocFailed: 0,
8249            workspaceOversizedDuration: 0,
8250            phase: ZSTD_cwksp_alloc_objects,
8251            isStatic: ZSTD_cwksp_dynamic_alloc,
8252        },
8253        blockSizeMax: 0,
8254        pledgedSrcSizePlusOne: 0,
8255        consumedSrcSize: 0,
8256        producedCSize: 0,
8257        xxhState: XXH64_state_t::default(),
8258        customMem: ZSTD_customMem::default(),
8259        pool: core::ptr::null_mut::<ZSTD_threadPool>(),
8260        staticSize: 0,
8261        seqCollector: SeqCollector {
8262            collectSequences: 0,
8263            seqStart: core::ptr::null_mut::<ZSTD_Sequence>(),
8264            seqIndex: 0,
8265            maxSequences: 0,
8266        },
8267        isFirstBlock: 0,
8268        initialized: 0,
8269        seqStore: SeqStore_t {
8270            sequencesStart: core::ptr::null_mut::<SeqDef>(),
8271            sequences: core::ptr::null_mut::<SeqDef>(),
8272            litStart: core::ptr::null_mut::<u8>(),
8273            lit: core::ptr::null_mut::<u8>(),
8274            llCode: core::ptr::null_mut::<u8>(),
8275            mlCode: core::ptr::null_mut::<u8>(),
8276            ofCode: core::ptr::null_mut::<u8>(),
8277            maxNbSeq: 0,
8278            maxNbLit: 0,
8279            longLengthType: ZSTD_llt_none,
8280            longLengthPos: 0,
8281        },
8282        ldmState: ldmState_t {
8283            window: ZSTD_window_t {
8284                nextSrc: core::ptr::null::<u8>(),
8285                base: core::ptr::null::<u8>(),
8286                dictBase: core::ptr::null::<u8>(),
8287                dictLimit: 0,
8288                lowLimit: 0,
8289                nbOverflowCorrections: 0,
8290            },
8291            hashTable: core::ptr::null_mut::<ldmEntry_t>(),
8292            loadedDictEnd: 0,
8293            bucketOffsets: core::ptr::null_mut::<u8>(),
8294            splitIndices: [0; 64],
8295            matchCandidates: [ldmMatchCandidate_t {
8296                split: core::ptr::null::<u8>(),
8297                hash: 0,
8298                checksum: 0,
8299                bucket: core::ptr::null_mut::<ldmEntry_t>(),
8300            }; 64],
8301        },
8302        ldmSequences: core::ptr::null_mut::<rawSeq>(),
8303        maxNbLdmSequences: 0,
8304        externSeqStore: RawSeqStore_t {
8305            seq: core::ptr::null_mut::<rawSeq>(),
8306            pos: 0,
8307            posInSequence: 0,
8308            size: 0,
8309            capacity: 0,
8310        },
8311        blockState: ZSTD_blockState_t {
8312            prevCBlock: core::ptr::null_mut::<ZSTD_compressedBlockState_t>(),
8313            nextCBlock: core::ptr::null_mut::<ZSTD_compressedBlockState_t>(),
8314            matchState: ZSTD_MatchState_t {
8315                window: ZSTD_window_t {
8316                    nextSrc: core::ptr::null::<u8>(),
8317                    base: core::ptr::null::<u8>(),
8318                    dictBase: core::ptr::null::<u8>(),
8319                    dictLimit: 0,
8320                    lowLimit: 0,
8321                    nbOverflowCorrections: 0,
8322                },
8323                loadedDictEnd: 0,
8324                nextToUpdate: 0,
8325                hashLog3: 0,
8326                rowHashLog: 0,
8327                tagTable: core::ptr::null_mut::<u8>(),
8328                hashCache: [0; 8],
8329                hashSalt: 0,
8330                hashSaltEntropy: 0,
8331                hashTable: core::ptr::null_mut::<u32>(),
8332                hashTable3: core::ptr::null_mut::<u32>(),
8333                chainTable: core::ptr::null_mut::<u32>(),
8334                forceNonContiguous: 0,
8335                dedicatedDictSearch: 0,
8336                opt: optState_t {
8337                    litFreq: core::ptr::null_mut::<core::ffi::c_uint>(),
8338                    litLengthFreq: core::ptr::null_mut::<core::ffi::c_uint>(),
8339                    matchLengthFreq: core::ptr::null_mut::<core::ffi::c_uint>(),
8340                    offCodeFreq: core::ptr::null_mut::<core::ffi::c_uint>(),
8341                    matchTable: core::ptr::null_mut::<ZSTD_match_t>(),
8342                    priceTable: core::ptr::null_mut::<ZSTD_optimal_t>(),
8343                    litSum: 0,
8344                    litLengthSum: 0,
8345                    matchLengthSum: 0,
8346                    offCodeSum: 0,
8347                    litSumBasePrice: 0,
8348                    litLengthSumBasePrice: 0,
8349                    matchLengthSumBasePrice: 0,
8350                    offCodeSumBasePrice: 0,
8351                    priceType: zop_dynamic,
8352                    symbolCosts: core::ptr::null::<ZSTD_entropyCTables_t>(),
8353                    literalCompressionMode: ParamSwitch::Auto,
8354                },
8355                dictMatchState: core::ptr::null::<ZSTD_MatchState_t>(),
8356                cParams: ZSTD_compressionParameters {
8357                    windowLog: 0,
8358                    chainLog: 0,
8359                    hashLog: 0,
8360                    searchLog: 0,
8361                    minMatch: 0,
8362                    targetLength: 0,
8363                    strategy: 0,
8364                },
8365                ldmSeqStore: core::ptr::null::<RawSeqStore_t>(),
8366                prefetchCDictTables: 0,
8367                lazySkipping: 0,
8368            },
8369        },
8370        tmpWorkspace: core::ptr::null_mut::<core::ffi::c_void>(),
8371        tmpWkspSize: 0,
8372        bufferedPolicy: ZSTDb_not_buffered,
8373        inBuff: core::ptr::null_mut(),
8374        inBuffSize: 0,
8375        inToCompress: 0,
8376        inBuffPos: 0,
8377        inBuffTarget: 0,
8378        outBuff: core::ptr::null_mut(),
8379        outBuffSize: 0,
8380        outBuffContentSize: 0,
8381        outBuffFlushedSize: 0,
8382        streamStage: zcss_init,
8383        frameEnded: 0,
8384        expectedInBuffer: ZSTD_inBuffer_s {
8385            src: core::ptr::null::<core::ffi::c_void>(),
8386            size: 0,
8387            pos: 0,
8388        },
8389        stableIn_notConsumed: 0,
8390        expectedOutBufferSize: 0,
8391        localDict: ZSTD_localDict {
8392            dictBuffer: core::ptr::null_mut::<core::ffi::c_void>(),
8393            dict: core::ptr::null::<core::ffi::c_void>(),
8394            dictSize: 0,
8395            dictContentType: ZSTD_dct_auto,
8396            cdict: core::ptr::null_mut::<ZSTD_CDict>(),
8397        },
8398        cdict: core::ptr::null::<ZSTD_CDict>(),
8399        prefixDict: ZSTD_prefixDict_s {
8400            dict: core::ptr::null::<core::ffi::c_void>(),
8401            dictSize: 0,
8402            dictContentType: ZSTD_dct_auto,
8403        },
8404        mtctx: core::ptr::null_mut::<ZSTDMT_CCtx>(),
8405        traceCtx: 0,
8406        blockSplitCtx: ZSTD_blockSplitCtx {
8407            fullSeqStoreChunk: SeqStore_t {
8408                sequencesStart: core::ptr::null_mut::<SeqDef>(),
8409                sequences: core::ptr::null_mut::<SeqDef>(),
8410                litStart: core::ptr::null_mut::<u8>(),
8411                lit: core::ptr::null_mut::<u8>(),
8412                llCode: core::ptr::null_mut::<u8>(),
8413                mlCode: core::ptr::null_mut::<u8>(),
8414                ofCode: core::ptr::null_mut::<u8>(),
8415                maxNbSeq: 0,
8416                maxNbLit: 0,
8417                longLengthType: ZSTD_llt_none,
8418                longLengthPos: 0,
8419            },
8420            firstHalfSeqStore: SeqStore_t {
8421                sequencesStart: core::ptr::null_mut::<SeqDef>(),
8422                sequences: core::ptr::null_mut::<SeqDef>(),
8423                litStart: core::ptr::null_mut::<u8>(),
8424                lit: core::ptr::null_mut::<u8>(),
8425                llCode: core::ptr::null_mut::<u8>(),
8426                mlCode: core::ptr::null_mut::<u8>(),
8427                ofCode: core::ptr::null_mut::<u8>(),
8428                maxNbSeq: 0,
8429                maxNbLit: 0,
8430                longLengthType: ZSTD_llt_none,
8431                longLengthPos: 0,
8432            },
8433            secondHalfSeqStore: SeqStore_t {
8434                sequencesStart: core::ptr::null_mut::<SeqDef>(),
8435                sequences: core::ptr::null_mut::<SeqDef>(),
8436                litStart: core::ptr::null_mut::<u8>(),
8437                lit: core::ptr::null_mut::<u8>(),
8438                llCode: core::ptr::null_mut::<u8>(),
8439                mlCode: core::ptr::null_mut::<u8>(),
8440                ofCode: core::ptr::null_mut::<u8>(),
8441                maxNbSeq: 0,
8442                maxNbLit: 0,
8443                longLengthType: ZSTD_llt_none,
8444                longLengthPos: 0,
8445            },
8446            currSeqStore: SeqStore_t {
8447                sequencesStart: core::ptr::null_mut::<SeqDef>(),
8448                sequences: core::ptr::null_mut::<SeqDef>(),
8449                litStart: core::ptr::null_mut::<u8>(),
8450                lit: core::ptr::null_mut::<u8>(),
8451                llCode: core::ptr::null_mut::<u8>(),
8452                mlCode: core::ptr::null_mut::<u8>(),
8453                ofCode: core::ptr::null_mut::<u8>(),
8454                maxNbSeq: 0,
8455                maxNbLit: 0,
8456                longLengthType: ZSTD_llt_none,
8457                longLengthPos: 0,
8458            },
8459            nextSeqStore: SeqStore_t {
8460                sequencesStart: core::ptr::null_mut::<SeqDef>(),
8461                sequences: core::ptr::null_mut::<SeqDef>(),
8462                litStart: core::ptr::null_mut::<u8>(),
8463                lit: core::ptr::null_mut::<u8>(),
8464                llCode: core::ptr::null_mut::<u8>(),
8465                mlCode: core::ptr::null_mut::<u8>(),
8466                ofCode: core::ptr::null_mut::<u8>(),
8467                maxNbSeq: 0,
8468                maxNbLit: 0,
8469                longLengthType: ZSTD_llt_none,
8470                longLengthPos: 0,
8471            },
8472            partitions: [0; 196],
8473            entropyMetadata: ZSTD_entropyCTablesMetadata_t {
8474                hufMetadata: ZSTD_hufCTablesMetadata_t {
8475                    hType: set_basic,
8476                    hufDesBuffer: [0; 128],
8477                    hufDesSize: 0,
8478                },
8479                fseMetadata: ZSTD_fseCTablesMetadata_t {
8480                    llType: set_basic,
8481                    ofType: set_basic,
8482                    mlType: set_basic,
8483                    fseTablesBuffer: [0; 133],
8484                    fseTablesSize: 0,
8485                    lastCountSize: 0,
8486                },
8487            },
8488        },
8489        extSeqBuf: core::ptr::null_mut::<ZSTD_Sequence>(),
8490        extSeqBufCapacity: 0,
8491    };
8492    ZSTD_initCCtx(&mut ctxBody, ZSTD_customMem::default());
8493    result = ZSTD_compressCCtx(
8494        &mut ctxBody,
8495        dst,
8496        dstCapacity,
8497        src,
8498        srcSize,
8499        compressionLevel,
8500    );
8501    ZSTD_freeCCtxContent(&mut ctxBody);
8502    result
8503}
8504#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCDictSize_advanced))]
8505pub unsafe extern "C" fn ZSTD_estimateCDictSize_advanced(
8506    dictSize: size_t,
8507    cParams: ZSTD_compressionParameters,
8508    dictLoadMethod: ZSTD_dictLoadMethod_e,
8509) -> size_t {
8510    (ZSTD_cwksp_alloc_size(::core::mem::size_of::<ZSTD_CDict>()))
8511        .wrapping_add(ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE))
8512        .wrapping_add(ZSTD_sizeof_matchState(
8513            &cParams,
8514            ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cParams),
8515            1,
8516            0,
8517        ))
8518        .wrapping_add(
8519            if dictLoadMethod as core::ffi::c_uint
8520                == ZSTD_dlm_byRef as core::ffi::c_int as core::ffi::c_uint
8521            {
8522                0
8523            } else {
8524                ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(
8525                    dictSize,
8526                    ::core::mem::size_of::<*mut core::ffi::c_void>(),
8527                ))
8528            },
8529        )
8530}
8531#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateCDictSize))]
8532pub unsafe extern "C" fn ZSTD_estimateCDictSize(
8533    dictSize: size_t,
8534    compressionLevel: core::ffi::c_int,
8535) -> size_t {
8536    let cParams = ZSTD_getCParams_internal(
8537        compressionLevel,
8538        ZSTD_CONTENTSIZE_UNKNOWN,
8539        dictSize,
8540        ZSTD_cpm_createCDict,
8541    );
8542    ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy)
8543}
8544#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_sizeof_CDict))]
8545pub unsafe extern "C" fn ZSTD_sizeof_CDict(cdict: *const ZSTD_CDict) -> size_t {
8546    if cdict.is_null() {
8547        return 0;
8548    }
8549    (if (*cdict).workspace.workspace == cdict as *mut core::ffi::c_void {
8550        0
8551    } else {
8552        ::core::mem::size_of::<ZSTD_CDict>()
8553    })
8554    .wrapping_add(ZSTD_cwksp_sizeof(&(*cdict).workspace))
8555}
8556unsafe fn ZSTD_initCDict_internal(
8557    cdict: *mut ZSTD_CDict,
8558    dictBuffer: *const core::ffi::c_void,
8559    dictSize: size_t,
8560    dictLoadMethod: ZSTD_dictLoadMethod_e,
8561    dictContentType: ZSTD_dictContentType_e,
8562    mut params: ZSTD_CCtx_params,
8563) -> size_t {
8564    (*cdict).matchState.cParams = params.cParams;
8565    (*cdict).matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
8566    if dictLoadMethod as core::ffi::c_uint
8567        == ZSTD_dlm_byRef as core::ffi::c_int as core::ffi::c_uint
8568        || dictBuffer.is_null()
8569        || dictSize == 0
8570    {
8571        (*cdict).dictContent = dictBuffer;
8572    } else {
8573        let internalBuffer = ZSTD_cwksp_reserve_object(
8574            &mut (*cdict).workspace,
8575            ZSTD_cwksp_align(dictSize, ::core::mem::size_of::<*mut core::ffi::c_void>()),
8576        );
8577        if internalBuffer.is_null() {
8578            return Error::memory_allocation.to_error_code();
8579        }
8580        (*cdict).dictContent = internalBuffer;
8581        libc::memcpy(internalBuffer, dictBuffer, dictSize as libc::size_t);
8582    }
8583    (*cdict).dictContentSize = dictSize;
8584    (*cdict).dictContentType = dictContentType;
8585    (*cdict).entropyWorkspace =
8586        ZSTD_cwksp_reserve_object(&mut (*cdict).workspace, HUF_WORKSPACE_SIZE) as *mut u32;
8587    ZSTD_reset_compressedBlockState(&mut (*cdict).cBlockState);
8588    let err_code = ZSTD_reset_matchState(
8589        &mut (*cdict).matchState,
8590        &mut (*cdict).workspace,
8591        &params.cParams,
8592        params.useRowMatchFinder,
8593        ZSTDcrp_makeClean,
8594        ZSTDirp_reset,
8595        ZSTD_resetTarget_CDict,
8596    );
8597    if ERR_isError(err_code) {
8598        return err_code;
8599    }
8600    params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
8601    params.fParams.contentSizeFlag = 1;
8602    let dictID = ZSTD_compress_insertDictionary(
8603        &mut (*cdict).cBlockState,
8604        &mut (*cdict).matchState,
8605        core::ptr::null_mut(),
8606        &mut (*cdict).workspace,
8607        &params,
8608        (*cdict).dictContent,
8609        (*cdict).dictContentSize,
8610        dictContentType,
8611        ZSTD_dtlm_full,
8612        ZSTD_tfp_forCDict,
8613        (*cdict).entropyWorkspace as *mut core::ffi::c_void,
8614    );
8615    let err_code_0 = dictID;
8616    if ERR_isError(err_code_0) {
8617        return err_code_0;
8618    }
8619    (*cdict).dictID = dictID as u32;
8620    0
8621}
8622unsafe fn ZSTD_createCDict_advanced_internal(
8623    dictSize: size_t,
8624    dictLoadMethod: ZSTD_dictLoadMethod_e,
8625    cParams: ZSTD_compressionParameters,
8626    useRowMatchFinder: ZSTD_ParamSwitch_e,
8627    enableDedicatedDictSearch: core::ffi::c_int,
8628    customMem: ZSTD_customMem,
8629) -> *mut ZSTD_CDict {
8630    let workspaceSize = (ZSTD_cwksp_alloc_size(::core::mem::size_of::<ZSTD_CDict>()))
8631        .wrapping_add(ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE))
8632        .wrapping_add(ZSTD_sizeof_matchState(
8633            &cParams,
8634            useRowMatchFinder,
8635            enableDedicatedDictSearch,
8636            0,
8637        ))
8638        .wrapping_add(if dictLoadMethod == ZSTD_dlm_byRef {
8639            0
8640        } else {
8641            ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(
8642                dictSize,
8643                ::core::mem::size_of::<*mut core::ffi::c_void>(),
8644            ))
8645        });
8646    let workspace = ZSTD_customMalloc(workspaceSize, customMem);
8647    let mut ws = ZSTD_cwksp {
8648        workspace: core::ptr::null_mut::<core::ffi::c_void>(),
8649        workspaceEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8650        objectEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8651        tableEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8652        tableValidEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8653        allocStart: core::ptr::null_mut::<core::ffi::c_void>(),
8654        initOnceStart: core::ptr::null_mut::<core::ffi::c_void>(),
8655        allocFailed: 0,
8656        workspaceOversizedDuration: 0,
8657        phase: ZSTD_cwksp_alloc_objects,
8658        isStatic: ZSTD_cwksp_dynamic_alloc,
8659    };
8660    if workspace.is_null() {
8661        return core::ptr::null_mut();
8662    }
8663    ZSTD_cwksp_init(&mut ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
8664    let cdict =
8665        ZSTD_cwksp_reserve_object(&mut ws, ::core::mem::size_of::<ZSTD_CDict>()) as *mut ZSTD_CDict;
8666    ZSTD_cwksp_move(&mut (*cdict).workspace, &mut ws);
8667    (*cdict).customMem = customMem;
8668    (*cdict).compressionLevel = ZSTD_NO_CLEVEL;
8669    (*cdict).useRowMatchFinder = useRowMatchFinder;
8670    cdict
8671}
8672#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCDict_advanced))]
8673pub unsafe extern "C" fn ZSTD_createCDict_advanced(
8674    dictBuffer: *const core::ffi::c_void,
8675    dictSize: size_t,
8676    dictLoadMethod: ZSTD_dictLoadMethod_e,
8677    dictContentType: ZSTD_dictContentType_e,
8678    cParams: ZSTD_compressionParameters,
8679    customMem: ZSTD_customMem,
8680) -> *mut ZSTD_CDict {
8681    let mut cctxParams = ZSTD_CCtx_params_s {
8682        format: Format::ZSTD_f_zstd1,
8683        cParams: ZSTD_compressionParameters {
8684            windowLog: 0,
8685            chainLog: 0,
8686            hashLog: 0,
8687            searchLog: 0,
8688            minMatch: 0,
8689            targetLength: 0,
8690            strategy: 0,
8691        },
8692        fParams: ZSTD_frameParameters {
8693            contentSizeFlag: 0,
8694            checksumFlag: 0,
8695            noDictIDFlag: 0,
8696        },
8697        compressionLevel: 0,
8698        forceWindow: 0,
8699        targetCBlockSize: 0,
8700        srcSizeHint: 0,
8701        attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
8702        literalCompressionMode: ParamSwitch::Auto,
8703        nbWorkers: 0,
8704        jobSize: 0,
8705        overlapLog: 0,
8706        rsyncable: 0,
8707        ldmParams: ldmParams_t {
8708            enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8709            hashLog: 0,
8710            bucketSizeLog: 0,
8711            minMatchLength: 0,
8712            hashRateLog: 0,
8713            windowLog: 0,
8714        },
8715        enableDedicatedDictSearch: 0,
8716        inBufferMode: ZSTD_bm_buffered,
8717        outBufferMode: ZSTD_bm_buffered,
8718        blockDelimiters: ZSTD_sf_noBlockDelimiters,
8719        validateSequences: 0,
8720        postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8721        preBlockSplitter_level: 0,
8722        maxBlockSize: 0,
8723        useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8724        deterministicRefPrefix: 0,
8725        customMem: ZSTD_customMem::default(),
8726        prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8727        enableMatchFinderFallback: 0,
8728        extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
8729        extSeqProdFunc: None,
8730        searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8731    };
8732    ptr::write_bytes(
8733        &mut cctxParams as *mut ZSTD_CCtx_params as *mut u8,
8734        0,
8735        ::core::mem::size_of::<ZSTD_CCtx_params>(),
8736    );
8737    ZSTD_CCtxParams_init(&mut cctxParams, 0);
8738    cctxParams.cParams = cParams;
8739    cctxParams.customMem = customMem;
8740    ZSTD_createCDict_advanced2(
8741        dictBuffer,
8742        dictSize,
8743        dictLoadMethod,
8744        dictContentType,
8745        &cctxParams,
8746        customMem,
8747    )
8748}
8749#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCDict_advanced2))]
8750pub unsafe extern "C" fn ZSTD_createCDict_advanced2(
8751    dict: *const core::ffi::c_void,
8752    dictSize: size_t,
8753    dictLoadMethod: ZSTD_dictLoadMethod_e,
8754    dictContentType: ZSTD_dictContentType_e,
8755    originalCctxParams: *const ZSTD_CCtx_params,
8756    customMem: ZSTD_customMem,
8757) -> *mut ZSTD_CDict {
8758    let mut cctxParams = *originalCctxParams;
8759    let mut cParams = ZSTD_compressionParameters {
8760        windowLog: 0,
8761        chainLog: 0,
8762        hashLog: 0,
8763        searchLog: 0,
8764        minMatch: 0,
8765        targetLength: 0,
8766        strategy: 0,
8767    };
8768    if cctxParams.enableDedicatedDictSearch != 0 {
8769        cParams = ZSTD_dedicatedDictSearch_getCParams(cctxParams.compressionLevel, dictSize);
8770        ZSTD_overrideCParams(&mut cParams, &cctxParams.cParams);
8771    } else {
8772        cParams = ZSTD_getCParamsFromCCtxParams(
8773            &cctxParams,
8774            ZSTD_CONTENTSIZE_UNKNOWN,
8775            dictSize,
8776            ZSTD_cpm_createCDict,
8777        );
8778    }
8779    if ZSTD_dedicatedDictSearch_isSupported(&cParams) == 0 {
8780        cctxParams.enableDedicatedDictSearch = 0;
8781        cParams = ZSTD_getCParamsFromCCtxParams(
8782            &cctxParams,
8783            ZSTD_CONTENTSIZE_UNKNOWN,
8784            dictSize,
8785            ZSTD_cpm_createCDict,
8786        );
8787    }
8788    cctxParams.cParams = cParams;
8789    cctxParams.useRowMatchFinder =
8790        ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
8791    let cdict = ZSTD_createCDict_advanced_internal(
8792        dictSize,
8793        dictLoadMethod,
8794        cctxParams.cParams,
8795        cctxParams.useRowMatchFinder,
8796        cctxParams.enableDedicatedDictSearch,
8797        customMem,
8798    );
8799    if cdict.is_null()
8800        || ERR_isError(ZSTD_initCDict_internal(
8801            cdict,
8802            dict,
8803            dictSize,
8804            dictLoadMethod,
8805            dictContentType,
8806            cctxParams,
8807        ))
8808    {
8809        ZSTD_freeCDict(cdict);
8810        return core::ptr::null_mut();
8811    }
8812    cdict
8813}
8814#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCDict))]
8815pub unsafe extern "C" fn ZSTD_createCDict(
8816    dict: *const core::ffi::c_void,
8817    dictSize: size_t,
8818    compressionLevel: core::ffi::c_int,
8819) -> *mut ZSTD_CDict {
8820    let cParams = ZSTD_getCParams_internal(
8821        compressionLevel,
8822        ZSTD_CONTENTSIZE_UNKNOWN,
8823        dictSize,
8824        ZSTD_cpm_createCDict,
8825    );
8826    let cdict = ZSTD_createCDict_advanced(
8827        dict,
8828        dictSize,
8829        ZSTD_dlm_byCopy,
8830        ZSTD_dct_auto,
8831        cParams,
8832        ZSTD_customMem::default(),
8833    );
8834    if !cdict.is_null() {
8835        (*cdict).compressionLevel = if compressionLevel == 0 {
8836            ZSTD_CLEVEL_DEFAULT
8837        } else {
8838            compressionLevel
8839        };
8840    }
8841    cdict
8842}
8843#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCDict_byReference))]
8844pub unsafe extern "C" fn ZSTD_createCDict_byReference(
8845    dict: *const core::ffi::c_void,
8846    dictSize: size_t,
8847    compressionLevel: core::ffi::c_int,
8848) -> *mut ZSTD_CDict {
8849    let cParams = ZSTD_getCParams_internal(
8850        compressionLevel,
8851        ZSTD_CONTENTSIZE_UNKNOWN,
8852        dictSize,
8853        ZSTD_cpm_createCDict,
8854    );
8855    let cdict = ZSTD_createCDict_advanced(
8856        dict,
8857        dictSize,
8858        ZSTD_dlm_byRef,
8859        ZSTD_dct_auto,
8860        cParams,
8861        ZSTD_customMem::default(),
8862    );
8863    if !cdict.is_null() {
8864        (*cdict).compressionLevel = if compressionLevel == 0 {
8865            ZSTD_CLEVEL_DEFAULT
8866        } else {
8867            compressionLevel
8868        };
8869    }
8870    cdict
8871}
8872#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_freeCDict))]
8873pub unsafe extern "C" fn ZSTD_freeCDict(cdict: *mut ZSTD_CDict) -> size_t {
8874    if cdict.is_null() {
8875        return 0;
8876    }
8877    let cMem = (*cdict).customMem;
8878    let cdictInWorkspace =
8879        ZSTD_cwksp_owns_buffer(&(*cdict).workspace, cdict as *const core::ffi::c_void);
8880    ZSTD_cwksp_free(&mut (*cdict).workspace, cMem);
8881    if cdictInWorkspace == 0 {
8882        ZSTD_customFree(
8883            cdict as *mut core::ffi::c_void,
8884            (*cdict).dictContentSize,
8885            cMem,
8886        );
8887    }
8888    0
8889}
8890#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initStaticCDict))]
8891pub unsafe extern "C" fn ZSTD_initStaticCDict(
8892    workspace: *mut core::ffi::c_void,
8893    workspaceSize: size_t,
8894    dict: *const core::ffi::c_void,
8895    dictSize: size_t,
8896    dictLoadMethod: ZSTD_dictLoadMethod_e,
8897    dictContentType: ZSTD_dictContentType_e,
8898    cParams: ZSTD_compressionParameters,
8899) -> *const ZSTD_CDict {
8900    let useRowMatchFinder =
8901        ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cParams);
8902    let matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, 1, 0);
8903    let neededSize = (ZSTD_cwksp_alloc_size(::core::mem::size_of::<ZSTD_CDict>()))
8904        .wrapping_add(if dictLoadMethod == ZSTD_dlm_byRef {
8905            0
8906        } else {
8907            ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(
8908                dictSize,
8909                ::core::mem::size_of::<*mut core::ffi::c_void>(),
8910            ))
8911        })
8912        .wrapping_add(ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE))
8913        .wrapping_add(matchStateSize);
8914    let mut cdict = core::ptr::null_mut::<ZSTD_CDict>();
8915    let mut params = ZSTD_CCtx_params_s {
8916        format: Format::ZSTD_f_zstd1,
8917        cParams: ZSTD_compressionParameters {
8918            windowLog: 0,
8919            chainLog: 0,
8920            hashLog: 0,
8921            searchLog: 0,
8922            minMatch: 0,
8923            targetLength: 0,
8924            strategy: 0,
8925        },
8926        fParams: ZSTD_frameParameters {
8927            contentSizeFlag: 0,
8928            checksumFlag: 0,
8929            noDictIDFlag: 0,
8930        },
8931        compressionLevel: 0,
8932        forceWindow: 0,
8933        targetCBlockSize: 0,
8934        srcSizeHint: 0,
8935        attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
8936        literalCompressionMode: ParamSwitch::Auto,
8937        nbWorkers: 0,
8938        jobSize: 0,
8939        overlapLog: 0,
8940        rsyncable: 0,
8941        ldmParams: ldmParams_t {
8942            enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8943            hashLog: 0,
8944            bucketSizeLog: 0,
8945            minMatchLength: 0,
8946            hashRateLog: 0,
8947            windowLog: 0,
8948        },
8949        enableDedicatedDictSearch: 0,
8950        inBufferMode: ZSTD_bm_buffered,
8951        outBufferMode: ZSTD_bm_buffered,
8952        blockDelimiters: ZSTD_sf_noBlockDelimiters,
8953        validateSequences: 0,
8954        postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8955        preBlockSplitter_level: 0,
8956        maxBlockSize: 0,
8957        useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8958        deterministicRefPrefix: 0,
8959        customMem: ZSTD_customMem::default(),
8960        prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8961        enableMatchFinderFallback: 0,
8962        extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
8963        extSeqProdFunc: None,
8964        searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
8965    };
8966    if workspace as size_t & 7 != 0 {
8967        return core::ptr::null();
8968    }
8969    let mut ws = ZSTD_cwksp {
8970        workspace: core::ptr::null_mut::<core::ffi::c_void>(),
8971        workspaceEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8972        objectEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8973        tableEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8974        tableValidEnd: core::ptr::null_mut::<core::ffi::c_void>(),
8975        allocStart: core::ptr::null_mut::<core::ffi::c_void>(),
8976        initOnceStart: core::ptr::null_mut::<core::ffi::c_void>(),
8977        allocFailed: 0,
8978        workspaceOversizedDuration: 0,
8979        phase: ZSTD_cwksp_alloc_objects,
8980        isStatic: ZSTD_cwksp_dynamic_alloc,
8981    };
8982    ZSTD_cwksp_init(&mut ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
8983    cdict =
8984        ZSTD_cwksp_reserve_object(&mut ws, ::core::mem::size_of::<ZSTD_CDict>()) as *mut ZSTD_CDict;
8985    if cdict.is_null() {
8986        return core::ptr::null();
8987    }
8988    ZSTD_cwksp_move(&mut (*cdict).workspace, &mut ws);
8989    if workspaceSize < neededSize {
8990        return core::ptr::null();
8991    }
8992    ZSTD_CCtxParams_init(&mut params, 0);
8993    params.cParams = cParams;
8994    params.useRowMatchFinder = useRowMatchFinder;
8995    (*cdict).useRowMatchFinder = useRowMatchFinder;
8996    (*cdict).compressionLevel = ZSTD_NO_CLEVEL;
8997    if ERR_isError(ZSTD_initCDict_internal(
8998        cdict,
8999        dict,
9000        dictSize,
9001        dictLoadMethod,
9002        dictContentType,
9003        params,
9004    )) {
9005        return core::ptr::null();
9006    }
9007    cdict
9008}
9009#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getCParamsFromCDict))]
9010pub unsafe extern "C" fn ZSTD_getCParamsFromCDict(
9011    cdict: *const ZSTD_CDict,
9012) -> ZSTD_compressionParameters {
9013    (*cdict).matchState.cParams
9014}
9015#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getDictID_fromCDict))]
9016pub unsafe extern "C" fn ZSTD_getDictID_fromCDict(cdict: *const ZSTD_CDict) -> core::ffi::c_uint {
9017    if cdict.is_null() {
9018        return 0;
9019    }
9020    (*cdict).dictID
9021}
9022unsafe fn ZSTD_compressBegin_usingCDict_internal(
9023    cctx: *mut ZSTD_CCtx,
9024    cdict: *const ZSTD_CDict,
9025    fParams: ZSTD_frameParameters,
9026    pledgedSrcSize: core::ffi::c_ulonglong,
9027) -> size_t {
9028    let mut cctxParams = ZSTD_CCtx_params_s {
9029        format: Format::ZSTD_f_zstd1,
9030        cParams: ZSTD_compressionParameters {
9031            windowLog: 0,
9032            chainLog: 0,
9033            hashLog: 0,
9034            searchLog: 0,
9035            minMatch: 0,
9036            targetLength: 0,
9037            strategy: 0,
9038        },
9039        fParams: ZSTD_frameParameters {
9040            contentSizeFlag: 0,
9041            checksumFlag: 0,
9042            noDictIDFlag: 0,
9043        },
9044        compressionLevel: 0,
9045        forceWindow: 0,
9046        targetCBlockSize: 0,
9047        srcSizeHint: 0,
9048        attachDictPref: ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach,
9049        literalCompressionMode: ParamSwitch::Auto,
9050        nbWorkers: 0,
9051        jobSize: 0,
9052        overlapLog: 0,
9053        rsyncable: 0,
9054        ldmParams: ldmParams_t {
9055            enableLdm: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
9056            hashLog: 0,
9057            bucketSizeLog: 0,
9058            minMatchLength: 0,
9059            hashRateLog: 0,
9060            windowLog: 0,
9061        },
9062        enableDedicatedDictSearch: 0,
9063        inBufferMode: ZSTD_bm_buffered,
9064        outBufferMode: ZSTD_bm_buffered,
9065        blockDelimiters: ZSTD_sf_noBlockDelimiters,
9066        validateSequences: 0,
9067        postBlockSplitter: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
9068        preBlockSplitter_level: 0,
9069        maxBlockSize: 0,
9070        useRowMatchFinder: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
9071        deterministicRefPrefix: 0,
9072        customMem: ZSTD_customMem::default(),
9073        prefetchCDictTables: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
9074        enableMatchFinderFallback: 0,
9075        extSeqProdState: core::ptr::null_mut::<core::ffi::c_void>(),
9076        extSeqProdFunc: None,
9077        searchForExternalRepcodes: ZSTD_ParamSwitch_e::ZSTD_ps_auto,
9078    };
9079    if cdict.is_null() {
9080        return Error::dictionary_wrong.to_error_code();
9081    }
9082    let mut params = ZSTD_parameters {
9083        cParams: ZSTD_compressionParameters {
9084            windowLog: 0,
9085            chainLog: 0,
9086            hashLog: 0,
9087            searchLog: 0,
9088            minMatch: 0,
9089            targetLength: 0,
9090            strategy: 0,
9091        },
9092        fParams: ZSTD_frameParameters {
9093            contentSizeFlag: 0,
9094            checksumFlag: 0,
9095            noDictIDFlag: 0,
9096        },
9097    };
9098    params.fParams = fParams;
9099    params.cParams = if pledgedSrcSize
9100        < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF as core::ffi::c_ulonglong
9101        || pledgedSrcSize
9102            < ((*cdict).dictContentSize as core::ffi::c_ulonglong)
9103                .wrapping_mul(ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER)
9104        || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
9105        || (*cdict).compressionLevel == 0
9106    {
9107        ZSTD_getCParamsFromCDict(cdict)
9108    } else {
9109        ZSTD_getCParams(
9110            (*cdict).compressionLevel,
9111            pledgedSrcSize,
9112            (*cdict).dictContentSize,
9113        )
9114    };
9115    ZSTD_CCtxParams_init_internal(&mut cctxParams, &params, (*cdict).compressionLevel);
9116    if pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN {
9117        let limitedSrcSize = (if pledgedSrcSize < ((1) << 19) as core::ffi::c_ulonglong {
9118            pledgedSrcSize
9119        } else {
9120            ((1) << 19) as core::ffi::c_ulonglong
9121        }) as u32;
9122        let limitedSrcLog = if limitedSrcSize > 1 {
9123            (ZSTD_highbit32(limitedSrcSize.wrapping_sub(1))).wrapping_add(1)
9124        } else {
9125            1
9126        };
9127        cctxParams.cParams.windowLog = if cctxParams.cParams.windowLog > limitedSrcLog {
9128            cctxParams.cParams.windowLog
9129        } else {
9130            limitedSrcLog
9131        };
9132    }
9133    ZSTD_compressBegin_internal(
9134        cctx,
9135        core::ptr::null(),
9136        0,
9137        ZSTD_dct_auto,
9138        ZSTD_dtlm_fast,
9139        cdict,
9140        &cctxParams,
9141        pledgedSrcSize,
9142        ZSTDb_not_buffered,
9143    )
9144}
9145#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBegin_usingCDict_advanced))]
9146pub unsafe extern "C" fn ZSTD_compressBegin_usingCDict_advanced(
9147    cctx: *mut ZSTD_CCtx,
9148    cdict: *const ZSTD_CDict,
9149    fParams: ZSTD_frameParameters,
9150    pledgedSrcSize: core::ffi::c_ulonglong,
9151) -> size_t {
9152    ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize)
9153}
9154#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBegin_usingCDict_deprecated))]
9155pub unsafe extern "C" fn ZSTD_compressBegin_usingCDict_deprecated(
9156    cctx: *mut ZSTD_CCtx,
9157    cdict: *const ZSTD_CDict,
9158) -> size_t {
9159    let fParams = {
9160        ZSTD_frameParameters {
9161            contentSizeFlag: 0,
9162            checksumFlag: 0,
9163            noDictIDFlag: 0,
9164        }
9165    };
9166    ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN)
9167}
9168#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressBegin_usingCDict))]
9169pub unsafe extern "C" fn ZSTD_compressBegin_usingCDict(
9170    cctx: *mut ZSTD_CCtx,
9171    cdict: *const ZSTD_CDict,
9172) -> size_t {
9173    ZSTD_compressBegin_usingCDict_deprecated(cctx, cdict)
9174}
9175unsafe fn ZSTD_compress_usingCDict_internal(
9176    cctx: *mut ZSTD_CCtx,
9177    dst: *mut core::ffi::c_void,
9178    dstCapacity: size_t,
9179    src: *const core::ffi::c_void,
9180    srcSize: size_t,
9181    cdict: *const ZSTD_CDict,
9182    fParams: ZSTD_frameParameters,
9183) -> size_t {
9184    let err_code = ZSTD_compressBegin_usingCDict_internal(
9185        cctx,
9186        cdict,
9187        fParams,
9188        srcSize as core::ffi::c_ulonglong,
9189    );
9190    if ERR_isError(err_code) {
9191        return err_code;
9192    }
9193    ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize)
9194}
9195#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compress_usingCDict_advanced))]
9196pub unsafe extern "C" fn ZSTD_compress_usingCDict_advanced(
9197    cctx: *mut ZSTD_CCtx,
9198    dst: *mut core::ffi::c_void,
9199    dstCapacity: size_t,
9200    src: *const core::ffi::c_void,
9201    srcSize: size_t,
9202    cdict: *const ZSTD_CDict,
9203    fParams: ZSTD_frameParameters,
9204) -> size_t {
9205    ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams)
9206}
9207#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compress_usingCDict))]
9208pub unsafe extern "C" fn ZSTD_compress_usingCDict(
9209    cctx: *mut ZSTD_CCtx,
9210    dst: *mut core::ffi::c_void,
9211    dstCapacity: size_t,
9212    src: *const core::ffi::c_void,
9213    srcSize: size_t,
9214    cdict: *const ZSTD_CDict,
9215) -> size_t {
9216    let fParams = {
9217        ZSTD_frameParameters {
9218            contentSizeFlag: 1,
9219            checksumFlag: 0,
9220            noDictIDFlag: 0,
9221        }
9222    };
9223    ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams)
9224}
9225#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCStream))]
9226pub unsafe extern "C" fn ZSTD_createCStream() -> *mut ZSTD_CStream {
9227    ZSTD_createCStream_advanced(ZSTD_customMem::default())
9228}
9229#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initStaticCStream))]
9230pub unsafe extern "C" fn ZSTD_initStaticCStream(
9231    workspace: *mut core::ffi::c_void,
9232    workspaceSize: size_t,
9233) -> *mut ZSTD_CStream {
9234    ZSTD_initStaticCCtx(workspace, workspaceSize)
9235}
9236#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createCStream_advanced))]
9237pub unsafe extern "C" fn ZSTD_createCStream_advanced(
9238    customMem: ZSTD_customMem,
9239) -> *mut ZSTD_CStream {
9240    ZSTD_createCCtx_advanced(customMem)
9241}
9242#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_freeCStream))]
9243pub unsafe extern "C" fn ZSTD_freeCStream(zcs: *mut ZSTD_CStream) -> size_t {
9244    ZSTD_freeCCtx(zcs)
9245}
9246#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CStreamInSize))]
9247pub unsafe extern "C" fn ZSTD_CStreamInSize() -> size_t {
9248    ZSTD_BLOCKSIZE_MAX as size_t
9249}
9250#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CStreamOutSize))]
9251pub unsafe extern "C" fn ZSTD_CStreamOutSize() -> size_t {
9252    (ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX as size_t))
9253        .wrapping_add(ZSTD_blockHeaderSize)
9254        .wrapping_add(4)
9255}
9256unsafe fn ZSTD_getCParamMode(
9257    cdict: *const ZSTD_CDict,
9258    params: *const ZSTD_CCtx_params,
9259    pledgedSrcSize: u64,
9260) -> ZSTD_CParamMode_e {
9261    if !cdict.is_null() && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize) != 0 {
9262        ZSTD_cpm_attachDict
9263    } else {
9264        ZSTD_cpm_noAttachDict
9265    }
9266}
9267#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_resetCStream))]
9268pub unsafe extern "C" fn ZSTD_resetCStream(
9269    zcs: *mut ZSTD_CStream,
9270    pss: core::ffi::c_ulonglong,
9271) -> size_t {
9272    let pledgedSrcSize = if pss == 0 {
9273        ZSTD_CONTENTSIZE_UNKNOWN
9274    } else {
9275        pss
9276    };
9277    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9278    if ERR_isError(err_code) {
9279        return err_code;
9280    }
9281    let err_code_0 = ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize as core::ffi::c_ulonglong);
9282    if ERR_isError(err_code_0) {
9283        return err_code_0;
9284    }
9285    0
9286}
9287pub unsafe fn ZSTD_initCStream_internal(
9288    zcs: *mut ZSTD_CStream,
9289    dict: *const core::ffi::c_void,
9290    dictSize: size_t,
9291    cdict: *const ZSTD_CDict,
9292    params: *const ZSTD_CCtx_params,
9293    pledgedSrcSize: core::ffi::c_ulonglong,
9294) -> size_t {
9295    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9296    if ERR_isError(err_code) {
9297        return err_code;
9298    }
9299    let err_code_0 = ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
9300    if ERR_isError(err_code_0) {
9301        return err_code_0;
9302    }
9303    (*zcs).requestedParams = *params;
9304    if !dict.is_null() {
9305        let err_code_1 = ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
9306        if ERR_isError(err_code_1) {
9307            return err_code_1;
9308        }
9309    } else {
9310        let err_code_2 = ZSTD_CCtx_refCDict(zcs, cdict);
9311        if ERR_isError(err_code_2) {
9312            return err_code_2;
9313        }
9314    }
9315    0
9316}
9317#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initCStream_usingCDict_advanced))]
9318pub unsafe extern "C" fn ZSTD_initCStream_usingCDict_advanced(
9319    zcs: *mut ZSTD_CStream,
9320    cdict: *const ZSTD_CDict,
9321    fParams: ZSTD_frameParameters,
9322    pledgedSrcSize: core::ffi::c_ulonglong,
9323) -> size_t {
9324    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9325    if ERR_isError(err_code) {
9326        return err_code;
9327    }
9328    let err_code_0 = ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
9329    if ERR_isError(err_code_0) {
9330        return err_code_0;
9331    }
9332    (*zcs).requestedParams.fParams = fParams;
9333    let err_code_1 = ZSTD_CCtx_refCDict(zcs, cdict);
9334    if ERR_isError(err_code_1) {
9335        return err_code_1;
9336    }
9337    0
9338}
9339#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initCStream_usingCDict))]
9340pub unsafe extern "C" fn ZSTD_initCStream_usingCDict(
9341    zcs: *mut ZSTD_CStream,
9342    cdict: *const ZSTD_CDict,
9343) -> size_t {
9344    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9345    if ERR_isError(err_code) {
9346        return err_code;
9347    }
9348    let err_code_0 = ZSTD_CCtx_refCDict(zcs, cdict);
9349    if ERR_isError(err_code_0) {
9350        return err_code_0;
9351    }
9352    0
9353}
9354#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initCStream_advanced))]
9355pub unsafe extern "C" fn ZSTD_initCStream_advanced(
9356    zcs: *mut ZSTD_CStream,
9357    dict: *const core::ffi::c_void,
9358    dictSize: size_t,
9359    params: ZSTD_parameters,
9360    pss: core::ffi::c_ulonglong,
9361) -> size_t {
9362    let pledgedSrcSize = if pss == 0 && params.fParams.contentSizeFlag == 0 {
9363        ZSTD_CONTENTSIZE_UNKNOWN
9364    } else {
9365        pss
9366    };
9367    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9368    if ERR_isError(err_code) {
9369        return err_code;
9370    }
9371    let err_code_0 = ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize as core::ffi::c_ulonglong);
9372    if ERR_isError(err_code_0) {
9373        return err_code_0;
9374    }
9375    let err_code_1 = ZSTD_checkCParams(params.cParams);
9376    if ERR_isError(err_code_1) {
9377        return err_code_1;
9378    }
9379    ZSTD_CCtxParams_setZstdParams(&mut (*zcs).requestedParams, &params);
9380    let err_code_2 = ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
9381    if ERR_isError(err_code_2) {
9382        return err_code_2;
9383    }
9384    0
9385}
9386#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initCStream_usingDict))]
9387pub unsafe extern "C" fn ZSTD_initCStream_usingDict(
9388    zcs: *mut ZSTD_CStream,
9389    dict: *const core::ffi::c_void,
9390    dictSize: size_t,
9391    compressionLevel: core::ffi::c_int,
9392) -> size_t {
9393    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9394    if ERR_isError(err_code) {
9395        return err_code;
9396    }
9397    let err_code_0 = ZSTD_CCtx_setParameter(
9398        zcs,
9399        ZSTD_cParameter::ZSTD_c_compressionLevel,
9400        compressionLevel,
9401    );
9402    if ERR_isError(err_code_0) {
9403        return err_code_0;
9404    }
9405    let err_code_1 = ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
9406    if ERR_isError(err_code_1) {
9407        return err_code_1;
9408    }
9409    0
9410}
9411#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initCStream_srcSize))]
9412pub unsafe extern "C" fn ZSTD_initCStream_srcSize(
9413    zcs: *mut ZSTD_CStream,
9414    compressionLevel: core::ffi::c_int,
9415    pss: core::ffi::c_ulonglong,
9416) -> size_t {
9417    let pledgedSrcSize = if pss == 0 {
9418        ZSTD_CONTENTSIZE_UNKNOWN
9419    } else {
9420        pss
9421    };
9422    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9423    if ERR_isError(err_code) {
9424        return err_code;
9425    }
9426    let err_code_0 = ZSTD_CCtx_refCDict(zcs, core::ptr::null::<ZSTD_CDict>());
9427    if ERR_isError(err_code_0) {
9428        return err_code_0;
9429    }
9430    let err_code_1 = ZSTD_CCtx_setParameter(
9431        zcs,
9432        ZSTD_cParameter::ZSTD_c_compressionLevel,
9433        compressionLevel,
9434    );
9435    if ERR_isError(err_code_1) {
9436        return err_code_1;
9437    }
9438    let err_code_2 = ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize as core::ffi::c_ulonglong);
9439    if ERR_isError(err_code_2) {
9440        return err_code_2;
9441    }
9442    0
9443}
9444#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initCStream))]
9445pub unsafe extern "C" fn ZSTD_initCStream(
9446    zcs: *mut ZSTD_CStream,
9447    compressionLevel: core::ffi::c_int,
9448) -> size_t {
9449    let err_code = ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9450    if ERR_isError(err_code) {
9451        return err_code;
9452    }
9453    let err_code_0 = ZSTD_CCtx_refCDict(zcs, core::ptr::null::<ZSTD_CDict>());
9454    if ERR_isError(err_code_0) {
9455        return err_code_0;
9456    }
9457    let err_code_1 = ZSTD_CCtx_setParameter(
9458        zcs,
9459        ZSTD_cParameter::ZSTD_c_compressionLevel,
9460        compressionLevel,
9461    );
9462    if ERR_isError(err_code_1) {
9463        return err_code_1;
9464    }
9465    0
9466}
9467unsafe fn ZSTD_nextInputSizeHint(cctx: *const ZSTD_CCtx) -> size_t {
9468    if (*cctx).appliedParams.inBufferMode as core::ffi::c_uint
9469        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9470    {
9471        return ((*cctx).blockSizeMax).wrapping_sub((*cctx).stableIn_notConsumed);
9472    }
9473    let mut hintInSize = ((*cctx).inBuffTarget).wrapping_sub((*cctx).inBuffPos);
9474    if hintInSize == 0 {
9475        hintInSize = (*cctx).blockSizeMax;
9476    }
9477    hintInSize
9478}
9479unsafe fn ZSTD_compressStream_generic(
9480    zcs: *mut ZSTD_CStream,
9481    output: *mut ZSTD_outBuffer,
9482    input: *mut ZSTD_inBuffer,
9483    flushMode: ZSTD_EndDirective,
9484) -> size_t {
9485    let istart = (*input).src as *const u8;
9486    let iend = if !istart.is_null() {
9487        istart.add((*input).size)
9488    } else {
9489        istart
9490    };
9491    let mut ip = if !istart.is_null() {
9492        istart.add((*input).pos)
9493    } else {
9494        istart
9495    };
9496    let ostart = (*output).dst as *mut u8;
9497    let oend = if !ostart.is_null() {
9498        ostart.add((*output).size)
9499    } else {
9500        ostart
9501    };
9502    let mut op = if !ostart.is_null() {
9503        ostart.add((*output).pos)
9504    } else {
9505        ostart
9506    };
9507    let mut someMoreWork = 1;
9508    if (*zcs).appliedParams.inBufferMode as core::ffi::c_uint
9509        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9510    {
9511        (*input).pos = ((*input).pos).wrapping_sub((*zcs).stableIn_notConsumed);
9512        if !ip.is_null() {
9513            ip = ip.offset(-((*zcs).stableIn_notConsumed as isize));
9514        }
9515        (*zcs).stableIn_notConsumed = 0;
9516    }
9517    if (*zcs).appliedParams.inBufferMode == ZSTD_bm_buffered {
9518        assert!(!(*zcs).inBuff.is_null());
9519        assert!((*zcs).inBuffSize > 0);
9520    }
9521    if (*zcs).appliedParams.outBufferMode == ZSTD_bm_buffered {
9522        assert!(!(*zcs).outBuff.is_null());
9523        assert!((*zcs).outBuffSize > 0);
9524    }
9525    ((*input).src).is_null();
9526    ((*output).dst).is_null();
9527    while someMoreWork != 0 {
9528        let mut current_block_156: u64;
9529        match (*zcs).streamStage as core::ffi::c_uint {
9530            0 => return Error::init_missing.to_error_code(),
9531            1 => {
9532                if flushMode as core::ffi::c_uint
9533                    == ZSTD_e_end as core::ffi::c_int as core::ffi::c_uint
9534                    && (oend.offset_from_unsigned(op)
9535                        >= ZSTD_compressBound(iend.offset_from_unsigned(ip))
9536                        || (*zcs).appliedParams.outBufferMode as core::ffi::c_uint
9537                            == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint)
9538                    && (*zcs).inBuffPos == 0
9539                {
9540                    let cSize = ZSTD_compressEnd_public(
9541                        zcs,
9542                        op as *mut core::ffi::c_void,
9543                        oend.offset_from_unsigned(op),
9544                        ip as *const core::ffi::c_void,
9545                        iend.offset_from_unsigned(ip),
9546                    );
9547                    let err_code = cSize;
9548                    if ERR_isError(err_code) {
9549                        return err_code;
9550                    }
9551                    ip = iend;
9552                    op = op.add(cSize);
9553                    (*zcs).frameEnded = 1;
9554                    ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9555                    someMoreWork = 0;
9556                    current_block_156 = 16754622181974910496;
9557                } else {
9558                    if (*zcs).appliedParams.inBufferMode as core::ffi::c_uint
9559                        == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint
9560                    {
9561                        let toLoad = ((*zcs).inBuffTarget).wrapping_sub((*zcs).inBuffPos);
9562                        let loaded = ZSTD_limitCopy(
9563                            ((*zcs).inBuff).add((*zcs).inBuffPos),
9564                            toLoad,
9565                            ip,
9566                            iend.offset_from_unsigned(ip),
9567                        );
9568                        (*zcs).inBuffPos = ((*zcs).inBuffPos).wrapping_add(loaded);
9569                        if !ip.is_null() {
9570                            ip = ip.add(loaded);
9571                        }
9572                        if flushMode as core::ffi::c_uint
9573                            == ZSTD_e_continue as core::ffi::c_int as core::ffi::c_uint
9574                            && (*zcs).inBuffPos < (*zcs).inBuffTarget
9575                        {
9576                            someMoreWork = 0;
9577                            current_block_156 = 16754622181974910496;
9578                        } else if flushMode as core::ffi::c_uint
9579                            == ZSTD_e_flush as core::ffi::c_int as core::ffi::c_uint
9580                            && (*zcs).inBuffPos == (*zcs).inToCompress
9581                        {
9582                            someMoreWork = 0;
9583                            current_block_156 = 16754622181974910496;
9584                        } else {
9585                            current_block_156 = 13910774313357589740;
9586                        }
9587                    } else if flushMode as core::ffi::c_uint
9588                        == ZSTD_e_continue as core::ffi::c_int as core::ffi::c_uint
9589                        && (iend.offset_from_unsigned(ip)) < (*zcs).blockSizeMax
9590                    {
9591                        (*zcs).stableIn_notConsumed = iend.offset_from_unsigned(ip);
9592                        ip = iend;
9593                        someMoreWork = 0;
9594                        current_block_156 = 16754622181974910496;
9595                    } else if flushMode as core::ffi::c_uint
9596                        == ZSTD_e_flush as core::ffi::c_int as core::ffi::c_uint
9597                        && ip == iend
9598                    {
9599                        someMoreWork = 0;
9600                        current_block_156 = 16754622181974910496;
9601                    } else {
9602                        current_block_156 = 13910774313357589740;
9603                    }
9604                    match current_block_156 {
9605                        16754622181974910496 => {}
9606                        _ => {
9607                            let inputBuffered = ((*zcs).appliedParams.inBufferMode
9608                                as core::ffi::c_uint
9609                                == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint)
9610                                as core::ffi::c_int;
9611                            let mut cDst = core::ptr::null_mut::<core::ffi::c_void>();
9612                            let mut cSize_0: size_t = 0;
9613                            let mut oSize = oend.offset_from_unsigned(op);
9614                            let iSize = if inputBuffered != 0 {
9615                                ((*zcs).inBuffPos).wrapping_sub((*zcs).inToCompress)
9616                            } else if (iend.offset_from_unsigned(ip)) < (*zcs).blockSizeMax {
9617                                iend.offset_from_unsigned(ip)
9618                            } else {
9619                                (*zcs).blockSizeMax
9620                            };
9621                            if oSize >= ZSTD_compressBound(iSize)
9622                                || (*zcs).appliedParams.outBufferMode as core::ffi::c_uint
9623                                    == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9624                            {
9625                                cDst = op as *mut core::ffi::c_void;
9626                            } else {
9627                                cDst = (*zcs).outBuff as *mut core::ffi::c_void;
9628                                oSize = (*zcs).outBuffSize;
9629                            }
9630                            if inputBuffered != 0 {
9631                                let lastBlock = (flushMode as core::ffi::c_uint
9632                                    == ZSTD_e_end as core::ffi::c_int as core::ffi::c_uint
9633                                    && ip == iend)
9634                                    as core::ffi::c_int
9635                                    as core::ffi::c_uint;
9636                                cSize_0 = if lastBlock != 0 {
9637                                    ZSTD_compressEnd_public(
9638                                        zcs,
9639                                        cDst,
9640                                        oSize,
9641                                        ((*zcs).inBuff).add((*zcs).inToCompress)
9642                                            as *const core::ffi::c_void,
9643                                        iSize,
9644                                    )
9645                                } else {
9646                                    ZSTD_compressContinue_public(
9647                                        zcs,
9648                                        cDst,
9649                                        oSize,
9650                                        ((*zcs).inBuff).add((*zcs).inToCompress)
9651                                            as *const core::ffi::c_void,
9652                                        iSize,
9653                                    )
9654                                };
9655                                let err_code_0 = cSize_0;
9656                                if ERR_isError(err_code_0) {
9657                                    return err_code_0;
9658                                }
9659                                (*zcs).frameEnded = lastBlock;
9660                                (*zcs).inBuffTarget =
9661                                    ((*zcs).inBuffPos).wrapping_add((*zcs).blockSizeMax);
9662                                if (*zcs).inBuffTarget > (*zcs).inBuffSize {
9663                                    (*zcs).inBuffPos = 0;
9664                                    (*zcs).inBuffTarget = (*zcs).blockSizeMax;
9665                                }
9666                                if lastBlock == 0 {
9667                                    assert!((*zcs).inBuffTarget <= (*zcs).inBuffSize);
9668                                }
9669                                (*zcs).inToCompress = (*zcs).inBuffPos;
9670                            } else {
9671                                let lastBlock_0 = (flushMode as core::ffi::c_uint
9672                                    == ZSTD_e_end as core::ffi::c_int as core::ffi::c_uint
9673                                    && ip.add(iSize) == iend)
9674                                    as core::ffi::c_int
9675                                    as core::ffi::c_uint;
9676                                cSize_0 = if lastBlock_0 != 0 {
9677                                    ZSTD_compressEnd_public(
9678                                        zcs,
9679                                        cDst,
9680                                        oSize,
9681                                        ip as *const core::ffi::c_void,
9682                                        iSize,
9683                                    )
9684                                } else {
9685                                    ZSTD_compressContinue_public(
9686                                        zcs,
9687                                        cDst,
9688                                        oSize,
9689                                        ip as *const core::ffi::c_void,
9690                                        iSize,
9691                                    )
9692                                };
9693                                if !ip.is_null() {
9694                                    ip = ip.add(iSize);
9695                                }
9696                                let err_code_1 = cSize_0;
9697                                if ERR_isError(err_code_1) {
9698                                    return err_code_1;
9699                                }
9700                                (*zcs).frameEnded = lastBlock_0;
9701                                if lastBlock_0 != 0 {
9702                                    assert_eq!(ip, iend);
9703                                }
9704                            }
9705                            if cDst == op as *mut core::ffi::c_void {
9706                                op = op.add(cSize_0);
9707                                if (*zcs).frameEnded != 0 {
9708                                    someMoreWork = 0;
9709                                    ZSTD_CCtx_reset(
9710                                        zcs,
9711                                        ZSTD_ResetDirective::ZSTD_reset_session_only,
9712                                    );
9713                                }
9714                                current_block_156 = 16754622181974910496;
9715                            } else {
9716                                (*zcs).outBuffContentSize = cSize_0;
9717                                (*zcs).outBuffFlushedSize = 0;
9718                                (*zcs).streamStage = zcss_flush;
9719                                current_block_156 = 5431927413890720344;
9720                            }
9721                        }
9722                    }
9723                }
9724            }
9725            2 => {
9726                current_block_156 = 5431927413890720344;
9727            }
9728            _ => {
9729                current_block_156 = 16754622181974910496;
9730            }
9731        }
9732        if current_block_156 == 5431927413890720344 {
9733            let toFlush = ((*zcs).outBuffContentSize).wrapping_sub((*zcs).outBuffFlushedSize);
9734            let flushed = ZSTD_limitCopy(
9735                op,
9736                oend.offset_from_unsigned(op),
9737                ((*zcs).outBuff).add((*zcs).outBuffFlushedSize),
9738                toFlush,
9739            );
9740            if flushed != 0 {
9741                op = op.add(flushed);
9742            }
9743            (*zcs).outBuffFlushedSize = ((*zcs).outBuffFlushedSize).wrapping_add(flushed);
9744            if toFlush != flushed {
9745                someMoreWork = 0;
9746            } else {
9747                (*zcs).outBuffFlushedSize = 0;
9748                (*zcs).outBuffContentSize = (*zcs).outBuffFlushedSize;
9749                if (*zcs).frameEnded != 0 {
9750                    someMoreWork = 0;
9751                    ZSTD_CCtx_reset(zcs, ZSTD_ResetDirective::ZSTD_reset_session_only);
9752                } else {
9753                    (*zcs).streamStage = zcss_load;
9754                }
9755            }
9756        }
9757    }
9758    (*input).pos = ip.offset_from_unsigned(istart);
9759    (*output).pos = op.offset_from_unsigned(ostart);
9760    if (*zcs).frameEnded != 0 {
9761        return 0;
9762    }
9763    ZSTD_nextInputSizeHint(zcs)
9764}
9765unsafe fn ZSTD_nextInputSizeHint_MTorST(cctx: *const ZSTD_CCtx) -> size_t {
9766    if (*cctx).appliedParams.nbWorkers >= 1 {
9767        return ZSTDMT_nextInputSizeHint((*cctx).mtctx);
9768    }
9769    ZSTD_nextInputSizeHint(cctx)
9770}
9771#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressStream))]
9772pub unsafe extern "C" fn ZSTD_compressStream(
9773    zcs: *mut ZSTD_CStream,
9774    output: *mut ZSTD_outBuffer,
9775    input: *mut ZSTD_inBuffer,
9776) -> size_t {
9777    let err_code = ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue);
9778    if ERR_isError(err_code) {
9779        return err_code;
9780    }
9781    ZSTD_nextInputSizeHint_MTorST(zcs)
9782}
9783unsafe fn ZSTD_setBufferExpectations(
9784    cctx: *mut ZSTD_CCtx,
9785    output: *const ZSTD_outBuffer,
9786    input: *const ZSTD_inBuffer,
9787) {
9788    if (*cctx).appliedParams.inBufferMode as core::ffi::c_uint
9789        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9790    {
9791        (*cctx).expectedInBuffer = *input;
9792    }
9793    if (*cctx).appliedParams.outBufferMode as core::ffi::c_uint
9794        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9795    {
9796        (*cctx).expectedOutBufferSize = ((*output).size).wrapping_sub((*output).pos);
9797    }
9798}
9799unsafe fn ZSTD_checkBufferStability(
9800    cctx: *const ZSTD_CCtx,
9801    output: *const ZSTD_outBuffer,
9802    input: *const ZSTD_inBuffer,
9803    _endOp: ZSTD_EndDirective,
9804) -> size_t {
9805    if (*cctx).appliedParams.inBufferMode as core::ffi::c_uint
9806        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9807    {
9808        let expect = (*cctx).expectedInBuffer;
9809        if expect.src != (*input).src || expect.pos != (*input).pos {
9810            return Error::stabilityCondition_notRespected.to_error_code();
9811        }
9812    }
9813    if (*cctx).appliedParams.outBufferMode as core::ffi::c_uint
9814        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9815    {
9816        let outBufferSize = ((*output).size).wrapping_sub((*output).pos);
9817        if (*cctx).expectedOutBufferSize != outBufferSize {
9818            return Error::stabilityCondition_notRespected.to_error_code();
9819        }
9820    }
9821    0
9822}
9823unsafe fn ZSTD_CCtx_init_compressStream2(
9824    cctx: *mut ZSTD_CCtx,
9825    endOp: ZSTD_EndDirective,
9826    inSize: size_t,
9827) -> size_t {
9828    let mut params = (*cctx).requestedParams;
9829    let prefixDict = (*cctx).prefixDict;
9830    let err_code = ZSTD_initLocalDict(cctx);
9831    if ERR_isError(err_code) {
9832        return err_code;
9833    }
9834    ptr::write_bytes(
9835        &mut (*cctx).prefixDict as *mut ZSTD_prefixDict as *mut u8,
9836        0,
9837        ::core::mem::size_of::<ZSTD_prefixDict>(),
9838    );
9839    if !((*cctx).cdict).is_null() && ((*cctx).localDict.cdict).is_null() {
9840        params.compressionLevel = (*(*cctx).cdict).compressionLevel;
9841    }
9842    if endOp as core::ffi::c_uint == ZSTD_e_end as core::ffi::c_int as core::ffi::c_uint {
9843        (*cctx).pledgedSrcSizePlusOne = inSize.wrapping_add(1) as core::ffi::c_ulonglong;
9844    }
9845    let dictSize = if !(prefixDict.dict).is_null() {
9846        prefixDict.dictSize
9847    } else if !((*cctx).cdict).is_null() {
9848        (*(*cctx).cdict).dictContentSize
9849    } else {
9850        0
9851    };
9852    let mode = ZSTD_getCParamMode(
9853        (*cctx).cdict,
9854        &params,
9855        ((*cctx).pledgedSrcSizePlusOne).wrapping_sub(1),
9856    );
9857    params.cParams = ZSTD_getCParamsFromCCtxParams(
9858        &params,
9859        ((*cctx).pledgedSrcSizePlusOne).wrapping_sub(1),
9860        dictSize,
9861        mode,
9862    );
9863    params.postBlockSplitter =
9864        ZSTD_resolveBlockSplitterMode(params.postBlockSplitter, &params.cParams);
9865    params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, &params.cParams);
9866    params.useRowMatchFinder =
9867        ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
9868    params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences);
9869    params.maxBlockSize = ZSTD_resolveMaxBlockSize(params.maxBlockSize);
9870    params.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(
9871        params.searchForExternalRepcodes,
9872        params.compressionLevel,
9873    );
9874    if ZSTD_hasExtSeqProd(&params) != 0 && params.nbWorkers >= 1 {
9875        return Error::parameter_combination_unsupported.to_error_code();
9876    }
9877    if ((*cctx).pledgedSrcSizePlusOne).wrapping_sub(1)
9878        <= ZSTDMT_JOBSIZE_MIN as core::ffi::c_ulonglong
9879    {
9880        params.nbWorkers = 0;
9881    }
9882    if params.nbWorkers > 0 {
9883        (*cctx).traceCtx = ZSTD_trace_compress_begin(cctx);
9884        if ((*cctx).mtctx).is_null() {
9885            (*cctx).mtctx = ZSTDMT_createCCtx_advanced(
9886                params.nbWorkers as u32,
9887                (*cctx).customMem,
9888                (*cctx).pool,
9889            );
9890            if ((*cctx).mtctx).is_null() {
9891                return Error::memory_allocation.to_error_code();
9892            }
9893        }
9894        let err_code_0 = ZSTDMT_initCStream_internal(
9895            (*cctx).mtctx,
9896            prefixDict.dict,
9897            prefixDict.dictSize,
9898            prefixDict.dictContentType,
9899            (*cctx).cdict,
9900            params,
9901            ((*cctx).pledgedSrcSizePlusOne).wrapping_sub(1),
9902        );
9903        if ERR_isError(err_code_0) {
9904            return err_code_0;
9905        }
9906        (*cctx).dictID = if !((*cctx).cdict).is_null() {
9907            (*(*cctx).cdict).dictID
9908        } else {
9909            0
9910        };
9911        (*cctx).dictContentSize = if !((*cctx).cdict).is_null() {
9912            (*(*cctx).cdict).dictContentSize
9913        } else {
9914            prefixDict.dictSize
9915        };
9916        (*cctx).consumedSrcSize = 0;
9917        (*cctx).producedCSize = 0;
9918        (*cctx).streamStage = zcss_load;
9919        (*cctx).appliedParams = params;
9920    } else {
9921        let pledgedSrcSize = ((*cctx).pledgedSrcSizePlusOne).wrapping_sub(1);
9922        let err_code_1 = ZSTD_compressBegin_internal(
9923            cctx,
9924            prefixDict.dict,
9925            prefixDict.dictSize,
9926            prefixDict.dictContentType,
9927            ZSTD_dtlm_fast,
9928            (*cctx).cdict,
9929            &params,
9930            pledgedSrcSize,
9931            ZSTDb_buffered,
9932        );
9933        if ERR_isError(err_code_1) {
9934            return err_code_1;
9935        }
9936        (*cctx).inToCompress = 0;
9937        (*cctx).inBuffPos = 0;
9938        if (*cctx).appliedParams.inBufferMode as core::ffi::c_uint
9939            == ZSTD_bm_buffered as core::ffi::c_int as core::ffi::c_uint
9940        {
9941            (*cctx).inBuffTarget = ((*cctx).blockSizeMax).wrapping_add(
9942                ((*cctx).blockSizeMax as u64 == pledgedSrcSize) as core::ffi::c_int as size_t,
9943            );
9944        } else {
9945            (*cctx).inBuffTarget = 0;
9946        }
9947        (*cctx).outBuffFlushedSize = 0;
9948        (*cctx).outBuffContentSize = (*cctx).outBuffFlushedSize;
9949        (*cctx).streamStage = zcss_load;
9950        (*cctx).frameEnded = 0;
9951    }
9952    0
9953}
9954#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressStream2))]
9955pub unsafe extern "C" fn ZSTD_compressStream2(
9956    cctx: *mut ZSTD_CCtx,
9957    output: *mut ZSTD_outBuffer,
9958    input: *mut ZSTD_inBuffer,
9959    endOp: ZSTD_EndDirective,
9960) -> size_t {
9961    if (*output).pos > (*output).size {
9962        return Error::dstSize_tooSmall.to_error_code();
9963    }
9964    if (*input).pos > (*input).size {
9965        return Error::srcSize_wrong.to_error_code();
9966    }
9967    if endOp > ZSTD_e_end as core::ffi::c_int as u32 {
9968        return Error::parameter_outOfBound.to_error_code();
9969    }
9970    if (*cctx).streamStage as core::ffi::c_uint
9971        == zcss_init as core::ffi::c_int as core::ffi::c_uint
9972    {
9973        let inputSize = ((*input).size).wrapping_sub((*input).pos);
9974        let totalInputSize = inputSize.wrapping_add((*cctx).stableIn_notConsumed);
9975        if (*cctx).requestedParams.inBufferMode as core::ffi::c_uint
9976            == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint
9977            && endOp as core::ffi::c_uint
9978                == ZSTD_e_continue as core::ffi::c_int as core::ffi::c_uint
9979            && totalInputSize < ZSTD_BLOCKSIZE_MAX as size_t
9980        {
9981            if (*cctx).stableIn_notConsumed != 0 {
9982                if (*input).src != (*cctx).expectedInBuffer.src {
9983                    return -(ZSTD_error_stabilityCondition_notRespected as core::ffi::c_int)
9984                        as size_t;
9985                }
9986                if (*input).pos != (*cctx).expectedInBuffer.size {
9987                    return -(ZSTD_error_stabilityCondition_notRespected as core::ffi::c_int)
9988                        as size_t;
9989                }
9990            }
9991            (*input).pos = (*input).size;
9992            (*cctx).expectedInBuffer = *input;
9993            (*cctx).stableIn_notConsumed = ((*cctx).stableIn_notConsumed).wrapping_add(inputSize);
9994            return (if (*cctx).requestedParams.format == Format::ZSTD_f_zstd1 {
9995                6
9996            } else {
9997                2
9998            }) as size_t;
9999        }
10000        let err_code = ZSTD_CCtx_init_compressStream2(cctx, endOp, totalInputSize);
10001        if ERR_isError(err_code) {
10002            return err_code;
10003        }
10004        ZSTD_setBufferExpectations(cctx, output, input);
10005    }
10006    let err_code_0 = ZSTD_checkBufferStability(cctx, output, input, endOp);
10007    if ERR_isError(err_code_0) {
10008        return err_code_0;
10009    }
10010    if (*cctx).appliedParams.nbWorkers > 0 {
10011        let mut flushMin: size_t = 0;
10012        if (*cctx).cParamsChanged != 0 {
10013            ZSTDMT_updateCParams_whileCompressing((*cctx).mtctx, &(*cctx).requestedParams);
10014            (*cctx).cParamsChanged = 0;
10015        }
10016        if (*cctx).stableIn_notConsumed != 0 {
10017            (*input).pos = ((*input).pos).wrapping_sub((*cctx).stableIn_notConsumed);
10018            (*cctx).stableIn_notConsumed = 0;
10019        }
10020        loop {
10021            let ipos = (*input).pos;
10022            let opos = (*output).pos;
10023            flushMin = ZSTDMT_compressStream_generic((*cctx).mtctx, output, input, endOp);
10024            (*cctx).consumedSrcSize = ((*cctx).consumedSrcSize)
10025                .wrapping_add(((*input).pos).wrapping_sub(ipos) as core::ffi::c_ulonglong);
10026            (*cctx).producedCSize = ((*cctx).producedCSize)
10027                .wrapping_add(((*output).pos).wrapping_sub(opos) as core::ffi::c_ulonglong);
10028            if ERR_isError(flushMin)
10029                || endOp as core::ffi::c_uint == ZSTD_e_end as core::ffi::c_int as core::ffi::c_uint
10030                    && flushMin == 0
10031            {
10032                if flushMin == 0 {
10033                    ZSTD_CCtx_trace(cctx, 0);
10034                }
10035                ZSTD_CCtx_reset(cctx, ZSTD_ResetDirective::ZSTD_reset_session_only);
10036            }
10037            let err_code_1 = flushMin;
10038            if ERR_isError(err_code_1) {
10039                return err_code_1;
10040            }
10041            if endOp as core::ffi::c_uint
10042                == ZSTD_e_continue as core::ffi::c_int as core::ffi::c_uint
10043            {
10044                if (*input).pos != ipos
10045                    || (*output).pos != opos
10046                    || (*input).pos == (*input).size
10047                    || (*output).pos == (*output).size
10048                {
10049                    break;
10050                }
10051            } else if flushMin == 0 || (*output).pos == (*output).size {
10052                break;
10053            }
10054        }
10055        ZSTD_setBufferExpectations(cctx, output, input);
10056        return flushMin;
10057    }
10058    let err_code_2 = ZSTD_compressStream_generic(cctx, output, input, endOp);
10059    if ERR_isError(err_code_2) {
10060        return err_code_2;
10061    }
10062    ZSTD_setBufferExpectations(cctx, output, input);
10063    ((*cctx).outBuffContentSize).wrapping_sub((*cctx).outBuffFlushedSize)
10064}
10065#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressStream2_simpleArgs))]
10066pub unsafe extern "C" fn ZSTD_compressStream2_simpleArgs(
10067    cctx: *mut ZSTD_CCtx,
10068    dst: *mut core::ffi::c_void,
10069    dstCapacity: size_t,
10070    dstPos: *mut size_t,
10071    src: *const core::ffi::c_void,
10072    srcSize: size_t,
10073    srcPos: *mut size_t,
10074    endOp: ZSTD_EndDirective,
10075) -> size_t {
10076    let mut output = ZSTD_outBuffer_s {
10077        dst: core::ptr::null_mut::<core::ffi::c_void>(),
10078        size: 0,
10079        pos: 0,
10080    };
10081    let mut input = ZSTD_inBuffer_s {
10082        src: core::ptr::null::<core::ffi::c_void>(),
10083        size: 0,
10084        pos: 0,
10085    };
10086    output.dst = dst;
10087    output.size = dstCapacity;
10088    output.pos = *dstPos;
10089    input.src = src;
10090    input.size = srcSize;
10091    input.pos = *srcPos;
10092    let cErr = ZSTD_compressStream2(cctx, &mut output, &mut input, endOp);
10093    *dstPos = output.pos;
10094    *srcPos = input.pos;
10095    cErr
10096}
10097#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compress2))]
10098pub unsafe extern "C" fn ZSTD_compress2(
10099    cctx: *mut ZSTD_CCtx,
10100    dst: *mut core::ffi::c_void,
10101    dstCapacity: size_t,
10102    src: *const core::ffi::c_void,
10103    srcSize: size_t,
10104) -> size_t {
10105    let originalInBufferMode = (*cctx).requestedParams.inBufferMode;
10106    let originalOutBufferMode = (*cctx).requestedParams.outBufferMode;
10107    ZSTD_CCtx_reset(cctx, ZSTD_ResetDirective::ZSTD_reset_session_only);
10108    (*cctx).requestedParams.inBufferMode = ZSTD_bm_stable;
10109    (*cctx).requestedParams.outBufferMode = ZSTD_bm_stable;
10110    let mut oPos = 0;
10111    let mut iPos = 0;
10112    let result = ZSTD_compressStream2_simpleArgs(
10113        cctx,
10114        dst,
10115        dstCapacity,
10116        &mut oPos,
10117        src,
10118        srcSize,
10119        &mut iPos,
10120        ZSTD_e_end,
10121    );
10122    (*cctx).requestedParams.inBufferMode = originalInBufferMode;
10123    (*cctx).requestedParams.outBufferMode = originalOutBufferMode;
10124    let err_code = result;
10125    if ERR_isError(err_code) {
10126        return err_code;
10127    }
10128    if result != 0 {
10129        return Error::dstSize_tooSmall.to_error_code();
10130    }
10131    oPos
10132}
10133unsafe fn ZSTD_validateSequence(
10134    offBase: u32,
10135    matchLength: u32,
10136    minMatch: u32,
10137    posInSrc: size_t,
10138    windowLog: u32,
10139    dictSize: size_t,
10140    useSequenceProducer: core::ffi::c_int,
10141) -> size_t {
10142    let windowSize = (1) << windowLog;
10143    let offsetBound = if posInSrc > windowSize as size_t {
10144        windowSize as size_t
10145    } else {
10146        posInSrc.wrapping_add(dictSize)
10147    };
10148    let matchLenLowerBound = (if minMatch == 3 || useSequenceProducer != 0 {
10149        3
10150    } else {
10151        4
10152    }) as size_t;
10153    if offBase as size_t > offsetBound.wrapping_add(3) {
10154        return Error::externalSequences_invalid.to_error_code();
10155    }
10156    if (matchLength as size_t) < matchLenLowerBound {
10157        return Error::externalSequences_invalid.to_error_code();
10158    }
10159    0
10160}
10161unsafe fn ZSTD_finalizeOffBase(rawOffset: u32, rep: *const u32, ll0: u32) -> u32 {
10162    let mut offBase = rawOffset.wrapping_add(ZSTD_REP_NUM as u32);
10163    if ll0 == 0 && rawOffset == *rep {
10164        offBase = REPCODE1_TO_OFFBASE as u32;
10165    } else if rawOffset == *rep.add(1) {
10166        offBase = 2u32.wrapping_sub(ll0);
10167    } else if rawOffset == *rep.add(2) {
10168        offBase = 3u32.wrapping_sub(ll0);
10169    } else if ll0 != 0 && rawOffset == (*rep).wrapping_sub(1) {
10170        offBase = REPCODE3_TO_OFFBASE as u32;
10171    }
10172    offBase
10173}
10174unsafe fn ZSTD_transferSequences_wBlockDelim(
10175    cctx: *mut ZSTD_CCtx,
10176    seqPos: *mut ZSTD_SequencePosition,
10177    inSeqs: *const ZSTD_Sequence,
10178    inSeqsSize: size_t,
10179    src: *const core::ffi::c_void,
10180    blockSize: size_t,
10181    externalRepSearch: ZSTD_ParamSwitch_e,
10182) -> size_t {
10183    let mut idx = (*seqPos).idx;
10184    let startIdx = idx;
10185    let mut ip = src as *const u8;
10186    let iend = ip.add(blockSize);
10187    let mut updatedRepcodes = repcodes_s { rep: [0; 3] };
10188    let mut dictSize: u32 = 0;
10189    if !((*cctx).cdict).is_null() {
10190        dictSize = (*(*cctx).cdict).dictContentSize as u32;
10191    } else if !((*cctx).prefixDict.dict).is_null() {
10192        dictSize = (*cctx).prefixDict.dictSize as u32;
10193    } else {
10194        dictSize = 0;
10195    }
10196    libc::memcpy(
10197        (updatedRepcodes.rep).as_mut_ptr() as *mut core::ffi::c_void,
10198        ((*(*cctx).blockState.prevCBlock).rep).as_mut_ptr() as *const core::ffi::c_void,
10199        ::core::mem::size_of::<Repcodes_t>(),
10200    );
10201    while (idx as size_t) < inSeqsSize
10202        && ((*inSeqs.offset(idx as isize)).matchLength != 0
10203            || (*inSeqs.offset(idx as isize)).offset != 0)
10204    {
10205        let litLength = (*inSeqs.offset(idx as isize)).litLength;
10206        let matchLength = (*inSeqs.offset(idx as isize)).matchLength;
10207        let mut offBase: u32 = 0;
10208        if externalRepSearch == ZSTD_ParamSwitch_e::ZSTD_ps_disable {
10209            offBase = ((*inSeqs.offset(idx as isize)).offset)
10210                .wrapping_add(ZSTD_REP_NUM as core::ffi::c_uint);
10211        } else {
10212            let ll0 = (litLength == 0) as core::ffi::c_int as u32;
10213            offBase = ZSTD_finalizeOffBase(
10214                (*inSeqs.offset(idx as isize)).offset,
10215                (updatedRepcodes.rep).as_mut_ptr() as *const u32,
10216                ll0,
10217            );
10218            ZSTD_updateRep((updatedRepcodes.rep).as_mut_ptr(), offBase, ll0);
10219        }
10220        if (*cctx).appliedParams.validateSequences != 0 {
10221            (*seqPos).posInSrc =
10222                ((*seqPos).posInSrc).wrapping_add(litLength.wrapping_add(matchLength) as size_t);
10223            let err_code = ZSTD_validateSequence(
10224                offBase,
10225                matchLength,
10226                (*cctx).appliedParams.cParams.minMatch,
10227                (*seqPos).posInSrc,
10228                (*cctx).appliedParams.cParams.windowLog,
10229                dictSize as size_t,
10230                ZSTD_hasExtSeqProd(&(*cctx).appliedParams),
10231            );
10232            if ERR_isError(err_code) {
10233                return err_code;
10234            }
10235        }
10236        if idx.wrapping_sub((*seqPos).idx) as size_t >= (*cctx).seqStore.maxNbSeq {
10237            return Error::externalSequences_invalid.to_error_code();
10238        }
10239        ZSTD_storeSeq(
10240            &mut (*cctx).seqStore,
10241            litLength as size_t,
10242            ip,
10243            iend,
10244            offBase,
10245            matchLength as size_t,
10246        );
10247        ip = ip.offset(matchLength.wrapping_add(litLength) as isize);
10248        idx = idx.wrapping_add(1);
10249    }
10250    if idx as size_t == inSeqsSize {
10251        return Error::externalSequences_invalid.to_error_code();
10252    }
10253    if externalRepSearch == ZSTD_ParamSwitch_e::ZSTD_ps_disable && idx != startIdx {
10254        let rep = (updatedRepcodes.rep).as_mut_ptr();
10255        let lastSeqIdx = idx.wrapping_sub(1);
10256        if lastSeqIdx >= startIdx.wrapping_add(2) {
10257            *rep.add(2) = (*inSeqs.offset(lastSeqIdx.wrapping_sub(2) as isize)).offset;
10258            *rep.add(1) = (*inSeqs.offset(lastSeqIdx.wrapping_sub(1) as isize)).offset;
10259            *rep = (*inSeqs.offset(lastSeqIdx as isize)).offset;
10260        } else if lastSeqIdx == startIdx.wrapping_add(1) {
10261            *rep.add(2) = *rep;
10262            *rep.add(1) = (*inSeqs.offset(lastSeqIdx.wrapping_sub(1) as isize)).offset;
10263            *rep = (*inSeqs.offset(lastSeqIdx as isize)).offset;
10264        } else {
10265            *rep.add(2) = *rep.add(1);
10266            *rep.add(1) = *rep;
10267            *rep = (*inSeqs.offset(lastSeqIdx as isize)).offset;
10268        }
10269    }
10270    libc::memcpy(
10271        ((*(*cctx).blockState.nextCBlock).rep).as_mut_ptr() as *mut core::ffi::c_void,
10272        (updatedRepcodes.rep).as_mut_ptr() as *const core::ffi::c_void,
10273        ::core::mem::size_of::<Repcodes_t>(),
10274    );
10275    if (*inSeqs.offset(idx as isize)).litLength != 0 {
10276        ZSTD_storeLastLiterals(
10277            &mut (*cctx).seqStore,
10278            ip,
10279            (*inSeqs.offset(idx as isize)).litLength as size_t,
10280        );
10281        ip = ip.offset((*inSeqs.offset(idx as isize)).litLength as isize);
10282        (*seqPos).posInSrc =
10283            ((*seqPos).posInSrc).wrapping_add((*inSeqs.offset(idx as isize)).litLength as size_t);
10284    }
10285    if ip != iend {
10286        return Error::externalSequences_invalid.to_error_code();
10287    }
10288    (*seqPos).idx = idx.wrapping_add(1);
10289    blockSize
10290}
10291unsafe fn ZSTD_transferSequences_noDelim(
10292    cctx: *mut ZSTD_CCtx,
10293    seqPos: *mut ZSTD_SequencePosition,
10294    inSeqs: *const ZSTD_Sequence,
10295    inSeqsSize: size_t,
10296    src: *const core::ffi::c_void,
10297    blockSize: size_t,
10298    externalRepSearch: ZSTD_ParamSwitch_e,
10299) -> size_t {
10300    let mut idx = (*seqPos).idx;
10301    let mut startPosInSequence = (*seqPos).posInSequence;
10302    let mut endPosInSequence = ((*seqPos).posInSequence).wrapping_add(blockSize as u32);
10303    let mut dictSize: size_t = 0;
10304    let istart = src as *const u8;
10305    let mut ip = istart;
10306    let mut iend = istart.add(blockSize);
10307    let mut updatedRepcodes = repcodes_s { rep: [0; 3] };
10308    let mut bytesAdjustment = 0;
10309    let mut finalMatchSplit = 0;
10310
10311    /* TODO(embg) support fast parsing mode in noBlockDelim mode */
10312    let _ = externalRepSearch;
10313
10314    if !((*cctx).cdict).is_null() {
10315        dictSize = (*(*cctx).cdict).dictContentSize;
10316    } else if !((*cctx).prefixDict.dict).is_null() {
10317        dictSize = (*cctx).prefixDict.dictSize;
10318    } else {
10319        dictSize = 0;
10320    }
10321    libc::memcpy(
10322        (updatedRepcodes.rep).as_mut_ptr() as *mut core::ffi::c_void,
10323        ((*(*cctx).blockState.prevCBlock).rep).as_mut_ptr() as *const core::ffi::c_void,
10324        ::core::mem::size_of::<Repcodes_t>(),
10325    );
10326    while endPosInSequence != 0 && (idx as size_t) < inSeqsSize && finalMatchSplit == 0 {
10327        let currSeq = *inSeqs.offset(idx as isize);
10328        let mut litLength = currSeq.litLength;
10329        let mut matchLength = currSeq.matchLength;
10330        let rawOffset = currSeq.offset;
10331        let mut offBase: u32 = 0;
10332        if endPosInSequence >= (currSeq.litLength).wrapping_add(currSeq.matchLength) {
10333            if startPosInSequence >= litLength {
10334                startPosInSequence = startPosInSequence.wrapping_sub(litLength);
10335                litLength = 0;
10336                matchLength = matchLength.wrapping_sub(startPosInSequence);
10337            } else {
10338                litLength = litLength.wrapping_sub(startPosInSequence);
10339            }
10340            endPosInSequence = (endPosInSequence as core::ffi::c_uint)
10341                .wrapping_sub((currSeq.litLength).wrapping_add(currSeq.matchLength));
10342            startPosInSequence = 0;
10343        } else {
10344            if endPosInSequence <= litLength {
10345                break;
10346            }
10347            let mut firstHalfMatchLength: u32 = 0;
10348            litLength = if startPosInSequence >= litLength {
10349                0
10350            } else {
10351                litLength.wrapping_sub(startPosInSequence)
10352            };
10353            firstHalfMatchLength = endPosInSequence
10354                .wrapping_sub(startPosInSequence)
10355                .wrapping_sub(litLength);
10356            if matchLength as size_t > blockSize
10357                && firstHalfMatchLength >= (*cctx).appliedParams.cParams.minMatch
10358            {
10359                let secondHalfMatchLength = (currSeq.matchLength)
10360                    .wrapping_add(currSeq.litLength)
10361                    .wrapping_sub(endPosInSequence);
10362                if secondHalfMatchLength < (*cctx).appliedParams.cParams.minMatch {
10363                    endPosInSequence = (endPosInSequence as core::ffi::c_uint).wrapping_sub(
10364                        ((*cctx).appliedParams.cParams.minMatch)
10365                            .wrapping_sub(secondHalfMatchLength),
10366                    );
10367                    bytesAdjustment = ((*cctx).appliedParams.cParams.minMatch)
10368                        .wrapping_sub(secondHalfMatchLength);
10369                    firstHalfMatchLength = firstHalfMatchLength.wrapping_sub(bytesAdjustment);
10370                }
10371                matchLength = firstHalfMatchLength;
10372                finalMatchSplit = 1;
10373            } else {
10374                bytesAdjustment = endPosInSequence.wrapping_sub(currSeq.litLength);
10375                endPosInSequence = currSeq.litLength;
10376                break;
10377            }
10378        }
10379        let ll0 = (litLength == 0) as core::ffi::c_int as u32;
10380        offBase = ZSTD_finalizeOffBase(
10381            rawOffset,
10382            (updatedRepcodes.rep).as_mut_ptr() as *const u32,
10383            ll0,
10384        );
10385        ZSTD_updateRep((updatedRepcodes.rep).as_mut_ptr(), offBase, ll0);
10386        if (*cctx).appliedParams.validateSequences != 0 {
10387            (*seqPos).posInSrc =
10388                ((*seqPos).posInSrc).wrapping_add(litLength.wrapping_add(matchLength) as size_t);
10389            let err_code = ZSTD_validateSequence(
10390                offBase,
10391                matchLength,
10392                (*cctx).appliedParams.cParams.minMatch,
10393                (*seqPos).posInSrc,
10394                (*cctx).appliedParams.cParams.windowLog,
10395                dictSize,
10396                ZSTD_hasExtSeqProd(&(*cctx).appliedParams),
10397            );
10398            if ERR_isError(err_code) {
10399                return err_code;
10400            }
10401        }
10402        if idx.wrapping_sub((*seqPos).idx) as size_t >= (*cctx).seqStore.maxNbSeq {
10403            return Error::externalSequences_invalid.to_error_code();
10404        }
10405        ZSTD_storeSeq(
10406            &mut (*cctx).seqStore,
10407            litLength as size_t,
10408            ip,
10409            iend,
10410            offBase,
10411            matchLength as size_t,
10412        );
10413        ip = ip.offset(matchLength.wrapping_add(litLength) as isize);
10414        if finalMatchSplit == 0 {
10415            idx = idx.wrapping_add(1);
10416        }
10417    }
10418    (*seqPos).idx = idx;
10419    (*seqPos).posInSequence = endPosInSequence;
10420    libc::memcpy(
10421        ((*(*cctx).blockState.nextCBlock).rep).as_mut_ptr() as *mut core::ffi::c_void,
10422        (updatedRepcodes.rep).as_mut_ptr() as *const core::ffi::c_void,
10423        ::core::mem::size_of::<Repcodes_t>(),
10424    );
10425    iend = iend.offset(-(bytesAdjustment as isize));
10426    if ip != iend {
10427        let lastLLSize = iend.offset_from(ip) as core::ffi::c_long as u32;
10428        ZSTD_storeLastLiterals(&mut (*cctx).seqStore, ip, lastLLSize as size_t);
10429        (*seqPos).posInSrc = ((*seqPos).posInSrc).wrapping_add(lastLLSize as size_t);
10430    }
10431    iend.offset_from_unsigned(istart)
10432}
10433unsafe fn ZSTD_selectSequenceCopier(mode: ZSTD_SequenceFormat_e) -> ZSTD_SequenceCopier_f {
10434    if mode as core::ffi::c_uint
10435        == ZSTD_sf_explicitBlockDelimiters as core::ffi::c_int as core::ffi::c_uint
10436    {
10437        return Some(
10438            ZSTD_transferSequences_wBlockDelim
10439                as unsafe fn(
10440                    *mut ZSTD_CCtx,
10441                    *mut ZSTD_SequencePosition,
10442                    *const ZSTD_Sequence,
10443                    size_t,
10444                    *const core::ffi::c_void,
10445                    size_t,
10446                    ZSTD_ParamSwitch_e,
10447                ) -> size_t,
10448        );
10449    }
10450    Some(
10451        ZSTD_transferSequences_noDelim
10452            as unsafe fn(
10453                *mut ZSTD_CCtx,
10454                *mut ZSTD_SequencePosition,
10455                *const ZSTD_Sequence,
10456                size_t,
10457                *const core::ffi::c_void,
10458                size_t,
10459                ZSTD_ParamSwitch_e,
10460            ) -> size_t,
10461    )
10462}
10463unsafe fn blockSize_explicitDelimiter(
10464    inSeqs: *const ZSTD_Sequence,
10465    inSeqsSize: size_t,
10466    seqPos: ZSTD_SequencePosition,
10467) -> size_t {
10468    let mut end = 0;
10469    let mut blockSize = 0 as size_t;
10470    let mut spos = seqPos.idx as size_t;
10471    while spos < inSeqsSize {
10472        end = ((*inSeqs.add(spos)).offset == 0) as core::ffi::c_int;
10473        blockSize = blockSize.wrapping_add(
10474            ((*inSeqs.add(spos)).litLength).wrapping_add((*inSeqs.add(spos)).matchLength) as size_t,
10475        );
10476        if end != 0 {
10477            if (*inSeqs.add(spos)).matchLength != 0 {
10478                return Error::externalSequences_invalid.to_error_code();
10479            }
10480            break;
10481        } else {
10482            spos = spos.wrapping_add(1);
10483        }
10484    }
10485    if end == 0 {
10486        return Error::externalSequences_invalid.to_error_code();
10487    }
10488    blockSize
10489}
10490unsafe fn determine_blockSize(
10491    mode: ZSTD_SequenceFormat_e,
10492    blockSize: size_t,
10493    remaining: size_t,
10494    inSeqs: *const ZSTD_Sequence,
10495    inSeqsSize: size_t,
10496    seqPos: ZSTD_SequencePosition,
10497) -> size_t {
10498    if mode as core::ffi::c_uint
10499        == ZSTD_sf_noBlockDelimiters as core::ffi::c_int as core::ffi::c_uint
10500    {
10501        return if remaining < blockSize {
10502            remaining
10503        } else {
10504            blockSize
10505        };
10506    }
10507    let explicitBlockSize = blockSize_explicitDelimiter(inSeqs, inSeqsSize, seqPos);
10508    let err_code = explicitBlockSize;
10509    if ERR_isError(err_code) {
10510        return err_code;
10511    }
10512    if explicitBlockSize > blockSize {
10513        return Error::externalSequences_invalid.to_error_code();
10514    }
10515    if explicitBlockSize > remaining {
10516        return Error::externalSequences_invalid.to_error_code();
10517    }
10518    explicitBlockSize
10519}
10520unsafe fn ZSTD_compressSequences_internal(
10521    cctx: *mut ZSTD_CCtx,
10522    dst: *mut core::ffi::c_void,
10523    mut dstCapacity: size_t,
10524    inSeqs: *const ZSTD_Sequence,
10525    inSeqsSize: size_t,
10526    src: *const core::ffi::c_void,
10527    srcSize: size_t,
10528) -> size_t {
10529    let mut cSize = 0 as size_t;
10530    let mut remaining = srcSize;
10531    let mut seqPos = {
10532        ZSTD_SequencePosition {
10533            idx: 0,
10534            posInSequence: 0,
10535            posInSrc: 0,
10536        }
10537    };
10538    let mut ip = src as *const u8;
10539    let mut op = dst as *mut u8;
10540    let sequenceCopier = ZSTD_selectSequenceCopier((*cctx).appliedParams.blockDelimiters);
10541    if remaining == 0 {
10542        let cBlockHeader24 = 1u32.wrapping_add((bt_raw as core::ffi::c_int as u32) << 1);
10543        if dstCapacity < 4 {
10544            return Error::dstSize_tooSmall.to_error_code();
10545        }
10546        MEM_writeLE32(op as *mut core::ffi::c_void, cBlockHeader24);
10547        op = op.add(ZSTD_blockHeaderSize);
10548        dstCapacity = dstCapacity.wrapping_sub(ZSTD_blockHeaderSize);
10549        cSize = cSize.wrapping_add(ZSTD_blockHeaderSize);
10550    }
10551    while remaining != 0 {
10552        let mut compressedSeqsSize: size_t = 0;
10553        let mut cBlockSize: size_t = 0;
10554        let mut blockSize = determine_blockSize(
10555            (*cctx).appliedParams.blockDelimiters,
10556            (*cctx).blockSizeMax,
10557            remaining,
10558            inSeqs,
10559            inSeqsSize,
10560            seqPos,
10561        );
10562        let lastBlock = (blockSize == remaining) as core::ffi::c_int as u32;
10563        let err_code = blockSize;
10564        if ERR_isError(err_code) {
10565            return err_code;
10566        }
10567        ZSTD_resetSeqStore(&mut (*cctx).seqStore);
10568        blockSize = sequenceCopier.unwrap_unchecked()(
10569            cctx,
10570            &mut seqPos,
10571            inSeqs,
10572            inSeqsSize,
10573            ip as *const core::ffi::c_void,
10574            blockSize,
10575            (*cctx).appliedParams.searchForExternalRepcodes,
10576        );
10577        let err_code_0 = blockSize;
10578        if ERR_isError(err_code_0) {
10579            return err_code_0;
10580        }
10581        if blockSize
10582            < (MIN_CBLOCK_SIZE as size_t)
10583                .wrapping_add(ZSTD_blockHeaderSize)
10584                .wrapping_add(1)
10585                .wrapping_add(1)
10586        {
10587            cBlockSize = ZSTD_noCompressBlock(
10588                op as *mut core::ffi::c_void,
10589                dstCapacity,
10590                ip as *const core::ffi::c_void,
10591                blockSize,
10592                lastBlock,
10593            );
10594            let err_code_1 = cBlockSize;
10595            if ERR_isError(err_code_1) {
10596                return err_code_1;
10597            }
10598            cSize = cSize.wrapping_add(cBlockSize);
10599            ip = ip.add(blockSize);
10600            op = op.add(cBlockSize);
10601            remaining = remaining.wrapping_sub(blockSize);
10602            dstCapacity = dstCapacity.wrapping_sub(cBlockSize);
10603        } else {
10604            if dstCapacity < ZSTD_blockHeaderSize {
10605                return Error::dstSize_tooSmall.to_error_code();
10606            }
10607            compressedSeqsSize = ZSTD_entropyCompressSeqStore(
10608                &(*cctx).seqStore,
10609                &(*(*cctx).blockState.prevCBlock).entropy,
10610                &mut (*(*cctx).blockState.nextCBlock).entropy,
10611                &(*cctx).appliedParams,
10612                op.add(ZSTD_blockHeaderSize) as *mut core::ffi::c_void,
10613                dstCapacity.wrapping_sub(ZSTD_blockHeaderSize),
10614                blockSize,
10615                (*cctx).tmpWorkspace,
10616                (*cctx).tmpWkspSize,
10617                (*cctx).bmi2,
10618            );
10619            let err_code_2 = compressedSeqsSize;
10620            if ERR_isError(err_code_2) {
10621                return err_code_2;
10622            }
10623            if (*cctx).isFirstBlock == 0
10624                && ZSTD_maybeRLE(&(*cctx).seqStore) != 0
10625                && ZSTD_isRLE(ip, blockSize) != 0
10626            {
10627                compressedSeqsSize = 1;
10628            }
10629            if compressedSeqsSize == 0 {
10630                cBlockSize = ZSTD_noCompressBlock(
10631                    op as *mut core::ffi::c_void,
10632                    dstCapacity,
10633                    ip as *const core::ffi::c_void,
10634                    blockSize,
10635                    lastBlock,
10636                );
10637                let err_code_3 = cBlockSize;
10638                if ERR_isError(err_code_3) {
10639                    return err_code_3;
10640                }
10641            } else if compressedSeqsSize == 1 {
10642                cBlockSize = ZSTD_rleCompressBlock(
10643                    op as *mut core::ffi::c_void,
10644                    dstCapacity,
10645                    *ip,
10646                    blockSize,
10647                    lastBlock,
10648                );
10649                let err_code_4 = cBlockSize;
10650                if ERR_isError(err_code_4) {
10651                    return err_code_4;
10652                }
10653            } else {
10654                let mut cBlockHeader: u32 = 0;
10655                ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*cctx).blockState);
10656                if (*(*cctx).blockState.prevCBlock)
10657                    .entropy
10658                    .fse
10659                    .offcode_repeatMode as core::ffi::c_uint
10660                    == FSE_repeat_valid as core::ffi::c_int as core::ffi::c_uint
10661                {
10662                    (*(*cctx).blockState.prevCBlock)
10663                        .entropy
10664                        .fse
10665                        .offcode_repeatMode = FSE_repeat_check;
10666                }
10667                cBlockHeader = lastBlock
10668                    .wrapping_add((bt_compressed as core::ffi::c_int as u32) << 1)
10669                    .wrapping_add((compressedSeqsSize << 3) as u32);
10670                MEM_writeLE24(op as *mut core::ffi::c_void, cBlockHeader);
10671                cBlockSize = ZSTD_blockHeaderSize.wrapping_add(compressedSeqsSize);
10672            }
10673            cSize = cSize.wrapping_add(cBlockSize);
10674            if lastBlock != 0 {
10675                break;
10676            }
10677            ip = ip.add(blockSize);
10678            op = op.add(cBlockSize);
10679            remaining = remaining.wrapping_sub(blockSize);
10680            dstCapacity = dstCapacity.wrapping_sub(cBlockSize);
10681            (*cctx).isFirstBlock = 0;
10682        }
10683    }
10684    cSize
10685}
10686#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressSequences))]
10687pub unsafe extern "C" fn ZSTD_compressSequences(
10688    cctx: *mut ZSTD_CCtx,
10689    dst: *mut core::ffi::c_void,
10690    mut dstCapacity: size_t,
10691    inSeqs: *const ZSTD_Sequence,
10692    inSeqsSize: size_t,
10693    src: *const core::ffi::c_void,
10694    srcSize: size_t,
10695) -> size_t {
10696    let mut op = dst as *mut u8;
10697    let mut cSize = 0 as size_t;
10698    let err_code = ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize);
10699    if ERR_isError(err_code) {
10700        return err_code;
10701    }
10702    let frameHeaderSize = ZSTD_writeFrameHeader(
10703        op as *mut core::ffi::c_void,
10704        dstCapacity,
10705        &(*cctx).appliedParams,
10706        srcSize as u64,
10707        (*cctx).dictID,
10708    );
10709    op = op.add(frameHeaderSize);
10710    dstCapacity = dstCapacity.wrapping_sub(frameHeaderSize);
10711    cSize = cSize.wrapping_add(frameHeaderSize);
10712    if (*cctx).appliedParams.fParams.checksumFlag != 0 && srcSize != 0 {
10713        ZSTD_XXH64_update_slice(
10714            &mut (*cctx).xxhState,
10715            core::slice::from_raw_parts(src as *const u8, srcSize),
10716        );
10717    }
10718    let cBlocksSize = ZSTD_compressSequences_internal(
10719        cctx,
10720        op as *mut core::ffi::c_void,
10721        dstCapacity,
10722        inSeqs,
10723        inSeqsSize,
10724        src,
10725        srcSize,
10726    );
10727    let err_code_0 = cBlocksSize;
10728    if ERR_isError(err_code_0) {
10729        return err_code_0;
10730    }
10731    cSize = cSize.wrapping_add(cBlocksSize);
10732    dstCapacity = dstCapacity.wrapping_sub(cBlocksSize);
10733    if (*cctx).appliedParams.fParams.checksumFlag != 0 {
10734        let checksum = ZSTD_XXH64_digest(&mut (*cctx).xxhState) as u32;
10735        if dstCapacity < 4 {
10736            return Error::dstSize_tooSmall.to_error_code();
10737        }
10738        MEM_writeLE32(
10739            (dst as *mut core::ffi::c_char).add(cSize) as *mut core::ffi::c_void,
10740            checksum,
10741        );
10742        cSize = cSize.wrapping_add(4);
10743    }
10744    cSize
10745}
10746pub unsafe fn convertSequences_noRepcodes(
10747    dstSeqs: *mut SeqDef,
10748    inSeqs: *const ZSTD_Sequence,
10749    nbSequences: size_t,
10750) -> size_t {
10751    let mut longLen = 0;
10752    let mut n: size_t = 0;
10753    n = 0;
10754    while n < nbSequences {
10755        (*dstSeqs.add(n)).offBase =
10756            ((*inSeqs.add(n)).offset).wrapping_add(ZSTD_REP_NUM as core::ffi::c_uint);
10757        (*dstSeqs.add(n)).litLength = (*inSeqs.add(n)).litLength as u16;
10758        (*dstSeqs.add(n)).mlBase =
10759            ((*inSeqs.add(n)).matchLength).wrapping_sub(MINMATCH as core::ffi::c_uint) as u16;
10760        if (*inSeqs.add(n)).matchLength > 65535 + 3 {
10761            longLen = n.wrapping_add(1);
10762        }
10763        if (*inSeqs.add(n)).litLength > 65535 {
10764            longLen = n.wrapping_add(nbSequences).wrapping_add(1);
10765        }
10766        n = n.wrapping_add(1);
10767    }
10768    longLen
10769}
10770pub unsafe fn ZSTD_convertBlockSequences(
10771    cctx: *mut ZSTD_CCtx,
10772    inSeqs: *const ZSTD_Sequence,
10773    nbSequences: size_t,
10774    repcodeResolution: core::ffi::c_int,
10775) -> size_t {
10776    let mut updatedRepcodes = repcodes_s { rep: [0; 3] };
10777    let mut seqNb = 0;
10778    if nbSequences >= (*cctx).seqStore.maxNbSeq {
10779        return Error::externalSequences_invalid.to_error_code();
10780    }
10781    libc::memcpy(
10782        (updatedRepcodes.rep).as_mut_ptr() as *mut core::ffi::c_void,
10783        ((*(*cctx).blockState.prevCBlock).rep).as_mut_ptr() as *const core::ffi::c_void,
10784        ::core::mem::size_of::<Repcodes_t>(),
10785    );
10786    if repcodeResolution == 0 {
10787        let longl = convertSequences_noRepcodes(
10788            (*cctx).seqStore.sequencesStart,
10789            inSeqs,
10790            nbSequences.wrapping_sub(1),
10791        );
10792        (*cctx).seqStore.sequences = ((*cctx).seqStore.sequencesStart).add(nbSequences).sub(1);
10793        if longl != 0 {
10794            if longl <= nbSequences.wrapping_sub(1) {
10795                (*cctx).seqStore.longLengthType = ZSTD_llt_matchLength;
10796                (*cctx).seqStore.longLengthPos = longl.wrapping_sub(1) as u32;
10797            } else {
10798                (*cctx).seqStore.longLengthType = ZSTD_llt_literalLength;
10799                (*cctx).seqStore.longLengthPos = longl
10800                    .wrapping_sub(nbSequences.wrapping_sub(1))
10801                    .wrapping_sub(1) as u32;
10802            }
10803        }
10804    } else {
10805        seqNb = 0;
10806        while seqNb < nbSequences.wrapping_sub(1) {
10807            let litLength = (*inSeqs.add(seqNb)).litLength;
10808            let matchLength = (*inSeqs.add(seqNb)).matchLength;
10809            let ll0 = (litLength == 0) as core::ffi::c_int as u32;
10810            let offBase = ZSTD_finalizeOffBase(
10811                (*inSeqs.add(seqNb)).offset,
10812                (updatedRepcodes.rep).as_mut_ptr() as *const u32,
10813                ll0,
10814            );
10815            ZSTD_storeSeqOnly(
10816                &mut (*cctx).seqStore,
10817                litLength as size_t,
10818                offBase,
10819                matchLength as size_t,
10820            );
10821            ZSTD_updateRep((updatedRepcodes.rep).as_mut_ptr(), offBase, ll0);
10822            seqNb = seqNb.wrapping_add(1);
10823        }
10824    }
10825    if repcodeResolution == 0 && nbSequences > 1 {
10826        let rep = (updatedRepcodes.rep).as_mut_ptr();
10827        if nbSequences >= 4 {
10828            let lastSeqIdx = (nbSequences as u32).wrapping_sub(2);
10829            *rep.add(2) = (*inSeqs.offset(lastSeqIdx.wrapping_sub(2) as isize)).offset;
10830            *rep.add(1) = (*inSeqs.offset(lastSeqIdx.wrapping_sub(1) as isize)).offset;
10831            *rep = (*inSeqs.offset(lastSeqIdx as isize)).offset;
10832        } else if nbSequences == 3 {
10833            *rep.add(2) = *rep;
10834            *rep.add(1) = (*inSeqs).offset;
10835            *rep = (*inSeqs.add(1)).offset;
10836        } else {
10837            *rep.add(2) = *rep.add(1);
10838            *rep.add(1) = *rep;
10839            *rep = (*inSeqs).offset;
10840        }
10841    }
10842    libc::memcpy(
10843        ((*(*cctx).blockState.nextCBlock).rep).as_mut_ptr() as *mut core::ffi::c_void,
10844        (updatedRepcodes.rep).as_mut_ptr() as *const core::ffi::c_void,
10845        ::core::mem::size_of::<Repcodes_t>(),
10846    );
10847    0
10848}
10849
10850#[inline(always)]
10851const fn matchLengthHalfIsZero(litMatchLength: u64) -> core::ffi::c_int {
10852    if cfg!(target_endian = "little") {
10853        (litMatchLength <= 0xffffffff) as core::ffi::c_int
10854    } else {
10855        (litMatchLength as u32 == 0) as core::ffi::c_int
10856    }
10857}
10858
10859pub unsafe fn ZSTD_get1BlockSummary(seqs: *const ZSTD_Sequence, nbSeqs: size_t) -> BlockSummary {
10860    let mut current_block: u64;
10861    let mut litMatchSize0 = 0u64;
10862    let mut litMatchSize1 = 0u64;
10863    let mut litMatchSize2 = 0u64;
10864    let mut litMatchSize3 = 0u64;
10865    let mut n = 0 as size_t;
10866    if nbSeqs > 3 as size_t {
10867        loop {
10868            let mut litMatchLength = MEM_read64(
10869                &(*seqs.add(n)).litLength as *const core::ffi::c_uint as *const core::ffi::c_void,
10870            );
10871            litMatchSize0 = litMatchSize0.wrapping_add(litMatchLength);
10872            if matchLengthHalfIsZero(litMatchLength) != 0 {
10873                current_block = 13744635599856597681;
10874                break;
10875            }
10876            litMatchLength = MEM_read64(
10877                &(*seqs.add(n.wrapping_add(1))).litLength as *const core::ffi::c_uint
10878                    as *const core::ffi::c_void,
10879            );
10880            litMatchSize1 = litMatchSize1.wrapping_add(litMatchLength);
10881            if matchLengthHalfIsZero(litMatchLength) != 0 {
10882                n = n.wrapping_add(1);
10883                current_block = 13744635599856597681;
10884                break;
10885            } else {
10886                litMatchLength = MEM_read64(
10887                    &(*seqs.add(n.wrapping_add(2))).litLength as *const core::ffi::c_uint
10888                        as *const core::ffi::c_void,
10889                );
10890                litMatchSize2 = litMatchSize2.wrapping_add(litMatchLength);
10891                if matchLengthHalfIsZero(litMatchLength) != 0 {
10892                    n = n.wrapping_add(2);
10893                    current_block = 13744635599856597681;
10894                    break;
10895                } else {
10896                    litMatchLength = MEM_read64(
10897                        &(*seqs.add(n.wrapping_add(3))).litLength as *const core::ffi::c_uint
10898                            as *const core::ffi::c_void,
10899                    );
10900                    litMatchSize3 = litMatchSize3.wrapping_add(litMatchLength);
10901                    if matchLengthHalfIsZero(litMatchLength) != 0 {
10902                        n = n.wrapping_add(3);
10903                        current_block = 13744635599856597681;
10904                        break;
10905                    } else {
10906                        n = n.wrapping_add(4);
10907                        if n >= nbSeqs.wrapping_sub(3) {
10908                            current_block = 2668756484064249700;
10909                            break;
10910                        }
10911                    }
10912                }
10913            }
10914        }
10915    } else {
10916        current_block = 2668756484064249700;
10917    }
10918    loop {
10919        match current_block {
10920            13744635599856597681 => {
10921                litMatchSize0 = litMatchSize0.wrapping_add(
10922                    litMatchSize1
10923                        .wrapping_add(litMatchSize2)
10924                        .wrapping_add(litMatchSize3),
10925                );
10926                let mut bs_0 = BlockSummary {
10927                    nbSequences: 0,
10928                    blockSize: 0,
10929                    litSize: 0,
10930                };
10931                bs_0.nbSequences = n.wrapping_add(1);
10932                if cfg!(target_endian = "little") {
10933                    bs_0.litSize = litMatchSize0 as u32 as size_t;
10934                    bs_0.blockSize =
10935                        (bs_0.litSize as u64).wrapping_add(litMatchSize0 >> 32) as usize;
10936                } else {
10937                    bs_0.litSize = (litMatchSize0 >> 32) as usize;
10938                    bs_0.blockSize = (bs_0.litSize).wrapping_add(litMatchSize0 as u32 as size_t);
10939                }
10940                return bs_0;
10941            }
10942            _ => {
10943                if n < nbSeqs {
10944                    let litMatchLength_0 = MEM_read64(
10945                        &(*seqs.add(n)).litLength as *const core::ffi::c_uint
10946                            as *const core::ffi::c_void,
10947                    );
10948                    litMatchSize0 = litMatchSize0.wrapping_add(litMatchLength_0);
10949                    if matchLengthHalfIsZero(litMatchLength_0) != 0 {
10950                        current_block = 13744635599856597681;
10951                        continue;
10952                    }
10953                    n = n.wrapping_add(1);
10954                    current_block = 2668756484064249700;
10955                } else {
10956                    let mut bs = BlockSummary {
10957                        nbSequences: 0,
10958                        blockSize: 0,
10959                        litSize: 0,
10960                    };
10961                    bs.nbSequences = Error::externalSequences_invalid.to_error_code();
10962                    return bs;
10963                }
10964            }
10965        }
10966    }
10967}
10968unsafe fn ZSTD_compressSequencesAndLiterals_internal(
10969    cctx: *mut ZSTD_CCtx,
10970    dst: *mut core::ffi::c_void,
10971    mut dstCapacity: size_t,
10972    mut inSeqs: *const ZSTD_Sequence,
10973    mut nbSequences: size_t,
10974    mut literals: *const core::ffi::c_void,
10975    mut litSize: size_t,
10976    srcSize: size_t,
10977) -> size_t {
10978    let mut remaining = srcSize;
10979    let mut cSize = 0 as size_t;
10980    let mut op = dst as *mut u8;
10981    let repcodeResolution = ((*cctx).appliedParams.searchForExternalRepcodes
10982        == ZSTD_ParamSwitch_e::ZSTD_ps_enable) as core::ffi::c_int;
10983    if nbSequences == 0 {
10984        return Error::externalSequences_invalid.to_error_code();
10985    }
10986    if nbSequences == 1 && (*inSeqs).litLength == 0 {
10987        let cBlockHeader24 = 1u32.wrapping_add((bt_raw as core::ffi::c_int as u32) << 1);
10988        if dstCapacity < 3 {
10989            return Error::dstSize_tooSmall.to_error_code();
10990        }
10991        MEM_writeLE24(op as *mut core::ffi::c_void, cBlockHeader24);
10992        op = op.add(ZSTD_blockHeaderSize);
10993        dstCapacity = dstCapacity.wrapping_sub(ZSTD_blockHeaderSize);
10994        cSize = cSize.wrapping_add(ZSTD_blockHeaderSize);
10995    }
10996    while nbSequences != 0 {
10997        let mut compressedSeqsSize: size_t = 0;
10998        let mut cBlockSize: size_t = 0;
10999        let mut conversionStatus: size_t = 0;
11000        let block = ZSTD_get1BlockSummary(inSeqs, nbSequences);
11001        let lastBlock = (block.nbSequences == nbSequences) as core::ffi::c_int as u32;
11002        let err_code = block.nbSequences;
11003        if ERR_isError(err_code) {
11004            return err_code;
11005        }
11006        if block.litSize > litSize {
11007            return Error::externalSequences_invalid.to_error_code();
11008        }
11009        ZSTD_resetSeqStore(&mut (*cctx).seqStore);
11010        conversionStatus =
11011            ZSTD_convertBlockSequences(cctx, inSeqs, block.nbSequences, repcodeResolution);
11012        let err_code_0 = conversionStatus;
11013        if ERR_isError(err_code_0) {
11014            return err_code_0;
11015        }
11016        inSeqs = inSeqs.add(block.nbSequences);
11017        nbSequences = nbSequences.wrapping_sub(block.nbSequences);
11018        remaining = remaining.wrapping_sub(block.blockSize);
11019        if dstCapacity < ZSTD_blockHeaderSize {
11020            return Error::dstSize_tooSmall.to_error_code();
11021        }
11022        compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal(
11023            op.add(ZSTD_blockHeaderSize) as *mut core::ffi::c_void,
11024            dstCapacity.wrapping_sub(ZSTD_blockHeaderSize),
11025            literals,
11026            block.litSize,
11027            &(*cctx).seqStore,
11028            &(*(*cctx).blockState.prevCBlock).entropy,
11029            &mut (*(*cctx).blockState.nextCBlock).entropy,
11030            &(*cctx).appliedParams,
11031            (*cctx).tmpWorkspace,
11032            (*cctx).tmpWkspSize,
11033            (*cctx).bmi2,
11034        );
11035        let err_code_1 = compressedSeqsSize;
11036        if ERR_isError(err_code_1) {
11037            return err_code_1;
11038        }
11039        if compressedSeqsSize > (*cctx).blockSizeMax {
11040            compressedSeqsSize = 0;
11041        }
11042        litSize = litSize.wrapping_sub(block.litSize);
11043        literals =
11044            (literals as *const core::ffi::c_char).add(block.litSize) as *const core::ffi::c_void;
11045        if compressedSeqsSize == 0 {
11046            return Error::cannotProduce_uncompressedBlock.to_error_code();
11047        } else {
11048            let mut cBlockHeader: u32 = 0;
11049            ZSTD_blockState_confirmRepcodesAndEntropyTables(&mut (*cctx).blockState);
11050            if (*(*cctx).blockState.prevCBlock)
11051                .entropy
11052                .fse
11053                .offcode_repeatMode as core::ffi::c_uint
11054                == FSE_repeat_valid as core::ffi::c_int as core::ffi::c_uint
11055            {
11056                (*(*cctx).blockState.prevCBlock)
11057                    .entropy
11058                    .fse
11059                    .offcode_repeatMode = FSE_repeat_check;
11060            }
11061            cBlockHeader = lastBlock
11062                .wrapping_add((bt_compressed as core::ffi::c_int as u32) << 1)
11063                .wrapping_add((compressedSeqsSize << 3) as u32);
11064            MEM_writeLE24(op as *mut core::ffi::c_void, cBlockHeader);
11065            cBlockSize = ZSTD_blockHeaderSize.wrapping_add(compressedSeqsSize);
11066        }
11067        cSize = cSize.wrapping_add(cBlockSize);
11068        op = op.add(cBlockSize);
11069        dstCapacity = dstCapacity.wrapping_sub(cBlockSize);
11070        (*cctx).isFirstBlock = 0;
11071        if lastBlock != 0 {
11072            break;
11073        }
11074    }
11075    if litSize != 0 {
11076        return Error::externalSequences_invalid.to_error_code();
11077    }
11078    if remaining != 0 {
11079        return Error::externalSequences_invalid.to_error_code();
11080    }
11081    cSize
11082}
11083#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_compressSequencesAndLiterals))]
11084pub unsafe extern "C" fn ZSTD_compressSequencesAndLiterals(
11085    cctx: *mut ZSTD_CCtx,
11086    dst: *mut core::ffi::c_void,
11087    mut dstCapacity: size_t,
11088    inSeqs: *const ZSTD_Sequence,
11089    inSeqsSize: size_t,
11090    literals: *const core::ffi::c_void,
11091    litSize: size_t,
11092    litCapacity: size_t,
11093    decompressedSize: size_t,
11094) -> size_t {
11095    let mut op = dst as *mut u8;
11096    let mut cSize = 0 as size_t;
11097    if litCapacity < litSize {
11098        return Error::workSpace_tooSmall.to_error_code();
11099    }
11100    let err_code = ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize);
11101    if ERR_isError(err_code) {
11102        return err_code;
11103    }
11104    if (*cctx).appliedParams.blockDelimiters as core::ffi::c_uint
11105        == ZSTD_sf_noBlockDelimiters as core::ffi::c_int as core::ffi::c_uint
11106    {
11107        return Error::frameParameter_unsupported.to_error_code();
11108    }
11109    if (*cctx).appliedParams.validateSequences != 0 {
11110        return Error::parameter_unsupported.to_error_code();
11111    }
11112    if (*cctx).appliedParams.fParams.checksumFlag != 0 {
11113        return Error::frameParameter_unsupported.to_error_code();
11114    }
11115    let frameHeaderSize = ZSTD_writeFrameHeader(
11116        op as *mut core::ffi::c_void,
11117        dstCapacity,
11118        &(*cctx).appliedParams,
11119        decompressedSize as u64,
11120        (*cctx).dictID,
11121    );
11122    op = op.add(frameHeaderSize);
11123    dstCapacity = dstCapacity.wrapping_sub(frameHeaderSize);
11124    cSize = cSize.wrapping_add(frameHeaderSize);
11125    let cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(
11126        cctx,
11127        op as *mut core::ffi::c_void,
11128        dstCapacity,
11129        inSeqs,
11130        inSeqsSize,
11131        literals,
11132        litSize,
11133        decompressedSize,
11134    );
11135    let err_code_0 = cBlocksSize;
11136    if ERR_isError(err_code_0) {
11137        return err_code_0;
11138    }
11139    cSize = cSize.wrapping_add(cBlocksSize);
11140    dstCapacity = dstCapacity.wrapping_sub(cBlocksSize);
11141    cSize
11142}
11143unsafe fn inBuffer_forEndFlush(zcs: *const ZSTD_CStream) -> ZSTD_inBuffer {
11144    let nullInput = {
11145        ZSTD_inBuffer_s {
11146            src: core::ptr::null(),
11147            size: 0,
11148            pos: 0,
11149        }
11150    };
11151    let stableInput = ((*zcs).appliedParams.inBufferMode as core::ffi::c_uint
11152        == ZSTD_bm_stable as core::ffi::c_int as core::ffi::c_uint)
11153        as core::ffi::c_int;
11154    if stableInput != 0 {
11155        (*zcs).expectedInBuffer
11156    } else {
11157        nullInput
11158    }
11159}
11160#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_flushStream))]
11161pub unsafe extern "C" fn ZSTD_flushStream(
11162    zcs: *mut ZSTD_CStream,
11163    output: *mut ZSTD_outBuffer,
11164) -> size_t {
11165    let mut input = inBuffer_forEndFlush(zcs);
11166    input.size = input.pos;
11167    ZSTD_compressStream2(zcs, output, &mut input, ZSTD_e_flush)
11168}
11169#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_endStream))]
11170pub unsafe extern "C" fn ZSTD_endStream(
11171    zcs: *mut ZSTD_CStream,
11172    output: *mut ZSTD_outBuffer,
11173) -> size_t {
11174    let mut input = inBuffer_forEndFlush(zcs);
11175    let remainingToFlush = ZSTD_compressStream2(zcs, output, &mut input, ZSTD_e_end);
11176    let err_code = remainingToFlush;
11177    if ERR_isError(err_code) {
11178        return err_code;
11179    }
11180    if (*zcs).appliedParams.nbWorkers > 0 {
11181        return remainingToFlush;
11182    }
11183    let lastBlockSize = (if (*zcs).frameEnded != 0 {
11184        0
11185    } else {
11186        ZSTD_BLOCKHEADERSIZE
11187    }) as size_t;
11188    let checksumSize = (if (*zcs).frameEnded != 0 {
11189        0
11190    } else {
11191        (*zcs).appliedParams.fParams.checksumFlag * 4
11192    }) as size_t;
11193
11194    remainingToFlush
11195        .wrapping_add(lastBlockSize)
11196        .wrapping_add(checksumSize)
11197}
11198
11199#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_maxCLevel))]
11200pub const extern "C" fn ZSTD_maxCLevel() -> core::ffi::c_int {
11201    ZSTD_MAX_CLEVEL
11202}
11203
11204#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_minCLevel))]
11205pub const extern "C" fn ZSTD_minCLevel() -> core::ffi::c_int {
11206    -ZSTD_TARGETLENGTH_MAX
11207}
11208
11209#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_defaultCLevel))]
11210pub const extern "C" fn ZSTD_defaultCLevel() -> core::ffi::c_int {
11211    ZSTD_CLEVEL_DEFAULT
11212}
11213
11214unsafe fn ZSTD_dedicatedDictSearch_isSupported(
11215    cParams: *const ZSTD_compressionParameters,
11216) -> core::ffi::c_int {
11217    ((*cParams).strategy as core::ffi::c_uint
11218        >= ZSTD_greedy as core::ffi::c_int as core::ffi::c_uint
11219        && (*cParams).strategy as core::ffi::c_uint
11220            <= ZSTD_lazy2 as core::ffi::c_int as core::ffi::c_uint
11221        && (*cParams).hashLog > (*cParams).chainLog
11222        && (*cParams).chainLog <= 24) as core::ffi::c_int
11223}
11224unsafe fn ZSTD_dedicatedDictSearch_revertCParams(cParams: *mut ZSTD_compressionParameters) {
11225    if let 3..=5 = (*cParams).strategy as core::ffi::c_uint {
11226        (*cParams).hashLog =
11227            ((*cParams).hashLog).wrapping_sub(ZSTD_LAZY_DDSS_BUCKET_LOG as core::ffi::c_uint);
11228        if (*cParams).hashLog < ZSTD_HASHLOG_MIN as core::ffi::c_uint {
11229            (*cParams).hashLog = ZSTD_HASHLOG_MIN as core::ffi::c_uint;
11230        }
11231    }
11232}
11233unsafe fn ZSTD_getCParamRowSize(
11234    srcSizeHint: u64,
11235    mut dictSize: size_t,
11236    mode: ZSTD_CParamMode_e,
11237) -> u64 {
11238    if mode as core::ffi::c_uint == 1 {
11239        dictSize = 0;
11240    }
11241    let unknown =
11242        (srcSizeHint as core::ffi::c_ulonglong == ZSTD_CONTENTSIZE_UNKNOWN) as core::ffi::c_int;
11243    let addedSize = if unknown != 0 && dictSize > 0 { 500 } else { 0 };
11244    if unknown != 0 && dictSize == 0 {
11245        ZSTD_CONTENTSIZE_UNKNOWN
11246    } else {
11247        srcSizeHint
11248            .wrapping_add(dictSize as u64)
11249            .wrapping_add(addedSize)
11250    }
11251}
11252#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getCParams))]
11253pub unsafe extern "C" fn ZSTD_getCParams(
11254    compressionLevel: core::ffi::c_int,
11255    mut srcSizeHint: core::ffi::c_ulonglong,
11256    dictSize: size_t,
11257) -> ZSTD_compressionParameters {
11258    if srcSizeHint == 0 {
11259        srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
11260    }
11261    ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown)
11262}
11263#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getParams))]
11264pub unsafe extern "C" fn ZSTD_getParams(
11265    compressionLevel: core::ffi::c_int,
11266    mut srcSizeHint: core::ffi::c_ulonglong,
11267    dictSize: size_t,
11268) -> ZSTD_parameters {
11269    if srcSizeHint == 0 {
11270        srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
11271    }
11272    ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown)
11273}
11274pub const __INT_MAX__: core::ffi::c_int = 2147483647;
11275pub const ZSTD_MAX_CLEVEL: core::ffi::c_int = 22;
11276static ZSTD_defaultCParameters: [[ZSTD_compressionParameters; 23]; 4] = [
11277    [
11278        {
11279            ZSTD_compressionParameters {
11280                windowLog: 19,
11281                chainLog: 12,
11282                hashLog: 13,
11283                searchLog: 1,
11284                minMatch: 6,
11285                targetLength: 1,
11286                strategy: ZSTD_fast,
11287            }
11288        },
11289        {
11290            ZSTD_compressionParameters {
11291                windowLog: 19,
11292                chainLog: 13,
11293                hashLog: 14,
11294                searchLog: 1,
11295                minMatch: 7,
11296                targetLength: 0,
11297                strategy: ZSTD_fast,
11298            }
11299        },
11300        {
11301            ZSTD_compressionParameters {
11302                windowLog: 20,
11303                chainLog: 15,
11304                hashLog: 16,
11305                searchLog: 1,
11306                minMatch: 6,
11307                targetLength: 0,
11308                strategy: ZSTD_fast,
11309            }
11310        },
11311        {
11312            ZSTD_compressionParameters {
11313                windowLog: 21,
11314                chainLog: 16,
11315                hashLog: 17,
11316                searchLog: 1,
11317                minMatch: 5,
11318                targetLength: 0,
11319                strategy: ZSTD_dfast,
11320            }
11321        },
11322        {
11323            ZSTD_compressionParameters {
11324                windowLog: 21,
11325                chainLog: 18,
11326                hashLog: 18,
11327                searchLog: 1,
11328                minMatch: 5,
11329                targetLength: 0,
11330                strategy: ZSTD_dfast,
11331            }
11332        },
11333        {
11334            ZSTD_compressionParameters {
11335                windowLog: 21,
11336                chainLog: 18,
11337                hashLog: 19,
11338                searchLog: 3,
11339                minMatch: 5,
11340                targetLength: 2,
11341                strategy: ZSTD_greedy,
11342            }
11343        },
11344        {
11345            ZSTD_compressionParameters {
11346                windowLog: 21,
11347                chainLog: 18,
11348                hashLog: 19,
11349                searchLog: 3,
11350                minMatch: 5,
11351                targetLength: 4,
11352                strategy: ZSTD_lazy,
11353            }
11354        },
11355        {
11356            ZSTD_compressionParameters {
11357                windowLog: 21,
11358                chainLog: 19,
11359                hashLog: 20,
11360                searchLog: 4,
11361                minMatch: 5,
11362                targetLength: 8,
11363                strategy: ZSTD_lazy,
11364            }
11365        },
11366        {
11367            ZSTD_compressionParameters {
11368                windowLog: 21,
11369                chainLog: 19,
11370                hashLog: 20,
11371                searchLog: 4,
11372                minMatch: 5,
11373                targetLength: 16,
11374                strategy: ZSTD_lazy2,
11375            }
11376        },
11377        {
11378            ZSTD_compressionParameters {
11379                windowLog: 22,
11380                chainLog: 20,
11381                hashLog: 21,
11382                searchLog: 4,
11383                minMatch: 5,
11384                targetLength: 16,
11385                strategy: ZSTD_lazy2,
11386            }
11387        },
11388        {
11389            ZSTD_compressionParameters {
11390                windowLog: 22,
11391                chainLog: 21,
11392                hashLog: 22,
11393                searchLog: 5,
11394                minMatch: 5,
11395                targetLength: 16,
11396                strategy: ZSTD_lazy2,
11397            }
11398        },
11399        {
11400            ZSTD_compressionParameters {
11401                windowLog: 22,
11402                chainLog: 21,
11403                hashLog: 22,
11404                searchLog: 6,
11405                minMatch: 5,
11406                targetLength: 16,
11407                strategy: ZSTD_lazy2,
11408            }
11409        },
11410        {
11411            ZSTD_compressionParameters {
11412                windowLog: 22,
11413                chainLog: 22,
11414                hashLog: 23,
11415                searchLog: 6,
11416                minMatch: 5,
11417                targetLength: 32,
11418                strategy: ZSTD_lazy2,
11419            }
11420        },
11421        {
11422            ZSTD_compressionParameters {
11423                windowLog: 22,
11424                chainLog: 22,
11425                hashLog: 22,
11426                searchLog: 4,
11427                minMatch: 5,
11428                targetLength: 32,
11429                strategy: ZSTD_btlazy2,
11430            }
11431        },
11432        {
11433            ZSTD_compressionParameters {
11434                windowLog: 22,
11435                chainLog: 22,
11436                hashLog: 23,
11437                searchLog: 5,
11438                minMatch: 5,
11439                targetLength: 32,
11440                strategy: ZSTD_btlazy2,
11441            }
11442        },
11443        {
11444            ZSTD_compressionParameters {
11445                windowLog: 22,
11446                chainLog: 23,
11447                hashLog: 23,
11448                searchLog: 6,
11449                minMatch: 5,
11450                targetLength: 32,
11451                strategy: ZSTD_btlazy2,
11452            }
11453        },
11454        {
11455            ZSTD_compressionParameters {
11456                windowLog: 22,
11457                chainLog: 22,
11458                hashLog: 22,
11459                searchLog: 5,
11460                minMatch: 5,
11461                targetLength: 48,
11462                strategy: ZSTD_btopt,
11463            }
11464        },
11465        {
11466            ZSTD_compressionParameters {
11467                windowLog: 23,
11468                chainLog: 23,
11469                hashLog: 22,
11470                searchLog: 5,
11471                minMatch: 4,
11472                targetLength: 64,
11473                strategy: ZSTD_btopt,
11474            }
11475        },
11476        {
11477            ZSTD_compressionParameters {
11478                windowLog: 23,
11479                chainLog: 23,
11480                hashLog: 22,
11481                searchLog: 6,
11482                minMatch: 3,
11483                targetLength: 64,
11484                strategy: ZSTD_btultra,
11485            }
11486        },
11487        {
11488            ZSTD_compressionParameters {
11489                windowLog: 23,
11490                chainLog: 24,
11491                hashLog: 22,
11492                searchLog: 7,
11493                minMatch: 3,
11494                targetLength: 256,
11495                strategy: ZSTD_btultra2,
11496            }
11497        },
11498        {
11499            ZSTD_compressionParameters {
11500                windowLog: 25,
11501                chainLog: 25,
11502                hashLog: 23,
11503                searchLog: 7,
11504                minMatch: 3,
11505                targetLength: 256,
11506                strategy: ZSTD_btultra2,
11507            }
11508        },
11509        {
11510            ZSTD_compressionParameters {
11511                windowLog: 26,
11512                chainLog: 26,
11513                hashLog: 24,
11514                searchLog: 7,
11515                minMatch: 3,
11516                targetLength: 512,
11517                strategy: ZSTD_btultra2,
11518            }
11519        },
11520        {
11521            ZSTD_compressionParameters {
11522                windowLog: 27,
11523                chainLog: 27,
11524                hashLog: 25,
11525                searchLog: 9,
11526                minMatch: 3,
11527                targetLength: 999,
11528                strategy: ZSTD_btultra2,
11529            }
11530        },
11531    ],
11532    [
11533        {
11534            ZSTD_compressionParameters {
11535                windowLog: 18,
11536                chainLog: 12,
11537                hashLog: 13,
11538                searchLog: 1,
11539                minMatch: 5,
11540                targetLength: 1,
11541                strategy: ZSTD_fast,
11542            }
11543        },
11544        {
11545            ZSTD_compressionParameters {
11546                windowLog: 18,
11547                chainLog: 13,
11548                hashLog: 14,
11549                searchLog: 1,
11550                minMatch: 6,
11551                targetLength: 0,
11552                strategy: ZSTD_fast,
11553            }
11554        },
11555        {
11556            ZSTD_compressionParameters {
11557                windowLog: 18,
11558                chainLog: 14,
11559                hashLog: 14,
11560                searchLog: 1,
11561                minMatch: 5,
11562                targetLength: 0,
11563                strategy: ZSTD_dfast,
11564            }
11565        },
11566        {
11567            ZSTD_compressionParameters {
11568                windowLog: 18,
11569                chainLog: 16,
11570                hashLog: 16,
11571                searchLog: 1,
11572                minMatch: 4,
11573                targetLength: 0,
11574                strategy: ZSTD_dfast,
11575            }
11576        },
11577        {
11578            ZSTD_compressionParameters {
11579                windowLog: 18,
11580                chainLog: 16,
11581                hashLog: 17,
11582                searchLog: 3,
11583                minMatch: 5,
11584                targetLength: 2,
11585                strategy: ZSTD_greedy,
11586            }
11587        },
11588        {
11589            ZSTD_compressionParameters {
11590                windowLog: 18,
11591                chainLog: 17,
11592                hashLog: 18,
11593                searchLog: 5,
11594                minMatch: 5,
11595                targetLength: 2,
11596                strategy: ZSTD_greedy,
11597            }
11598        },
11599        {
11600            ZSTD_compressionParameters {
11601                windowLog: 18,
11602                chainLog: 18,
11603                hashLog: 19,
11604                searchLog: 3,
11605                minMatch: 5,
11606                targetLength: 4,
11607                strategy: ZSTD_lazy,
11608            }
11609        },
11610        {
11611            ZSTD_compressionParameters {
11612                windowLog: 18,
11613                chainLog: 18,
11614                hashLog: 19,
11615                searchLog: 4,
11616                minMatch: 4,
11617                targetLength: 4,
11618                strategy: ZSTD_lazy,
11619            }
11620        },
11621        {
11622            ZSTD_compressionParameters {
11623                windowLog: 18,
11624                chainLog: 18,
11625                hashLog: 19,
11626                searchLog: 4,
11627                minMatch: 4,
11628                targetLength: 8,
11629                strategy: ZSTD_lazy2,
11630            }
11631        },
11632        {
11633            ZSTD_compressionParameters {
11634                windowLog: 18,
11635                chainLog: 18,
11636                hashLog: 19,
11637                searchLog: 5,
11638                minMatch: 4,
11639                targetLength: 8,
11640                strategy: ZSTD_lazy2,
11641            }
11642        },
11643        {
11644            ZSTD_compressionParameters {
11645                windowLog: 18,
11646                chainLog: 18,
11647                hashLog: 19,
11648                searchLog: 6,
11649                minMatch: 4,
11650                targetLength: 8,
11651                strategy: ZSTD_lazy2,
11652            }
11653        },
11654        {
11655            ZSTD_compressionParameters {
11656                windowLog: 18,
11657                chainLog: 18,
11658                hashLog: 19,
11659                searchLog: 5,
11660                minMatch: 4,
11661                targetLength: 12,
11662                strategy: ZSTD_btlazy2,
11663            }
11664        },
11665        {
11666            ZSTD_compressionParameters {
11667                windowLog: 18,
11668                chainLog: 19,
11669                hashLog: 19,
11670                searchLog: 7,
11671                minMatch: 4,
11672                targetLength: 12,
11673                strategy: ZSTD_btlazy2,
11674            }
11675        },
11676        {
11677            ZSTD_compressionParameters {
11678                windowLog: 18,
11679                chainLog: 18,
11680                hashLog: 19,
11681                searchLog: 4,
11682                minMatch: 4,
11683                targetLength: 16,
11684                strategy: ZSTD_btopt,
11685            }
11686        },
11687        {
11688            ZSTD_compressionParameters {
11689                windowLog: 18,
11690                chainLog: 18,
11691                hashLog: 19,
11692                searchLog: 4,
11693                minMatch: 3,
11694                targetLength: 32,
11695                strategy: ZSTD_btopt,
11696            }
11697        },
11698        {
11699            ZSTD_compressionParameters {
11700                windowLog: 18,
11701                chainLog: 18,
11702                hashLog: 19,
11703                searchLog: 6,
11704                minMatch: 3,
11705                targetLength: 128,
11706                strategy: ZSTD_btopt,
11707            }
11708        },
11709        {
11710            ZSTD_compressionParameters {
11711                windowLog: 18,
11712                chainLog: 19,
11713                hashLog: 19,
11714                searchLog: 6,
11715                minMatch: 3,
11716                targetLength: 128,
11717                strategy: ZSTD_btultra,
11718            }
11719        },
11720        {
11721            ZSTD_compressionParameters {
11722                windowLog: 18,
11723                chainLog: 19,
11724                hashLog: 19,
11725                searchLog: 8,
11726                minMatch: 3,
11727                targetLength: 256,
11728                strategy: ZSTD_btultra,
11729            }
11730        },
11731        {
11732            ZSTD_compressionParameters {
11733                windowLog: 18,
11734                chainLog: 19,
11735                hashLog: 19,
11736                searchLog: 6,
11737                minMatch: 3,
11738                targetLength: 128,
11739                strategy: ZSTD_btultra2,
11740            }
11741        },
11742        {
11743            ZSTD_compressionParameters {
11744                windowLog: 18,
11745                chainLog: 19,
11746                hashLog: 19,
11747                searchLog: 8,
11748                minMatch: 3,
11749                targetLength: 256,
11750                strategy: ZSTD_btultra2,
11751            }
11752        },
11753        {
11754            ZSTD_compressionParameters {
11755                windowLog: 18,
11756                chainLog: 19,
11757                hashLog: 19,
11758                searchLog: 10,
11759                minMatch: 3,
11760                targetLength: 512,
11761                strategy: ZSTD_btultra2,
11762            }
11763        },
11764        {
11765            ZSTD_compressionParameters {
11766                windowLog: 18,
11767                chainLog: 19,
11768                hashLog: 19,
11769                searchLog: 12,
11770                minMatch: 3,
11771                targetLength: 512,
11772                strategy: ZSTD_btultra2,
11773            }
11774        },
11775        {
11776            ZSTD_compressionParameters {
11777                windowLog: 18,
11778                chainLog: 19,
11779                hashLog: 19,
11780                searchLog: 13,
11781                minMatch: 3,
11782                targetLength: 999,
11783                strategy: ZSTD_btultra2,
11784            }
11785        },
11786    ],
11787    [
11788        {
11789            ZSTD_compressionParameters {
11790                windowLog: 17,
11791                chainLog: 12,
11792                hashLog: 12,
11793                searchLog: 1,
11794                minMatch: 5,
11795                targetLength: 1,
11796                strategy: ZSTD_fast,
11797            }
11798        },
11799        {
11800            ZSTD_compressionParameters {
11801                windowLog: 17,
11802                chainLog: 12,
11803                hashLog: 13,
11804                searchLog: 1,
11805                minMatch: 6,
11806                targetLength: 0,
11807                strategy: ZSTD_fast,
11808            }
11809        },
11810        {
11811            ZSTD_compressionParameters {
11812                windowLog: 17,
11813                chainLog: 13,
11814                hashLog: 15,
11815                searchLog: 1,
11816                minMatch: 5,
11817                targetLength: 0,
11818                strategy: ZSTD_fast,
11819            }
11820        },
11821        {
11822            ZSTD_compressionParameters {
11823                windowLog: 17,
11824                chainLog: 15,
11825                hashLog: 16,
11826                searchLog: 2,
11827                minMatch: 5,
11828                targetLength: 0,
11829                strategy: ZSTD_dfast,
11830            }
11831        },
11832        {
11833            ZSTD_compressionParameters {
11834                windowLog: 17,
11835                chainLog: 17,
11836                hashLog: 17,
11837                searchLog: 2,
11838                minMatch: 4,
11839                targetLength: 0,
11840                strategy: ZSTD_dfast,
11841            }
11842        },
11843        {
11844            ZSTD_compressionParameters {
11845                windowLog: 17,
11846                chainLog: 16,
11847                hashLog: 17,
11848                searchLog: 3,
11849                minMatch: 4,
11850                targetLength: 2,
11851                strategy: ZSTD_greedy,
11852            }
11853        },
11854        {
11855            ZSTD_compressionParameters {
11856                windowLog: 17,
11857                chainLog: 16,
11858                hashLog: 17,
11859                searchLog: 3,
11860                minMatch: 4,
11861                targetLength: 4,
11862                strategy: ZSTD_lazy,
11863            }
11864        },
11865        {
11866            ZSTD_compressionParameters {
11867                windowLog: 17,
11868                chainLog: 16,
11869                hashLog: 17,
11870                searchLog: 3,
11871                minMatch: 4,
11872                targetLength: 8,
11873                strategy: ZSTD_lazy2,
11874            }
11875        },
11876        {
11877            ZSTD_compressionParameters {
11878                windowLog: 17,
11879                chainLog: 16,
11880                hashLog: 17,
11881                searchLog: 4,
11882                minMatch: 4,
11883                targetLength: 8,
11884                strategy: ZSTD_lazy2,
11885            }
11886        },
11887        {
11888            ZSTD_compressionParameters {
11889                windowLog: 17,
11890                chainLog: 16,
11891                hashLog: 17,
11892                searchLog: 5,
11893                minMatch: 4,
11894                targetLength: 8,
11895                strategy: ZSTD_lazy2,
11896            }
11897        },
11898        {
11899            ZSTD_compressionParameters {
11900                windowLog: 17,
11901                chainLog: 16,
11902                hashLog: 17,
11903                searchLog: 6,
11904                minMatch: 4,
11905                targetLength: 8,
11906                strategy: ZSTD_lazy2,
11907            }
11908        },
11909        {
11910            ZSTD_compressionParameters {
11911                windowLog: 17,
11912                chainLog: 17,
11913                hashLog: 17,
11914                searchLog: 5,
11915                minMatch: 4,
11916                targetLength: 8,
11917                strategy: ZSTD_btlazy2,
11918            }
11919        },
11920        {
11921            ZSTD_compressionParameters {
11922                windowLog: 17,
11923                chainLog: 18,
11924                hashLog: 17,
11925                searchLog: 7,
11926                minMatch: 4,
11927                targetLength: 12,
11928                strategy: ZSTD_btlazy2,
11929            }
11930        },
11931        {
11932            ZSTD_compressionParameters {
11933                windowLog: 17,
11934                chainLog: 18,
11935                hashLog: 17,
11936                searchLog: 3,
11937                minMatch: 4,
11938                targetLength: 12,
11939                strategy: ZSTD_btopt,
11940            }
11941        },
11942        {
11943            ZSTD_compressionParameters {
11944                windowLog: 17,
11945                chainLog: 18,
11946                hashLog: 17,
11947                searchLog: 4,
11948                minMatch: 3,
11949                targetLength: 32,
11950                strategy: ZSTD_btopt,
11951            }
11952        },
11953        {
11954            ZSTD_compressionParameters {
11955                windowLog: 17,
11956                chainLog: 18,
11957                hashLog: 17,
11958                searchLog: 6,
11959                minMatch: 3,
11960                targetLength: 256,
11961                strategy: ZSTD_btopt,
11962            }
11963        },
11964        {
11965            ZSTD_compressionParameters {
11966                windowLog: 17,
11967                chainLog: 18,
11968                hashLog: 17,
11969                searchLog: 6,
11970                minMatch: 3,
11971                targetLength: 128,
11972                strategy: ZSTD_btultra,
11973            }
11974        },
11975        {
11976            ZSTD_compressionParameters {
11977                windowLog: 17,
11978                chainLog: 18,
11979                hashLog: 17,
11980                searchLog: 8,
11981                minMatch: 3,
11982                targetLength: 256,
11983                strategy: ZSTD_btultra,
11984            }
11985        },
11986        {
11987            ZSTD_compressionParameters {
11988                windowLog: 17,
11989                chainLog: 18,
11990                hashLog: 17,
11991                searchLog: 10,
11992                minMatch: 3,
11993                targetLength: 512,
11994                strategy: ZSTD_btultra,
11995            }
11996        },
11997        {
11998            ZSTD_compressionParameters {
11999                windowLog: 17,
12000                chainLog: 18,
12001                hashLog: 17,
12002                searchLog: 5,
12003                minMatch: 3,
12004                targetLength: 256,
12005                strategy: ZSTD_btultra2,
12006            }
12007        },
12008        {
12009            ZSTD_compressionParameters {
12010                windowLog: 17,
12011                chainLog: 18,
12012                hashLog: 17,
12013                searchLog: 7,
12014                minMatch: 3,
12015                targetLength: 512,
12016                strategy: ZSTD_btultra2,
12017            }
12018        },
12019        {
12020            ZSTD_compressionParameters {
12021                windowLog: 17,
12022                chainLog: 18,
12023                hashLog: 17,
12024                searchLog: 9,
12025                minMatch: 3,
12026                targetLength: 512,
12027                strategy: ZSTD_btultra2,
12028            }
12029        },
12030        {
12031            ZSTD_compressionParameters {
12032                windowLog: 17,
12033                chainLog: 18,
12034                hashLog: 17,
12035                searchLog: 11,
12036                minMatch: 3,
12037                targetLength: 999,
12038                strategy: ZSTD_btultra2,
12039            }
12040        },
12041    ],
12042    [
12043        {
12044            ZSTD_compressionParameters {
12045                windowLog: 14,
12046                chainLog: 12,
12047                hashLog: 13,
12048                searchLog: 1,
12049                minMatch: 5,
12050                targetLength: 1,
12051                strategy: ZSTD_fast,
12052            }
12053        },
12054        {
12055            ZSTD_compressionParameters {
12056                windowLog: 14,
12057                chainLog: 14,
12058                hashLog: 15,
12059                searchLog: 1,
12060                minMatch: 5,
12061                targetLength: 0,
12062                strategy: ZSTD_fast,
12063            }
12064        },
12065        {
12066            ZSTD_compressionParameters {
12067                windowLog: 14,
12068                chainLog: 14,
12069                hashLog: 15,
12070                searchLog: 1,
12071                minMatch: 4,
12072                targetLength: 0,
12073                strategy: ZSTD_fast,
12074            }
12075        },
12076        {
12077            ZSTD_compressionParameters {
12078                windowLog: 14,
12079                chainLog: 14,
12080                hashLog: 15,
12081                searchLog: 2,
12082                minMatch: 4,
12083                targetLength: 0,
12084                strategy: ZSTD_dfast,
12085            }
12086        },
12087        {
12088            ZSTD_compressionParameters {
12089                windowLog: 14,
12090                chainLog: 14,
12091                hashLog: 14,
12092                searchLog: 4,
12093                minMatch: 4,
12094                targetLength: 2,
12095                strategy: ZSTD_greedy,
12096            }
12097        },
12098        {
12099            ZSTD_compressionParameters {
12100                windowLog: 14,
12101                chainLog: 14,
12102                hashLog: 14,
12103                searchLog: 3,
12104                minMatch: 4,
12105                targetLength: 4,
12106                strategy: ZSTD_lazy,
12107            }
12108        },
12109        {
12110            ZSTD_compressionParameters {
12111                windowLog: 14,
12112                chainLog: 14,
12113                hashLog: 14,
12114                searchLog: 4,
12115                minMatch: 4,
12116                targetLength: 8,
12117                strategy: ZSTD_lazy2,
12118            }
12119        },
12120        {
12121            ZSTD_compressionParameters {
12122                windowLog: 14,
12123                chainLog: 14,
12124                hashLog: 14,
12125                searchLog: 6,
12126                minMatch: 4,
12127                targetLength: 8,
12128                strategy: ZSTD_lazy2,
12129            }
12130        },
12131        {
12132            ZSTD_compressionParameters {
12133                windowLog: 14,
12134                chainLog: 14,
12135                hashLog: 14,
12136                searchLog: 8,
12137                minMatch: 4,
12138                targetLength: 8,
12139                strategy: ZSTD_lazy2,
12140            }
12141        },
12142        {
12143            ZSTD_compressionParameters {
12144                windowLog: 14,
12145                chainLog: 15,
12146                hashLog: 14,
12147                searchLog: 5,
12148                minMatch: 4,
12149                targetLength: 8,
12150                strategy: ZSTD_btlazy2,
12151            }
12152        },
12153        {
12154            ZSTD_compressionParameters {
12155                windowLog: 14,
12156                chainLog: 15,
12157                hashLog: 14,
12158                searchLog: 9,
12159                minMatch: 4,
12160                targetLength: 8,
12161                strategy: ZSTD_btlazy2,
12162            }
12163        },
12164        {
12165            ZSTD_compressionParameters {
12166                windowLog: 14,
12167                chainLog: 15,
12168                hashLog: 14,
12169                searchLog: 3,
12170                minMatch: 4,
12171                targetLength: 12,
12172                strategy: ZSTD_btopt,
12173            }
12174        },
12175        {
12176            ZSTD_compressionParameters {
12177                windowLog: 14,
12178                chainLog: 15,
12179                hashLog: 14,
12180                searchLog: 4,
12181                minMatch: 3,
12182                targetLength: 24,
12183                strategy: ZSTD_btopt,
12184            }
12185        },
12186        {
12187            ZSTD_compressionParameters {
12188                windowLog: 14,
12189                chainLog: 15,
12190                hashLog: 14,
12191                searchLog: 5,
12192                minMatch: 3,
12193                targetLength: 32,
12194                strategy: ZSTD_btultra,
12195            }
12196        },
12197        {
12198            ZSTD_compressionParameters {
12199                windowLog: 14,
12200                chainLog: 15,
12201                hashLog: 15,
12202                searchLog: 6,
12203                minMatch: 3,
12204                targetLength: 64,
12205                strategy: ZSTD_btultra,
12206            }
12207        },
12208        {
12209            ZSTD_compressionParameters {
12210                windowLog: 14,
12211                chainLog: 15,
12212                hashLog: 15,
12213                searchLog: 7,
12214                minMatch: 3,
12215                targetLength: 256,
12216                strategy: ZSTD_btultra,
12217            }
12218        },
12219        {
12220            ZSTD_compressionParameters {
12221                windowLog: 14,
12222                chainLog: 15,
12223                hashLog: 15,
12224                searchLog: 5,
12225                minMatch: 3,
12226                targetLength: 48,
12227                strategy: ZSTD_btultra2,
12228            }
12229        },
12230        {
12231            ZSTD_compressionParameters {
12232                windowLog: 14,
12233                chainLog: 15,
12234                hashLog: 15,
12235                searchLog: 6,
12236                minMatch: 3,
12237                targetLength: 128,
12238                strategy: ZSTD_btultra2,
12239            }
12240        },
12241        {
12242            ZSTD_compressionParameters {
12243                windowLog: 14,
12244                chainLog: 15,
12245                hashLog: 15,
12246                searchLog: 7,
12247                minMatch: 3,
12248                targetLength: 256,
12249                strategy: ZSTD_btultra2,
12250            }
12251        },
12252        {
12253            ZSTD_compressionParameters {
12254                windowLog: 14,
12255                chainLog: 15,
12256                hashLog: 15,
12257                searchLog: 8,
12258                minMatch: 3,
12259                targetLength: 256,
12260                strategy: ZSTD_btultra2,
12261            }
12262        },
12263        {
12264            ZSTD_compressionParameters {
12265                windowLog: 14,
12266                chainLog: 15,
12267                hashLog: 15,
12268                searchLog: 8,
12269                minMatch: 3,
12270                targetLength: 512,
12271                strategy: ZSTD_btultra2,
12272            }
12273        },
12274        {
12275            ZSTD_compressionParameters {
12276                windowLog: 14,
12277                chainLog: 15,
12278                hashLog: 15,
12279                searchLog: 9,
12280                minMatch: 3,
12281                targetLength: 512,
12282                strategy: ZSTD_btultra2,
12283            }
12284        },
12285        {
12286            ZSTD_compressionParameters {
12287                windowLog: 14,
12288                chainLog: 15,
12289                hashLog: 15,
12290                searchLog: 10,
12291                minMatch: 3,
12292                targetLength: 999,
12293                strategy: ZSTD_btultra2,
12294            }
12295        },
12296    ],
12297];
12298
12299unsafe fn ZSTD_dedicatedDictSearch_getCParams(
12300    compressionLevel: core::ffi::c_int,
12301    dictSize: size_t,
12302) -> ZSTD_compressionParameters {
12303    let mut cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
12304    if let 3..=5 = cParams.strategy as core::ffi::c_uint {
12305        cParams.hashLog =
12306            (cParams.hashLog).wrapping_add(ZSTD_LAZY_DDSS_BUCKET_LOG as core::ffi::c_uint);
12307    }
12308    cParams
12309}
12310unsafe fn ZSTD_getCParams_internal(
12311    compressionLevel: core::ffi::c_int,
12312    srcSizeHint: core::ffi::c_ulonglong,
12313    dictSize: size_t,
12314    mode: ZSTD_CParamMode_e,
12315) -> ZSTD_compressionParameters {
12316    let rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
12317    let tableID = ((rSize <= (256 * ((1) << 10)) as u64) as core::ffi::c_int
12318        + (rSize <= (128 * ((1) << 10)) as u64) as core::ffi::c_int
12319        + (rSize <= (16 * ((1) << 10)) as u64) as core::ffi::c_int) as u32;
12320    let mut row: core::ffi::c_int = 0;
12321    if compressionLevel == 0 {
12322        row = ZSTD_CLEVEL_DEFAULT;
12323    } else if compressionLevel < 0 {
12324        row = 0;
12325    } else if compressionLevel > ZSTD_MAX_CLEVEL {
12326        row = ZSTD_MAX_CLEVEL;
12327    } else {
12328        row = compressionLevel;
12329    }
12330    let mut cp = *(*ZSTD_defaultCParameters.as_ptr().offset(tableID as isize))
12331        .as_ptr()
12332        .offset(row as isize);
12333    if compressionLevel < 0 {
12334        let clampedCompressionLevel = if ZSTD_minCLevel() > compressionLevel {
12335            ZSTD_minCLevel()
12336        } else {
12337            compressionLevel
12338        };
12339        cp.targetLength = -clampedCompressionLevel as core::ffi::c_uint;
12340    }
12341    ZSTD_adjustCParams_internal(
12342        cp,
12343        srcSizeHint,
12344        dictSize,
12345        mode,
12346        ZSTD_ParamSwitch_e::ZSTD_ps_auto,
12347    )
12348}
12349unsafe fn ZSTD_getParams_internal(
12350    compressionLevel: core::ffi::c_int,
12351    srcSizeHint: core::ffi::c_ulonglong,
12352    dictSize: size_t,
12353    mode: ZSTD_CParamMode_e,
12354) -> ZSTD_parameters {
12355    let mut params = ZSTD_parameters {
12356        cParams: ZSTD_compressionParameters {
12357            windowLog: 0,
12358            chainLog: 0,
12359            hashLog: 0,
12360            searchLog: 0,
12361            minMatch: 0,
12362            targetLength: 0,
12363            strategy: 0,
12364        },
12365        fParams: ZSTD_frameParameters {
12366            contentSizeFlag: 0,
12367            checksumFlag: 0,
12368            noDictIDFlag: 0,
12369        },
12370    };
12371    let cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
12372    ptr::write_bytes(
12373        &mut params as *mut ZSTD_parameters as *mut u8,
12374        0,
12375        ::core::mem::size_of::<ZSTD_parameters>(),
12376    );
12377    params.cParams = cParams;
12378    params.fParams.contentSizeFlag = 1;
12379    params
12380}
12381#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_registerSequenceProducer))]
12382pub unsafe extern "C" fn ZSTD_registerSequenceProducer(
12383    zc: *mut ZSTD_CCtx,
12384    extSeqProdState: *mut core::ffi::c_void,
12385    extSeqProdFunc: ZSTD_sequenceProducer_F,
12386) {
12387    ZSTD_CCtxParams_registerSequenceProducer(
12388        &mut (*zc).requestedParams,
12389        extSeqProdState,
12390        extSeqProdFunc,
12391    );
12392}
12393#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_CCtxParams_registerSequenceProducer))]
12394pub unsafe extern "C" fn ZSTD_CCtxParams_registerSequenceProducer(
12395    params: *mut ZSTD_CCtx_params,
12396    extSeqProdState: *mut core::ffi::c_void,
12397    extSeqProdFunc: ZSTD_sequenceProducer_F,
12398) {
12399    if extSeqProdFunc.is_some() {
12400        (*params).extSeqProdFunc = extSeqProdFunc;
12401        (*params).extSeqProdState = extSeqProdState;
12402    } else {
12403        (*params).extSeqProdFunc = None;
12404        (*params).extSeqProdState = core::ptr::null_mut();
12405    }
12406}